<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="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: 0 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="观测时间:">
                <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-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/setting.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 v-bind="item" :fixed="item.fixed" :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" :page-sizes="[24,60]" :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 sensorList" :key="item.se_type"  >
                <div v-if="item.se_state===0"  :class="item.isSelected?'item-tag-active':'item-tag'" @click="toggleSelection(item)" >{{item.se_name}}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="自动">
            <div class="container-tag">
              <template v-for="item in sensorList" :key="item.se_type"  >
                <div v-if="item.se_state===1"  :class="item.isSelected?'item-tag-active':'item-tag'" @click="toggleSelection(item)" >{{item.se_name}}</div>
              </template>
            </div>
          </el-tab-pane>
          <el-tab-pane label="人工">
            <div class="container-tag">
              <template v-for="item in sensorList" :key="item.se_type"  >
                <div v-if="item.se_state===2"  :class="item.isSelected?'item-tag-active':'item-tag'" @click="toggleSelection(item)" >{{item.se_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.se_type">
              <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.se_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, computed} from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import {getPlatformList, getStaitemList, getYallSensorList} from "@/api/modules/allData";
import {Platform} from "@/api/interface";
import {ElNotification} from "element-plus";
import {useUserStore} from "@/stores/modules/user";

const userStore = useUserStore();
const userForm  = computed(() => userStore.userInfo);
const isStand =ref(true)
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 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 pageable = ref<any>({
  time_space:60,
  begin_time: undefined,
  end_time: undefined,
  data_type: false,
  time_order: 0,
  as_code_list:[],
  data_items:[],
  state_list: [
    "STATE_PART",
    "STATE_SENSOR",
    "STATE_ARTIFICIAL"
  ],
  pageNum: 1,
  pageSize: 24
});


const changeHot =(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
  }

}

function transformData(dataArray) {
  return dataArray.map(item => {
    const transformedItem = {};
    for (const key in item) {
      if (key === 'as_code' || key === 'data_time_i' || key === 'as_name' || key === 'data_count' || key === 'data_time') {
        transformedItem[key] = item[key];
      } else {
        const value = item[key];
        const device = deviceType.find(d => d.value === value);
        transformedItem[key] = device ? device.label : value;
      }
    }
    return transformedItem;
  });
}

const deviceType= [
  {
    value: 0,
    label: '正常',
  },
  {
    value: 1,
    label: '未连接',
  },
  {
    value: 2,
    label: '告警',
  },
  {
    value: 3,
    label: '故障',
  },
  {
    value: 4,
    label: '不确定',
  },
  {
    value: 5,
    label: '未启用',
  }
]


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

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 changeAslist =(row)=>{
  if(row){
    pageable.value.as_code_list = [row]
  }else {
    pageable.value.as_code_list = []
  }

}

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

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

    {
      "se_type": 0,
      "se_name": "预处理器",
      "data_item": "",
      "se_state": 0,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1,
      "data_item": "",
      "se_name": "通信模块",
      "data_r_table": "",
      "se_state": 0,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 100,
      "se_name": "超声风传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 200,
      "data_item": "",
      "se_name": "旋转式风向传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 300,
      "se_name": "旋转式风速传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 400,
      "data_item": "",
      "se_name": "气温传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 500,
      "se_name": "湿度传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 600,
      "data_item": "",
      "se_name": "气压传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 700,
      "data_item": "",
      "se_name": "称重式降水传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 800,
      "data_item": "",
      "se_name": "翻斗雨量传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1200,
      "se_name": "地面温度传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1100,
      "se_name": "DSS1型雪深观测仪",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1000,
      "se_name": "能见度/天气现象传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 900,
      "data_item": "",
      "se_name": "云高仪",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1300,
      "se_name": "大气电场传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1400,
      "se_name": "雷电预警仪",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1500,
      "se_name": "日照传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1600,
      "se_name": "总辐射传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1700,
      "se_name": "光照度传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1800,
      "se_name": "压力式水位传感器",
      "data_item": "",
      "se_state": 1,
      "data_r_table": "",
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    },
    {
      "se_type": 1900,
      "data_item": "",
      "se_name": "流向流速传感器",
      "data_r_table": "",
      "se_state": 1,
      "data_h_table": "",
      "data_value": "",
      "isSelected": true
    }

])
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;
      }
    }
    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 copiedCustomizeColumns = ref<any>([...customizeColumns.value]);

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

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

const handleSetting = () => {
  copiedCustomizeColumns.value = [...customizeColumns.value]
  sensorList.value.forEach(element => {
    const column = copiedCustomizeColumns.value.find(col => col.se_type === element.se_type);
    if (column) {
      element.isSelected = true;
    } else {
      element.isSelected = false;
    }
  });


  dialog.title = "列表字段设置"
  dialog.visible = true;
}



const getSensorList = async () => {
  const { data } = await getYallSensorList();
  sensorList.value = data.list
};


const submitForm = () => {
  dialog.visible = false;
  customizeColumns.value = [...copiedCustomizeColumns.value]
  updateColumns()
  saveCustomizeColumns()
}

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,fixed:true }
  ];
  const newColumns = customizeColumns.value.map(item => ({
    prop: item.se_type===0?'yclq_state':item.se_type.toString(),
    label: item.se_name,
    width: calculateTextLengthInPixels(item.se_name)
  }));


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


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

const changeCodeList =(value)=>{
  if(value){
    pageable.value.as_code_list = [value]
  }else {
    pageable.value.as_code_list= []
  }
  getList()
}


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

onMounted(() => {
  initSingle();
  loadCustomizeColumns()
  updateColumns()
  getSensorList()
})

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

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



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

const getList = async () => {
// 没有站不给数据
  processTableData.value = []
  pageable.value.total=0
  const { data } = await getStaitemList(pageable.value);
  processTableData.value = transformData(data.list)
  pageable.value.total = data.total
};





const handleSortChange = ({ column, prop, order }) =>{
  // 在这里发送请求到服务器端进行远程排序


}


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

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


function  timeDefault() {
  var date = new Date();
  var s1 = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());
  return s1;
}

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

function findLabelByValue(noticeTypeList, value) {
  const item = noticeTypeList.find(item => item.value === value);
  return item ? item.label : null;
}


// 单站
const initSingle=()=>{
  pageable.value = {
    time_space:60,
    begin_time: undefined,
    end_time: undefined,
    data_type: false,
    time_order: 0,
    as_code_list:[],
    data_items:[],
    state_list: [
      "STATE_PART",
      "STATE_SENSOR",
      "STATE_ARTIFICIAL"
    ],
    pageNum: 1,
    pageSize: 24
  }
  //站点数据
  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 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()
  }
};


</script>

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