<template>
  <div class="table-box">
    <div class="card table-main">
      <!-- 表格头部 操作按钮 -->
      <div class="table-header">
        <div class="header-button-lf">
          <el-form :model="pageable" label-width="auto" :inline="true">
            <el-form-item label="自动站:">
              <el-checkbox v-model="isStand" @change="changeStand" label="多站" />
              <!--多选自动站-->
              <SelectItem v-show="isStand" :select-data="selectedData" :select-list="platformList" :is-checkbox="false"
                          @update:selectedItems="selectedItems" style="width: 200px;margin:0 10px"> </SelectItem>

              <!--单站自动站选择-->
              <SelectItem v-show="!isStand" :select-data="selectedData" :select-list="platformList" :is-checkbox="true"
                          @update:selectedItems="selectedItems2" style="width: 200px;margin:0 10px"> </SelectItem>

              <!--正点和分钟-->
              <el-switch v-model="hot" inline-prompt active-text="正点" size="default" inactive-text="分钟" @change="changeHot"  style="margin-right: 20px;"/>

              <!--数据密度-->
              <el-form-item v-if="!hot" label="数据密度:">
                <el-select v-model="pageable.time_space" style="width: 100px" filterable placeholder="请选择" clearable>
                  <el-option v-for="item in timeSpaceList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <!--多选自动站 观测时间-->
              <el-form-item label="观测时间:" v-if="isStand">
                <el-date-picker v-if="hot" v-model="multiTime" style="margin-left: 10px" type="datetime"
                                popper-class="tpc" format="YYYY-MM-DD HH" placeholder="选择日期时间" @change="changeMultiTime">
                </el-date-picker>
                <el-date-picker v-if="!hot" v-model="multiTime" style="margin-left: 10px" type="datetime"
                                @change="changeMultiTime" format="YYYY-MM-DD HH:mm" placeholder="选择日期时间">
                </el-date-picker>

                <!-- 减少小时或分钟 -->
                <el-button style="margin: 0 5px" @click="decreaseDay2" icon="ArrowLeft"></el-button>
                <!-- 增加小时或分钟  -->
                <el-button @click="increaseDay2" icon="ArrowRight" :disabled="isIncreaseDay"></el-button>
              </el-form-item>

              <!--单选自动站 观测时间-->
              <el-form-item label="观测时间:" v-if="!isStand">
                <span class="form-item__label2">日界:</span>
                <el-switch v-model="points" inline-prompt active-text="0点" size="default" inactive-text="18点" @change="changePoints" />
                <el-date-picker style="margin-left: 10px" v-model="singleTime" type="date" placeholder="请选择" @change="changeTime" />
                <!-- 减少一天 -->
                <el-button style="margin: 0 5px" @click="decreaseDay" icon="ArrowLeft"></el-button>
                <!-- 增加一天 -->
                <el-button @click="increaseDay" icon="ArrowRight" :disabled="isIncreaseDay"></el-button>
              </el-form-item>

            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"> 查询 </el-button>
              <el-button style="margin-left: 10px" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="header-button-ri">
          <slot name="toolButton">
            <img class="setting" src="@/assets/images/setting2.png" @click="handleSetting" />
          </slot>
        </div>
      </div>
      <!-- 表格主体 -->
      <el-table stripe ref="tableRef" :border="true" :data="processTableData" size="small"
        @sort-change="handleSortChange">
        <el-table-column align="left" label="序号" width="45px" :show-overflow-tooltip="true" fixed >
          <template #default="scope">
            {{ (pageable.pageNum - 1) * pageable.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <template v-for="item in columns" :key="item">
          <el-table-column :fixed="item.fixed" v-bind="item" :align="item.align ?? 'left'" :reserve-selection="item.type == 'selection'"
            :sortable="item.sortable" :show-overflow-tooltip="true">
            <template #default="scope">
              <template v-if="item.prop === 'data_time_i'">
                {{ formatDate(scope.row.data_time_i) }}
              </template>
            </template>
          </el-table-column>
        </template>
        <!-- 无数据 -->
        <template #empty>
          <div class="table-empty">
            <slot name="empty">
              <img src="@/assets/images/notData.png" alt="notData" />
              <div>暂无数据</div>
            </slot>
          </div>
        </template>
      </el-table>
      <!-- 分页组件 -->
      <Pagination :pageable="pageable" :handle-size-change="handleSizeChange"
        :handle-current-change="handleCurrentChange" />
    </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">
            <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>
  </div>
</template>

<script setup lang="ts" name="useProTable">
import SelectItem from "@/components/SelectItem/index.vue";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ref, reactive, onMounted, onDeactivated, onActivated, computed } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { ElNotification, ElTable } from "element-plus";
import { getDataItemList, getPlatformList, getRgDataList } from "@/api/modules/allData";
import { Platform } from "@/api/interface";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();
const userForm = computed(() => userStore.userInfo);
const tableRef = ref<InstanceType<typeof ElTable>>();
const dialog = reactive<any>({
  visible: false,
  title: ''
});

const changeStand = () => {
  if(isStand.value){
    initMany()
  }else {
    initSingle()
  }
  getList()
}

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 cancel = () => {
  dialog.visible = false;
}

const handleSortChange = ({ column, prop, order }) => {


  // Reset sorting if order is null
  if (order === null) {
    pageable.value.time_order = 0;
    pageable.value.data_order = [];
    getList();
    return;
  }

  // Handle time sorting
  if (prop === 'data_time_i') {
    pageable.value.time_order = order === 'descending' ? 0 : 1;
    pageable.value.data_order = [];
    getList();
    return;
  }

  // Default time order to 0
  pageable.value.time_order = 0;
  pageable.value.data_order = [];

  // Find the item with the matching data_id and update its order
  const item = pageable.value.data_items.find(item => item.data_id === prop);
  if (item) {
    item.data_order = order === 'descending' ? 0 : 1;
    pageable.value.data_order = [item];
    getList();
  }
};


const timeSpaceList = [
  {
    value: 1,
    label: '1分钟',
  },
  {
    value: 5,
    label: '5分钟',
  },
  {
    value: 10,
    label: '10分钟',
  }
]

const sensorList = ref<any>([])
// 被选中当条数据下标
const selectedItemIndex = ref(0)


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--
  }
}

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++
  }
}

