<template>
  <div class="table-box">
    <div class="card table-search" style="overflow: hidden;display: flex;justify-content: space-between;">
      <el-form ref="formRef" :model="searchParam" :inline="true" label-width="auto">
        <el-form-item label="自动站：" prop="as_code">
          <el-select v-model="pageable.as_code" filterable placeholder="请搜索自动站" remote reserve-keyword clearable
            style="width: 200px" @change="changeStation">
            <el-option v-for="item in platformList" :key="item.as_code" :label="item.as_code + ' ' + item.as_name"
              :value="item.as_code" />
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="观测时间：" prop="base">
          <div>
            <el-switch v-model="value1" @change="changetype" class="ml-2" inline-prompt active-text="正点"
              inactive-text="分钟" style="margin-right: 10px;" />
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm"
              :format="value1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'" :type="value1 ? 'daterange' : 'datetimerange'"
              range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" :disabled-date="disabledDate"
              @focus="handleFocus" @calendar-change="handleChange" @change="handleDateChange" :editable="false"
              :default-time="[new Date(2000, 1, 1, 0, 0), new Date(2000, 1, 1, new Date().getHours(), 0)]"
              style="width: 300px;"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="getHistoryList" :loading="buttonLoading">查询</el-button>
            <el-button plain @click="resetForm">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="header-button-ri">
        <slot name="toolButton">
          <img class="setting" style="margin-top: 5px;" src="@/assets/images/setting2.png" @click="handleSetting" />
        </slot>
      </div>
    </div>
    <div class="main_list">
      <el-row :gutter="15">
        <template v-if="array.length > 0">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" v-if="windLineArr && windLineArr.length > 0">
            <div class="chart_item zhuti">
              <div style="font-weight: bold;" class="item_title">
                <span>2分钟平均风向 ( ° )/2分钟平均风速 ( m/s )</span>

                <el-icon style="vertical-align: middle;cursor: pointer;" @click="showBig(1, 0, 0)">
                  <Search />
                </el-icon>

              </div>
              <div class="mt5">
                <div ref="wind" class="ve-ring" style="height: 330px"></div>
              </div>
            </div>
          </el-col>
          <template v-for="(item, index) in array" :key="index">
            <el-col :xs="24" :sm="12" :md="8" :lg="8" v-if="item && item.data_id !== 1 && item.data_id !== 2">
              <div class="chart_item zhuti">
                <div style="font-weight: bold;" class="item_title">
                  <span>{{ item.data_name }} ( {{ item.data_unit ? item.data_unit : '' }} )</span>
                </div>
                <div class="mt5">
                  <div :id="'Access' + index" class="ve-ring" style="height: 330px"></div>
                </div>
              </div>
            </el-col>
          </template>

        </template>
        <el-col :span="24" v-else>
          <div class="chart_item zhuti nodata">
            <el-empty style="height: 100%;" description="暂无数据" />
          </div>
        </el-col>

      </el-row>
    </div>
    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <div style="height: 500px;display: flex">
        <el-tabs tab-position="left" class="demo-tabs" style="height: 100%;flex-grow: 1">
          <el-tab-pane label="风">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '风'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="温湿度">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '温湿度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="气压">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '气压'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="降水">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '降水'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="云">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '云'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="能见度">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '能见度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="天气现象">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '天气现象'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="积雪">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '积雪'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="地面温度">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '地面温度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="大气电场">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '大气电场'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="闪电">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '闪电'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="日照">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '日照'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="总辐射">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '总辐射'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="光照度">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '光照度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="水文">
            <div class="container-tag">
              <template v-for="item in elementList" :key="item.id">
                <div v-if="item.data_type === '水文'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                  @click="toggleSelection(item)">{{ item.data_name }}</div>
              </template>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="selected-list-box">
          <div class="disposition-title" style="margin-top: 0px">已选要素</div>
          <div class="selected-list-c" ref="scrollContainer">
            <template v-for="(item, index) in copiedCustomizeColumns" :key="item.id">
              <div :class="selectedItemIndex === index ? 'selected-item-tag-active' : 'selected-item-tag'"
                @click="changeSelected(index)" draggable="true" @dragstart="dragStart($event, index)" @dragover.prevent
                @drop="drop($event, index)">{{ item.data_name }}</div>
            </template>
          </div>
          <div class="button-container">
            <el-button type="primary" plain class="top-left" @click="changeMoveUp">上移</el-button>
            <el-button type="primary" plain class="top-right" @click="changeMoveDown">下移</el-button>
            <el-button type="primary" plain class="bottom-left" @click="changeRemove">移除</el-button>
            <el-button type="primary" plain class="bottom-right" @click="changeCleared">清空</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible" :title="dialogtitle" width="90%">
      <div class="mt5" v-if="showtype == 1">
        <div ref="wind2" class="ve-ring" style="height: 60vh"></div>
      </div>
      <div class="mt5" v-else>
        <div :id="'Access' + clickIndex" class="ve-ring" style="height: 80vh"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="dataSynthesis">
