<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" label="多站"/>

              <!--多站选择-->
              <el-select v-if="isStand" v-model="pageable.as_code_list"  multiple collapse-tags   filterable placeholder="请搜索自动站" remote reserve-keyword clearable  style="width: 200px;margin: 0 10px">
                <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 label="观测时间:" v-if="isStand">
                <el-switch
                  v-model="hot"
                  inline-prompt
                  active-text="正点"
                  size="default"
                  inactive-text="分钟"
                  @change="changeHot"
                />
                <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-form-item>

              <!--单站选择-->
              <el-select v-if="!isStand"  v-model="as_code_list"  @change="changeAslist" collapse-tags   filterable placeholder="请搜索自动站"  remote reserve-keyword clearable  style="width: 200px;padding: 0px 10px">
                <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 label="观测时间:" v-if="!isStand">
                <el-switch
                  v-model="hot"
                  inline-prompt
                  active-text="正点"
                  size="default"
                  inactive-text="分钟"
                  @change="changeHot"
                />

                <span class="form-item__label">日界:</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-form-item>

              <el-form-item v-if="!hot" label="数据密度:">
                <el-select v-model="pageable.time_space" style="width: 240px"  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>
            <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="940px" append-to-body>
      <div style="height: 500px">
        <el-tabs tab-position="left" class="demo-tabs" style="height: 100%">
          <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>
      <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 {ref, reactive, onMounted, onDeactivated, onActivated} 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";
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)
}

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


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(true)
const as_code_list = ref(undefined);
const hot = ref(true);
const points =ref(true);
const singleTime =ref(undefined)
const multiTime =ref(undefined)


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

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 changePoints=(row)=>{
  singleTime.value =undefined
  pageable.value.begin_time = undefined
  pageable.value.end_time = undefined

}
const changeTime =(time)=>{
  const timeStamp = new Date(time).getTime();
  if(points){
    //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点
    const startTimeStamp = timeStamp + 18 * 60 * 60 * 1000 + 60 * 1000;// 添加18小时和1分钟（18*60*60秒+60秒）
    const nextDay = new Date(time);
    nextDay.setDate(nextDay.getDate() + 1); // 设置为第二天
    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 changeAslist =(row)=>{
  if(row){
    pageable.value.as_code_list = [row]
  }else {
    pageable.value.as_code_list = []
  }

}


// 查询功能
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 resetQuery = () => {
  pageable.value.pageNum = 1;
  pageable.value.as_code_list = undefined
  getList();
};


/**
 * @description 每页条数改变
 * @param {Number} val 当前条数
 * @return void
 * */
const handleSizeChange = (val: number) => {
  console.log("=====");
  console.log(val);
};

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

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 updateColumns = () => {
  const column = [
    { prop: "as_name", label: "站名", width: 100 },
    { prop: "as_code", label: "站号", width: 100 },
    { prop: "data_time_i", label: "观测时间", width: 170 }
  ];

  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 queryas = ref<Platform>({
  pagesize: 50,
  currentpage: 1
})

const platformList =ref<any>([])

const getPlatforms = async () => {
  const { data } = await getPlatformList(queryas.value);
  platformList.value = data.list
};


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

const getList = async () => {
  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(() => {
  loadCustomizeColumns()
  updateColumns()
  getPlatforms()
  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);
  }
}
</script>
<style>
.tpc .el-time-spinner__wrapper {
  width:100% !important;
}
</style>