const changeRemove = () => {
  //删除数据
  if (copiedCustomizeColumns.value.length > 0) {
    const custom = copiedCustomizeColumns.value[selectedItemIndex.value];
    const data_id = custom.data_id
    for (let i = 0; i < elementList.value.length; i++) {
      if (elementList.value[i].data_id === data_id) {
        elementList.value[i].isSelected = false;
      }
    }
    copiedCustomizeColumns.value.splice(selectedItemIndex.value, 1)
    if (selectedItemIndex.value === copiedCustomizeColumns.value.length) {
      selectedItemIndex.value--
    }

  }
}

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

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


const pageable = ref<any>({
  data_type: false,
  time_order: 0,
  time_space: 60,
  begin_time: undefined,
  end_time: undefined,
  as_code_list: [],
  data_items: [],
  pageNum: 1,
  pageSize: 20,
  total: 0
});

const isStand = ref(false)
const as_code_list = ref(undefined);
const hot = ref(true);
const points = ref(userForm.value.role_id === '预报员' ? false : true);
const singleTime = ref()
const multiTime = ref()


const changeHot = (row) => {
  if (row) {
    pageable.value.time_space = 60
  } else {
    pageable.value.time_space = 1
  }

  if(isStand.value){
    changeMultiTime(multiTime.value)
  }else {
    changeTime(singleTime.value)
  }
}