import * as echarts from 'echarts';
import { ElMessage, formatter } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import { ref, computed, onMounted, reactive, watch, onDeactivated, onActivated, nextTick } from "vue";
import { getDataItemList, getPlatformList, getRgDataList, getTacRecordList } from "@/api/modules/allData";
import { Platform } from "@/api/interface";
import { parseTime } from '@/utils/index';
import { isToday, isWithinThirtyMinutes, getTimeStamp, getStamp, isDateFuture, isDateRangeWithinDays } from "@/utils/dateTime";
import { useUserStore } from "@/stores/modules/user";
const buttonLoading = ref(false)
const value1 = ref(true)
const dateRange = ref<[any, any]>([parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}') + ':00']);
const changetype = (e) => {
  if (!e) {
    dateRange.value = [parseTime(getTimeStamp(1), '{y}-{m}-{d} {h}:{i}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')]
  } else {
    dateRange.value = [parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}') + ':00'];
  }
  getHistoryList()
}

const dialogVisible = ref(false)
const clickIndex = ref(null)
const showtype = ref(1)
const dialogtitle = ref('')
const showBig = (type, item, index) => {
  showtype.value = type
  if (type == 1) {
    dialogtitle.value = '2分钟平均风向 ( ° )/2分钟平均风速 ( m/s )'
    dialogVisible.value = true
    nextTick(() => {
      showWind2()
    })
  } else {
    clickIndex.value = index
    dialogtitle.value = item.data_name
    dialogVisible.value = true

    nextTick(() => {
      Access()
    })
  }

}

const dragStart = (event, index) => {
  event.dataTransfer.effectAllowed = 'move';
  // 保存当前拖动的元素索引
  event.dataTransfer.setData('text/plain', index.toString());
};

const drop = (event, index) => {
  const draggedIndex = parseInt(event.dataTransfer.getData('text/plain'));
  // 移动数组中的元素来更新顺序
  const draggedItem = copiedCustomizeColumns.value.splice(draggedIndex, 1)[0];
  copiedCustomizeColumns.value.splice(index, 0, draggedItem);
  selectedItemIndex.value = index
};

const handleDateRangeChange = (newVal) => {
  const [startDate, endDate] = newVal;
  if (endDate && isToday(endDate)) {

    // 获取当前时间的整点
    const currentHour = new Date().getHours();
    const roundedEndDate = new Date(endDate);
    roundedEndDate.setMinutes(0, 0, 0); // 设置分钟、秒、毫秒为0
    const startZeroed = new Date(startDate);
    startZeroed.setHours(0, 0, 0, 0);
    dateRange.value = [parseTime(new Date(startZeroed)), parseTime(new Date(roundedEndDate))];
  } else {
    const noTodayStart = new Date(startDate).setMinutes(0, 0, 0);
    const noTodayEnd = new Date(endDate).setHours(23, 0, 0, 0);
    dateRange.value = [parseTime(new Date(noTodayStart)), parseTime(new Date(noTodayEnd))];

  }
};
const handleDateChange = async (e) => {
  if (isDateFuture(e[0]) || isDateFuture(e[1])) {
    ElMessage.error("不得选择未来的时间");
  } else {
    if (!value1.value) {
      if (isWithinThirtyMinutes(e[0], e[1])) {
        // 获取参数
        getHistoryList()

      } else {
        ElMessage.error("分钟模式下时间间隔不能大于3小时");
      }
    } else {
      if (isDateRangeWithinDays(e[0], e[1], 7)) {
        await handleDateRangeChange(e)
        getHistoryList()
      } else {
        ElMessage.error("正点模式下时间间隔不能大于7天");
      }
    }
  }
}
const pickDay = ref()
const handleFocus = () => {
  pickDay.value = null
}
const limitTime = 1000 * 60 * 60 * 24 * 6

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now() - 8.64e6
}
const handleChange = (val: Date[]) => {
  const [pointDay] = val
  pickDay.value = pointDay
}





