<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="自动站:">
              <SelectItem :select-data="selectedData" :select-list="platformList" :is-checkbox="false" @update:selectedItems="selectedItems" style="width: 200px"> </SelectItem>
            </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="80px" :show-overflow-tooltip="true">
          <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 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 Pagination from "@/components/ProTable/components/Pagination.vue";
import SelectItem from "@/components/SelectItem/index.vue";
import {ref, reactive, onMounted, onDeactivated, onActivated, computed} from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import {ElTable} from "element-plus";
import {getDataItemList, getPlatformList, getRgDataList} from "@/api/modules/allData";
import { Platform} from "@/api/interface";
import {useUserStore} from "@/stores/modules/user";
const tableRef = ref<InstanceType<typeof ElTable>>();
const dialog = reactive<any>({
  visible: false,
  title: ''
});

const cancel = () => {
  dialog.visible = false;
}
const handleSortChange = ({ column, prop, order }) => {
  console.log('column:', column);
  console.log('prop:', prop);
  console.log('order:', 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 pageable = ref<any>({
  data_type: true,
  time_order: 0,
  as_code_list:undefined,
  data_items:[],
  data_order:[],
  pageNum: 1,
  pageSize: 20,
  total: 0
});

// 查询功能
const handleQuery = () => {
  pageable.value.pageNum = 1;
  getList();

};

//重置功能
const resetQuery = () => {
  const allCodes = platformList.value.map(item => item.as_code);
  pageable.value.as_code_list = allCodes
  selectedData.value = []
  pageable.value.pageNum = 1;
  pageable.value.time_order =0
  pageable.value.data_order =[]
  pageable.value.pageSize =20
  pageable.value.total = 0
  tableRef.value!.clearSort()
  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([]);

// 表格配置项
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 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 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);
};

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;
      }
    }
    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 < sensorList.value.length; i++) {
    sensorList.value[i].isSelected = false;
  }
}

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


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

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

  columns = [...column, ...newColumns];
  pageable.value.data_items = [...customizeColumns.value];
  getList();
}

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

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

//搜索站号
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
  }
};

// 查询所有人工要素字典表
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 * 14)+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');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

onMounted(() => {
  const allCodes = platformList.value.map(item => item.as_code);
  pageable.value.as_code_list = allCodes

  loadCustomizeColumns()
  updateColumns()
  getAllRgDataList()
})

// 保存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);
  }
}
let intervalId;

onActivated(() => {
  intervalId = setInterval(() => {
    getList();
  }, 30 * 1000);
});

onDeactivated(() => {
  clearInterval(intervalId);
});


</script>