const changeMultiTime = (time) => {
  if (time) {
    const timeStamp = new Date(time).getTime();
    pageable.value.begin_time = timeStamp / 1000
    pageable.value.end_time = timeStamp / 1000
  } else {
    pageable.value.begin_time = undefined
    pageable.value.end_time = undefined
  }

// 创建一个新的日期对象，代表传入的时间
  const newDate = new Date(time);
  // 创建一个当前日期的对象，并设置为当天的0点0分0秒
  const today = new Date();

  if(hot.value){
    // 给新日期对象加上一个小时
    newDate.setHours(newDate.getHours() + 1);
    isIncreaseDay.value = newDate >  today;
  }else {
    // 创建一个新的日期对象，代表传入的时间
    // 给新日期对象加上一个小时
    newDate.setMinutes(newDate.getMinutes() + pageable.value.time_space);
    isIncreaseDay.value = newDate >  today;
  }



  getList()
}


const changePoints = (row) => {
  changeTime(singleTime.value)
  getList();
}

//
const changeTime = (time) => {
  console.log(time)
  const timeStamp = new Date(time).getTime();
  if (points.value) {
    //0点
    const startTime = timeStamp + 60 * 1000; // 添加1分钟（60秒）
    const endTime = timeStamp + 24 * 60 * 60 * 1000; // 添加一天（24小时）
    pageable.value.begin_time = startTime / 1000
    pageable.value.end_time = endTime / 1000
  } else {
    //18点
    // 前一天的18:01:00
    const previousDay = new Date(time);
    previousDay.setDate(previousDay.getDate() - 1); // 设置为前一天
    previousDay.setHours(18, 1, 0, 0); // 设置时间为18:01:00
    const startTimeStamp = previousDay.getTime(); // 获取前一天18:01:00的时间戳

    // 当天的18:00:00
    const nextDay = new Date(time);
    nextDay.setHours(18, 0, 0, 0); // 设置时间为18:00:00
    const endTimeStamp = nextDay.getTime(); // 获取当天18:00:00的时间戳

    pageable.value.begin_time = startTimeStamp / 1000;
    pageable.value.end_time = endTimeStamp / 1000;
  }

  const newDate = new Date(time);
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为当天的0点0分0秒
  if (newDate < today) {
    isIncreaseDay.value = false
  }else {
    isIncreaseDay.value = true
  }
  getList()
}

// 查询功能
const handleQuery = () => {
  if (isStand.value) {
    //多站
    pageable.value.pageNum = 1;
    getList();
  } else {
    //单站
    if (!pageable.value.as_code_list) {
      ElNotification({
        title: "错误",
        message: "请选择台站",
        type: "error",
        duration: 3000
      });
      return
    }
    pageable.value.pageNum = 1;
    getList();
  }


};


//搜索站号
const selectedData = ref([])
const selectedItems = (data) => {
  if (data.length > 0) {
    pageable.value.as_code_list = data
  } else {
    const allCodes = platformList.value.map(item => item.as_code);
    pageable.value.as_code_list = allCodes
  }
  getList()
};

//搜索站号
const selectedItems2 = (data) => {
  if (data.length > 0) {
    pageable.value.as_code_list = data
  } else {
    const allCodes = platformList.value.map(item => item.as_code);
    pageable.value.as_code_list = allCodes
  }

  getList()
};


//重置功能
const resetQuery = () => {
  initSingle();
  getList();
};


/**
 * @description 每页条数改变
 * @param {Number} val 当前条数
 * @return void
 * */
const handleSizeChange = (val: number) => {
  pageable.value.pageSize = val
  getList()

};

/**
 * @description 当前页改变
 * @param {Number} val 当前页
 * @return void
 * */
const handleCurrentChange = (val: number) => {
  pageable.value.pageNum = val
  getList()

};

const processTableData = ref<any>([]);

// 表格配置项
let columns = reactive<ColumnProps[]>([]);