// 查询所有人工要素字典表
const elementList = ref<any>([])
//自定义部分表头
const customizeColumns = ref<any>([

]);

const getAllRgDataList = async () => {
  const { data } = await getRgDataList();
  elementList.value = data.list
};
const copiedCustomizeColumns = ref<any>([...customizeColumns.value]);
const sensorList = ref<any>([])
// 被选中当条数据下标
const selectedItemIndex = ref(0)
const scrollContainer = ref<HTMLElement | null>(null);

const changeMoveUp = () => {
  //上移
  if (selectedItemIndex.value > 0) {
    const temp = copiedCustomizeColumns.value[selectedItemIndex.value - 1]
    copiedCustomizeColumns.value[selectedItemIndex.value - 1] = copiedCustomizeColumns.value[selectedItemIndex.value]
    copiedCustomizeColumns.value[selectedItemIndex.value] = temp
    selectedItemIndex.value--

    if (scrollContainer.value) {
      scrollContainer.value.scrollTop -= 50;
    }
  }
}

const changeMoveDown = () => {
  //下移
  if (selectedItemIndex.value < copiedCustomizeColumns.value.length - 1) {
    const temp = copiedCustomizeColumns.value[selectedItemIndex.value + 1]
    copiedCustomizeColumns.value[selectedItemIndex.value + 1] = copiedCustomizeColumns.value[selectedItemIndex.value]
    copiedCustomizeColumns.value[selectedItemIndex.value] = temp
    selectedItemIndex.value++

    if (scrollContainer.value) {
      scrollContainer.value.scrollTop += 50;
    }
  }
}

const changeRemove = () => {
  //删除数据
  if (copiedCustomizeColumns.value.length > 0) {
    const custom = copiedCustomizeColumns.value[selectedItemIndex.value];
    const se_type = custom.se_type
    for (let i = 0; i < sensorList.value.length; i++) {
      if (sensorList.value[i].se_type === se_type) {
        sensorList.value[i].isSelected = false;
      }
    }
    historyColumns.value = historyColumns.value.filter(item => item.data_id !== custom.data_id)

    copiedCustomizeColumns.value.splice(selectedItemIndex.value, 1)
    if (selectedItemIndex.value === copiedCustomizeColumns.value.length) {
      selectedItemIndex.value--
    }

  }
}

const changeCleared = () => {
  //清空所有数据
  selectedItemIndex.value = 0
  historyColumns.value = []
  copiedCustomizeColumns.value = []
  for (let i = 0; i < elementList.value.length; i++) {
    elementList.value[i].isSelected = false;
  }
}

const changeSelected = (index) => {
  selectedItemIndex.value = index
}

