<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="daterange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-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/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="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" :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">
            <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)">{{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 Pagination from "@/components/ProTable/components/Pagination.vue";
import {ref, reactive, onMounted} 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";


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 pageable = ref<any>({
  time_space:60,
  begin_time: undefined,
  end_time: undefined,
  data_type: false,
  time_order: 0,
  as_code_list:[],
  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)=>{
  singleTime.value =undefined
  pageable.value.begin_time = undefined
  pageable.value.end_time = undefined

}
const changeTime =(time)=> {
  const [start, end] = time;

  const startTime2 = new Date(start).getTime();
  const endTime2= new Date(end).getTime();
  if (points) {
    //0点
    const startTime = startTime2 + 60 * 1000; // 添加1分钟（60秒）
    const endTime = endTime2 + 24 * 60 * 60 * 1000; // 添加一天（24小时）
    pageable.value.begin_time = startTime / 1000
    pageable.value.end_time = endTime / 1000
  } else {
    //18点
    const startTimeStamp = startTime2 + 18 * 60 * 60 * 1000 + 60 * 1000;// 添加18小时和1分钟（18*60*60秒+60秒）
    const endTimeStamp = endTime2 + 18 * 60 * 60 * 1000 + 60 * 1000;// 添加18小时和1分钟（18*60*60秒+60秒）
    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 processTableData = ref([]);

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

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 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]
  console.log( customizeColumns.value)
  updateColumns()
  saveCustomizeColumns()
}

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.se_type===0?'yclq_state':item.se_type,
    label: item.se_name,
    width: calculateTextLengthInPixels(item.se_name)
  }));
  console.log('==============')
  console.log(newColumns)

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


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

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


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

onMounted(() => {
  loadCustomizeColumns()
  updateColumns()
  getPlatforms()
  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>([])
// 查询自动站列表
const queryas = ref<Platform>({
  pageSize: 10000,
  pageNum: 1
})

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


const getList = async () => {
  const { data } = await getStaitemList(pageable.value);
  console.log(transformData(data.list))
  processTableData.value = transformData(data.list)
  pageable.value.total = data.total
};



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


// 查询功能
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 = {
    time_space:60,
    begin_time: undefined,
    end_time: undefined,
    data_type: false,
    time_order: 1,
    as_code_list:[],
    state_list: [
      "STATE_PART",
      "STATE_SENSOR",
      "STATE_ARTIFICIAL"
    ],
    pageNum: 1,
    pageSize: 24
  }
  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}`;
}


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

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

<style>
.tpc .el-time-spinner__wrapper {
  width:100% !important;
}
</style>