//自定义部分表头
let customizeColumns = ref<any>([
  {
    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_id: 4,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "风",
    data_name: "10分钟风向",
    data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_XIANG",
    data_unit: "°",
    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: 3,
    data_type: "风",
    data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_SU",
    data_name: "10分钟风速",
    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: 501,
    data_type: "能见度",
    data_item: "YI_FEN_ZHONG_PING_JUN_NENG_JIAN_DU",
    data_name: "1分钟平均能见度",
    data_unit: "m",
    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: 101,
    data_type: "温湿度",
    data_item: "QI_WEN",
    data_name: "气温",
    data_unit: "℃",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    data_id: 201,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "水汽压",
    data_item: "SHUI_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: 109,
    data_type: "温湿度",
    data_item: "LU_DIAN_WEN_DU",
    data_name: "露点温度",
    data_unit: "℃",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  },
  {
    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_id: 207,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "气压",
    data_name: "海平面气压",
    data_item: "HAI_PING_MIAN_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: 312,
    data_type: "降水",
    data_item: "XIAO_SHI_LEI_JI_JIANG_SHUI_LIANG_CHENG_ZHONG",
    data_name: "小时累计降水量(称重)",
    data_unit: "mm",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_value: "",
    data_order: 0,
    data_condition: 0
  }
])


const updateColumns = () => {
  const column = [
    { prop: "as_name", label: "站名", width: 80,fixed:true },
    { prop: "as_code", label: "站号", width: 70,fixed:true },
    { prop: "data_time_i", label: "观测时间", width: 140, sortable: true,fixed:true }
  ];

  const newColumns = customizeColumns.value.map(item => ({
    prop: item.data_id.toString(),
    label: item.data_name + '' + item.data_unit + '',
    sortable: true,
    // width: calculateTextLengthInPixels(item.data_name)
  }));

  columns = [...column, ...newColumns];
  columns.forEach((column, index) => {
    renderHeader({ column });
  });
  pageable.value.data_items = [...customizeColumns.value];
  getList();
}

//操作 自定义部分表头
const copiedCustomizeColumns = ref<any>([...customizeColumns.value]);



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


// 查询所有人工要素字典表
const elementList = ref<any>([])
const getAllRgDataList = async () => {
  const { data } = await getRgDataList();
  elementList.value = data.list
};

const getList = async () => {
  if (pageable.value.as_code_list === undefined || pageable.value.as_code_list.length === 0) {
    // 没有站不给数据
    processTableData.value = []
    pageable.value.total = 0
    return;
  }
  const { data } = await getDataItemList(pageable.value);
  processTableData.value = data.list
  pageable.value.total = data.total
};

// 要素的选中和取消
const toggleSelection = (item) => {
  item.isSelected = !item.isSelected
  if (item.isSelected) {
    //添加
    copiedCustomizeColumns.value.push(item)
  } else {
    //删除
    copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== item.data_id);
  }

}