// 要素的选中和取消
const toggleSelection = (item) => {

  item.isSelected = !item.isSelected
  if (item.isSelected) {
    //添加
    copiedCustomizeColumns.value.push(item)
    if (item.data_id == 1) {
      historyColumns.value.push({
        data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
        data_id: 2,
        data_type: "风",
        data_item: "ER_FEN_ZHONG_PING_JUN_FENG_XIANG",
        data_name: "2分钟风向",
        data_unit: "°",
        data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
        data_value: "",
        data_order: 0,
        data_condition: 0
      })

    } else if (item.data_id == 2) {
      historyColumns.value.push({
        data_id: 1,
        data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
        data_type: "风",
        data_name: "2分钟风速",
        data_item: "ER_FEN_ZHONG_PING_JUN_FENG_SU",
        data_unit: "m/s",
        data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
        data_value: "",
        data_order: 0,
        data_condition: 0
      })
    }
  } else {
    //删除
    copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== item.data_id);
    historyColumns.value = historyColumns.value.filter(column => column.data_id !== item.data_id);
    if (item.data_id == 1) {
      historyColumns.value = historyColumns.value.filter(column => column.data_id !== 2);
      copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== 2);

    } else if (item.data_id == 2) {
      historyColumns.value = historyColumns.value.filter(column => column.data_id !== 1);
      copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== 1);

    }
  }
}
const handleSetting = () => {
  copiedCustomizeColumns.value = [...customizeColumns.value, ...historyColumns.value].reduce((acc, item) => {
    if (!acc.some(existingItem => existingItem.data_id === item.data_id)) {
      acc.push(item);
    }
    return acc;
  }, []);
  // copiedCustomizeColumns.value = [...customizeColumns.value]
  elementList.value.forEach(element => {
    const column = copiedCustomizeColumns.value.find(col => col.data_id === element.data_id);
    if (column) {
      element.isSelected = true;
    } else {
      element.isSelected = false;
    }
  });

  dialog.title = "列表字段设置"
  dialog.visible = true;
}
const submitForm = () => {
  if (copiedCustomizeColumns.value.length > 7) {
    ElMessage.error("最多选择7个要素！");
    return

  }
  dialog.visible = false;
  customizeColumns.value = [...copiedCustomizeColumns.value]
  // updateColumns()
  // getList()
  // weatherInfo()
  getHistoryList()
  // saveCustomizeColumns()
}

const cancel = () => {
  dialog.visible = false;
}




const formRef = ref()
const wind = ref()
const wind2 = ref()
const pressureLine = ref()
const radio = ref()
const radio2 = ref()


const searchParam = reactive({
  base: undefined,
  date: '',
  switch: true

})

const dialog = reactive<any>({
  visible: false,
  title: ''
});



const pageable = ref({
  data_type: false,
  time_order: 1,
  as_code: undefined,
  data_items: [],
  pageNum: 1,

});
const historyColumns = ref([
  {
    data_id: 202,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "本站气压",
    data_item: "BEN_ZHAN_QI_YA",
    data_unit: "hPa",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 2,
    data_type: "风",
    data_item: "ER_FEN_ZHONG_PING_JUN_FENG_XIANG",
    data_name: "2分钟风向",
    data_unit: "°",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 1,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "风",
    data_name: "2分钟风速",
    data_item: "ER_FEN_ZHONG_PING_JUN_FENG_SU",
    data_unit: "m/s",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },

  {
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 106,
    data_type: "温湿度",
    data_item: "XIANG_DUI_SHI_DU",
    data_name: "相对湿度",
    data_unit: "％",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0,
    isSelected: true
  },
  {
    data_order: 0,
    data_item: "QI_WEN",
    data_unit: "℃",
    data_value: "",
    data_condition: 0,
    data_name: "气温",
    data_id: 101,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "温湿度",
    isSelected: true
  },
  {
    data_type: "降水",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_id: 312,
    data_name: "小时累计降水量(称重)",
    data_condition: 0,
    data_value: "",
    data_unit: "mm",
    data_item: "XIAO_SHI_LEI_JI_JIANG_SHUI_LIANG_CHENG_ZHONG",
    data_order: 0,
    isSelected: true
  },
  {
    data_order: 0,
    data_item: "YI_FEN_ZHONG_PING_JUN_NENG_JIAN_DU",
    data_unit: "m",
    data_value: "",
    data_condition: 0,
    data_name: "1分钟平均能见度",
    data_id: 501,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "能见度",
    isSelected: true
  }
])




const userStore = useUserStore();
const platformList = ref<any>(computed(() => userStore.stations))
const selectPlatform = ref()

const getPlatforms = async () => {
  pageable.value.as_code = platformList.value[0].as_code
  selectPlatform.value = platformList.value[0]
  getHistoryList()
};

const changeStation = () => {
  getHistoryList()
}

//时间戳转换为指定格式的日期字符串
function formatDate(timestamp, type) {
  const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  if (type === 1) {
    return `${month}/${day} ${hours}:${minutes}`;
  } else {
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
}

const array = ref<any>([])
const Access = () => {

  array.value?.forEach((item, i) => {
    // 获取最大值方法
    function calMax(arr) {
      let max = Math.max.apply(null, arr); // 获取最大值方法
      let maxint = Math.ceil(max / 5); // 向上以5的倍数取整
      let maxval = maxint * 5; // 最终设置的最大值
      return maxval; // 输出最大值
    }
    // 获取最小值方法
    function calMin(arr) {
      let min = Math.min.apply(null, arr); // 获取最小值方法
      return min
    }
    // 调用方法，获取数据的最大值&最小值
    let maxData1 = calMax(item.value);
    let minData1 = calMin(item.value);

    let chartDom = document.getElementById("Access" + i);

    if (chartDom) {
      let myChart = echarts.init(chartDom);
      let option;
      option = {

        grid: {
          left: '10',
          right: '10',
          bottom: '3%',
          top: 20,
          containLabel: true
        },

        // X轴
        xAxis: {
          type: 'category',
          splitLine: {
            show: false
          },
          // boundaryGap: false,
          axisTick: {
            alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
          },
          data: timeArr.value,
          axisLabel: {
            formatter: function (value) {
              return value.replace(/ /g, '\n');
            },
            // interval: 0,
          },
          axisLine: {
            onZero: false    //-----------重点
          }
        },
        yAxis: {
          // min: minData1,
          // max: maxData1,
          type: 'value',
          // boundaryGap: [0, '10%']
        },
        // 鼠标悬浮提示
        tooltip: {
          trigger: "axis",
        },

        // 数据
        series: [
          {
            data: item.value,
            name: item.data_name,
            type: "line",
            smooth: true,
            lineStyle: {
              color: '#157aea',
              width: 1,
            },
            itemStyle: {
              normal: {
                color: '#157aea'

              },

            }
          },

        ]
      };
      myChart.setOption(option)
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    }

    // option && myChart.setOption(option);


  })
};
const timeArr = ref<any>([])
const windLineArr = ref<any>([]) // 2分钟风速风向
const getHistoryList = async () => {
  buttonLoading.value = true
  if (isDateFuture(dateRange.value[0]) || isDateFuture(dateRange.value[1])) {
    ElMessage.error("不得选择未来的时间");
    return false;
  }

  const arr = [...customizeColumns.value, ...historyColumns.value].reduce((acc, item) => {
    if (!acc.some(existingItem => existingItem.data_id === item.data_id)) {
      acc.push(item);
    }
    return acc;
  }, []);
  const { data } = await getDataItemList({ time_order: 1, as_code_list: [pageable.value.as_code], data_items: arr, data_type: false, time_space: value1.value ? 60 : 1, end_time: getStamp(dateRange.value[1]), begin_time: getStamp(dateRange.value[0]) });
  timeArr.value = data.list?.map(item => {
    return formatDate(item.data_time_i, 1)
  })

  let arr1 = arr.map(item => { return item.data_id })
  // 初始化一个空对象来存储归类后的数据
  const resultMap = {};

  // 遍历原数组
  data.list?.forEach(obj => {
    obj.data_list.forEach(item => {
      // 将data_value转换为数字
      const value = parseFloat(item.data_value);

      // 初始化或更新resultMap中的对应项
      if (!resultMap[item.data_id]) {
        resultMap[item.data_id] = {
          data_id: item.data_id,
          data_name: item.data_name,
          data_unit: item.data_unit,
          value: [value]
        };
      } else {
        resultMap[item.data_id].value.push(value);
      }
    });
  });
  let arr2 = Object.values(resultMap);

  if (arr2.length > 0) {
    // 创建一个映射来存储 arr2 中的对象
    const map = new Map(arr2.map(item => [item.data_id, item]));

    // 根据 arr1 的顺序来重新排列对象
    array.value = arr1.map(data_id => map.get(data_id));
  } else {
    array.value = []
  }

  nextTick(() => {
    if (array.value.length > 0) Access();
  });
  if (arr.some(item => item.data_id === 1)) {
    windLineArr.value = data.list?.map(item => {
      return {
        value: item[1],
        symbolRotate: adjustValue(item[2]),
        symbolRotateStr: item[2]
      }
    })

    nextTick(() => {
      if (array.value.length > 0) showWind()
    })
  } else {
    windLineArr.value = []
  }
  buttonLoading.value = false
};
function adjustValue(value) {
  if (value === 'C') {
    return 0
  } else if (value <= 180) {
    return -value - 180;
  } else {
    return 180 - value;
  }
}
const globalStore = useGlobalStore();
const isDark = computed(() => globalStore.isDark);

// resetForm
const resetForm = () => {
  dateRange.value = [parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}') + ':00'];
  value1.value = true
  pageable.value.as_code = platformList.value[0].as_code
  getHistoryList()

};

const showWind = () => {

  let mychart = echarts.init(wind.value);
  let option = {
    title: {
      text: '暂无数据',
      show: !timeArr.value ? true : false,
      x: 'center',
      y: 'center',
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal',
      }
    },

    grid: {
      left: '10',
      right: '10',
      bottom: '3%',
      top: 20,
      containLabel: true
    },
    // X轴
    xAxis: {
      type: 'category',
      splitLine: {
        show: false
      },
      boundaryGap: true,
      axisTick: {
        alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
      },
      data: timeArr.value,
      axisLabel: {
        // interval: 4,
        formatter: function (value) {
          // if (value.index % 4 === 0) {
          // 	return value.replace(/ /g, '\n');
          // } else {
          // 	return '';
          // }
          return value.replace(/ /g, '\n');
        },

      },
    },
    // Y轴
    // yAxis: {
    // 	type: 'value',
    // 	// name: "风速(m/s)",
    // },
    yAxis: {
      boundaryGap: [0, '20%'],
      type: 'value'
    },
    // 鼠标悬浮提示
    tooltip: {
      trigger: "axis",
      formatter(params) {
        let aa = ''
        if (params[0].data) {
          aa = params[0].data.symbolRotateStr === 'c' || params[0].data.symbolRotateStr === 'C' ? 'C' : params[0].data.symbolRotateStr + '°'
        } else {
          aa = '--'
        }
        let tip =
          "时间:" +
          params[0].axisValue +
          "<br/>风速:" +
          (params[0].value ? params[0].value : "--") +
          "m/s<br/>风向:" +
          (aa)
        return tip;
      },
    },
    // 数据
    series: [{
      data: windLineArr.value,
      type: 'line',
      smooth: true, //这句就是让曲线变平滑的
      symbol: function (params) {
        if (Number(params) < 0.3) {
          return
        } else {
          return 'path://M4.866,0,0,15.193l4.866-4.449L9.738,15.2Z'
        }
      },
      symbolSize: function (params) {
        if (Number(params) < 0.3) {
          return 5
        } else {
          return 11
        }
      },
      //折线样式
      lineStyle: {
        color: '#a5cfff',
        width: 1,
      },
      // label: {
      // 	normal: {
      // 		formatter: '{c}',
      // 		show: false,
      // 		position: 'top',
      // 		distance: 15
      // 	}
      // },
      itemStyle: {
        normal: {

        },
      },
    }]
  };

  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}