const handleSetting = () => {
  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 = () => {
  dialog.visible = false;
  customizeColumns.value = [...copiedCustomizeColumns.value]
  updateColumns()
  saveCustomizeColumns()
}

// 大概计算字符串长度
function calculateTextLengthInPixels(text) {
  return (text.length * 12) + 100;
}

//时间戳转换为指定格式的日期字符串
function formatDate(timestamp) {
  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 (isStand.value && hot.value) {
    return `${year}-${month}-${day} ${hours}`;
  }
  // 否则显示年月日小时分钟
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

onMounted(() => {
  initSingle()
  loadCustomizeColumns()
  updateColumns()
  getAllRgDataList()
})

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

// 从localStorage中获取customizeColumns数组
function loadCustomizeColumns() {
  const jsonString = localStorage.getItem('customizeColumns2');
  if (jsonString) {
    customizeColumns.value = JSON.parse(jsonString);
  }
}

const renderHeader = ({ column }: { column: any }) => {
  const span = document.createElement('span');
  span.innerText = column.label;
  document.body.appendChild(span);
  column.minWidth = span.getBoundingClientRect().width + 21;
  document.body.removeChild(span);
};


// 单站
const initSingle=()=>{
  isStand.value =false
  pageable.value = {
    data_type: false,
    time_order: 0,
    time_space: 60,
    begin_time: undefined,
    end_time: undefined,
    as_code_list: [],
    data_items: [],
    pageNum: 1,
    pageSize: 20,
    total: 0
  }
  //站点数据
  if (platformList.value && platformList.value.length > 0) {
    pageable.value.as_code_list = [platformList.value[0].as_code];
  } else {
    pageable.value.as_code_list =  [];
  }
  selectedData.value = pageable.value.as_code_list
  //正点
  hot.value = true
  pageable.value.time_space = 60
  points.value = userForm.value.role_id === '预报员' ? false : true;
  const singleTime2 = ref(new Date());
  singleTime.value= singleTime2.value.setHours(0, 0, 0, 0);
  changeTime(singleTime.value)
  pageable.value.data_items = [...customizeColumns.value];
}

// 多站
const initMany=()=>{
  isStand.value =true
  pageable.value = {
    data_type: false,
    time_order: 0,
    time_space: 60,
    begin_time: undefined,
    end_time: undefined,
    as_code_list: [],
    data_items: [],
    pageNum: 1,
    pageSize: 20,
    total: 0
  }
  //站点数据
  const allCodes = platformList.value.map(item => item.as_code);
  pageable.value.as_code_list = allCodes
  selectedData.value = pageable.value.as_code_list
  //正点
  hot.value = true
  pageable.value.time_space = 60
  points.value = userForm.value.role_id === '预报员' ? false : true;
  const singleTime2 = ref(new Date());
  multiTime.value= singleTime2.value.setHours(0, 0, 0, 0);
  changeMultiTime(multiTime.value)

  pageable.value.data_items = [...customizeColumns.value];
}

const isIncreaseDay =ref(true)

const decreaseDay = () => {
  if (singleTime.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(singleTime.value);
    newDate.setDate(newDate.getDate() - 1);
    singleTime.value = newDate;
    changeTime(newDate);
    getList()
  }
};

const increaseDay = () => {
  if (singleTime.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(singleTime.value);
    newDate.setDate(newDate.getDate() + 1);
    singleTime.value = newDate;
    changeTime(newDate);
    getList()
  }
};

const decreaseDay2 = () => {
  if (multiTime.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(multiTime.value);
    if (hot.value) {
      // 如果 hot 为 true，则减去一天
      newDate.setMinutes(newDate.getMinutes() - 60);
    } else {
      // 如果 hot 为 false，则减去分钟，这里需要具体逻辑，比如减去30分钟
      newDate.setMinutes(newDate.getMinutes() - pageable.value.time_space);
    }
    // 更新 multiTime 的值
    multiTime.value = newDate;
    // 调用 changeMultiTime 更新日期
    changeMultiTime(newDate);
    // 调用 getList 获取列表
    getList();
  }
};

const increaseDay2 = () => {
  if (multiTime.value) {
    pageable.value.pageNum = 1;
    const newDate = new Date(multiTime.value);
    if (hot.value) {
      // 如果 hot 为 true，则减去一天
      newDate.setMinutes(newDate.getMinutes() + 60);
    } else {
      // 如果 hot 为 false，则减去分钟，这里需要具体逻辑，比如减去30分钟
      newDate.setMinutes(newDate.getMinutes() + pageable.value.time_space);
    }
    // 更新 multiTime 的值
    multiTime.value = newDate;
    // 调用 changeMultiTime 更新日期
    changeMultiTime(newDate);
    // 调用 getList 获取列表
    getList();
  }
};

</script>
<style lang="scss" scoped >
.tpc .el-time-spinner__wrapper {
  width: 100% !important;
}
::v-deep .el-table-fixed-column--left {
  border-right: 1px solid #80bdff !important;
}
</style>