const showWind2 = () => {

  let mychart = echarts.init(wind2.value);
  let option = {
    title: {
      text: '暂无数据',
      show: !timeArr.value ? true : false,
      x: 'center',
      y: 'center',
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal',
      }
    },

    grid: {
      left: '10',
      right: '10',
      bottom: '90',
      top: 20,
      containLabel: true
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 50
      },
      {
        type: 'slider',

        left: '100',
        right: '100'


      }
    ],
    // X轴
    xAxis: {
      type: 'category',
      splitLine: {
        show: false
      },
      boundaryGap: true,
      axisTick: {
        alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
      },
      data: timeArr.value,
      axisLabel: {
        // interval: 4,
        formatter: function (value) {
          // if (value.index % 4 === 0) {
          // 	return value.replace(/ /g, '\n');
          // } else {
          // 	return '';
          // }
          return value.replace(/ /g, '\n');
        },

      },
    },
    // Y轴
    // yAxis: {
    // 	type: 'value',
    // 	// name: "风速(m/s)",
    // },
    yAxis: {
      boundaryGap: [0, '20%'],
      type: 'value'
    },
    // 鼠标悬浮提示
    tooltip: {
      trigger: "axis",
      formatter(params) {
        let tip =
          "时间:" +
          params[0].axisValue +
          "<br/>风速:" +
          (params[0].value ? params[0].value : "--") +
          "m/s<br/>风向:" +
          (params[0].data ? params[0].data.symbolRotateStr + '°' : "--")
        return tip;
      },
    },
    // 数据
    series: [{
      data: windLineArr.value,
      type: 'line',
      smooth: true, //这句就是让曲线变平滑的
      symbol: function (params) {
        if (Number(params) < 0.3) {
          return
        } else {
          return 'path://M4.866,0,0,15.193l4.866-4.449L9.738,15.2Z'
        }
      },
      symbolSize: function (params) {
        if (Number(params) < 0.3) {
          return 5
        } else {
          return 14
        }
      },
      //折线样式
      lineStyle: {
        color: '#a5cfff',
        width: 1,
      },
      // label: {
      // 	normal: {
      // 		formatter: '{c}',
      // 		show: false,
      // 		position: 'top',
      // 		distance: 15
      // 	}
      // },
      itemStyle: {
        normal: {

        },
      },
    }]
  };

  mychart.setOption(option)
  window.addEventListener("resize", function () {
    mychart.resize();
  });
}





// 保存customizeColumns数组到localStorage
function saveCustomizeColumns() {
  const jsonString = JSON.stringify(customizeColumns.value);
  localStorage.setItem('customizeColumns', jsonString);
}

// 从localStorage中获取customizeColumns数组
function loadCustomizeColumns() {

  const jsonString = localStorage.getItem('customizeColumns');

  if (jsonString) {
    customizeColumns.value = JSON.parse(jsonString);
  }
}


onMounted(() => {
  // loadCustomizeColumns()

  getPlatforms()

  getAllRgDataList()


  // nextTick(() => {
  // 	Access();
  // });
  // showWind()
  // showPressureLine()
  // showRadio()
  // showRadio2()

})


</script>
<style scoped lang="scss">
.el-row .el-col {
  margin-bottom: 15px;
}


.main_list {
  background: transparent !important;
  box-shadow: none !important;
  padding: 0 !important;
  height: calc(100vh - 150px);
  margin-bottom: 10px;
  overflow-y: scroll;
  overflow-x: hidden;


  .chart_item {
    border-radius: 10px;
    padding: 10px;
    background-color: #fff;
    // height: 100%;
    // margin-bottom: 15px;


    .item_title {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .info_box {
    .info_title {
      color: #999999;
      font-size: 16px;
    }

    .info_content {
      height: 40px;
      font-weight: bold;
      color: #000;
      font-size: 26px;
    }
  }

}

.el-button.is-link {
  height: 32px;
}

.nodata {
  height: calc(100vh - 220px);
}
</style>
