<template>
  <div>
    <div class="title">
      云端数据
      <div class="title_time">{{ currentDate }}</div>
    </div>
    <div class="card">
      <div class="screen">
        <div class="filter_item">
          电站&ensp;&ensp;
          <el-select v-model="status" placeholder="选择电站" @change="postemsDevice">
            <el-option v-for="item in cities" :key="item.id" :label="item.stationName" :value="item.id" />
          </el-select>
        </div>
        <div class="filter_item1">
          &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;所属设备&ensp;&ensp;
          <el-select
            v-model="emsDeviceId"
            placeholder="请先选择电站在选择所属设备"
            size="large"
            clearable
            @change="getpostdeviceClass"
          >
            <el-option v-for="item in emsDevice" :key="item.id" :label="item.emsDeviceId" :value="item.id" />
          </el-select>
        </div>
        <div class="filter_item1">
          &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;设备类型&ensp;&ensp;
          <el-select v-model="quipment" placeholder="请选择设备类型" size="large" clearable>
            <el-option v-for="item in quipmentlist" :key="item.peek" :label="item.peek" :value="item.peek" />
          </el-select>
        </div>
        <div class="filter_item1">
          &ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;标题翻译&ensp;&ensp;
          <el-select v-model="translate.user.peekType" placeholder="请选择设备类型" size="large" clearable @change="ontranslate">
            <el-option v-for="item in translatelist" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
        </div>
      </div>
      <div class="screen1">
        <div>
          时间范围&ensp;&ensp;
          <el-date-picker
            size="large"
            v-model="timevalue"
            :shortcuts="shortcuts"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-value="timevalue"
            :disabled-date="pickerOptions"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
          />
        </div>
        &ensp;&ensp; &ensp;&ensp;
        <div>
          <el-button type="primary" size="large" color="#0052d9" @click="query(0)">查询</el-button>
          <el-button type="primary" size="large" color="#0052d9" @click="newaddition">导出</el-button>
          <el-button size="large" @click="query(1)">重置</el-button>&ensp;&ensp;
        </div>
      </div>
    </div>
    <div class="card cardbottom">
      <div>&ensp;</div>
      <el-table :data="tableData.list" style="width: 100%" border @header-click="toggleColumn" show-overflow-tooltip>
        <el-table-column
          v-for="item in headdata"
          :key="item"
          :prop="visibleColumns[item] ? item : ''"
          :label="visibleColumns[item] ? item : ''"
          :width="visibleColumns[item] ? 250 : 10"
          style="overflow: auto"
        />
      </el-table>
      <!-- 分页 组件 -->
      <div class="pagination">
        <div></div>
        <slot name="pagination">
          <Pagination :pageable="pageable" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange" />
        </slot>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="导出中" top="300px" width="40%" @close="handleClose">
      <div class="lexce">{{ message }}</div>
      <template #footer>
        <div class="dialog-footer" v-if="excelexport">
          <el-button v-if="excelexport.progress == 0" @click="handleClose">取消导出</el-button>
          <el-button v-if="excelexport.progress == 3" type="primary" @click="handleClose"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  tdengineyuanshilURL,
  stationstationName,
  postemsSystemsingleStation,
  listexcellURL,
  powerlistURL,
  listexcelURL,
  updateURL,
  selectaccountNumber
} from "@/api/home/Multisite";
import { onMounted, Ref, ref } from "vue";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ElMessage } from "element-plus";

const emsDeviceId = ref("");
const quipment = ref("");
const quipmentlist = ref();
const translate = ref();
const translatelist = ref([
  {
    value: "中文",
    id: "2"
  },
  {
    value: "英文",
    id: "1"
  }
]);

const emsDevice: Ref<any[]> = ref([]);
const cities = ref();
const timevalue: Ref<any> = ref([]);

const poststationstationName = async () => {
  const { data } = await stationstationName({});
  cities.value = data;
};

const postemsDevice = async (value: any) => {
  console.log(value);

  emsDevice.value = [];
  emsDeviceId.value = "";
  const { data } = await postemsSystemsingleStation({}, value);
  emsDevice.value = data;
};

const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};

const getpostdeviceClass = async () => {
  const { data } = await powerlistURL({ eId: emsDeviceId.value });
  quipmentlist.value = data;
};

const query = (val: any) => {
  if (val == 0) {
    getplatformuserlist();
  } else {
    (quipment.value = ""), (status.value = "");
    (emsDeviceId.value = ""), getplatformuserlist();
  }
};

const dialogVisible = ref(false);
const message = ref("");

const newaddition = async () => {
  if (timevalue.value.length == 0) {
    console.log(timevalue.value.length == 0);

    ElMessage.error("请选择时间范围！");
    return;
  }
  message.value = "正在导出...";
  dialogVisible.value = true;

  let obj = {
    powerId: status.value,
    eId: emsDeviceId.value,
    peek: quipment.value,
    startTime: timevalue.value[0],
    endTime: timevalue.value[1]
  };
  const { data } = await listexcellURL(obj);
  console.log(data);

  gitlistexcelURL();
};

const timerId = ref();
const excelexport = ref();

const handleClose = async () => {
  if (timerId.value) {
    clearTimeout(timerId.value);
    timerId.value = ""; // 清除引用
    dialogVisible.value = false;
  }
};

const gitlistexcelURL = async () => {
  const { data } = await listexcelURL();
  console.log(data);
  excelexport.value = data;
  message.value = excelexport.value.message;
  if (excelexport.value.progress == 0) {
    timerId.value = setTimeout(() => {
      gitlistexcelURL();
    }, 2000);
  } else if (excelexport.value.progress == 3) {
    handleClose();
    downloadxlsx(data);
  }
};

const downloadxlsx = (data: any) => {
  let fileUrl = `download/${data.excelFileName}`;
  const date = new Date();
  const hours = formatTime(date.getHours());
  const minutes = formatTime(date.getMinutes());
  const seconds = formatTime(date.getSeconds());
  let fileName = `${currentDate.value} ${hours}：${minutes}：${seconds}故障报表.xlsx`;
  fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    })
    .catch(error => {
      console.error("下载文件时出错:", error);
    });
};

const formatTime = (time: number) => {
  return time < 10 ? `0${time}` : time;
};

const tableData = ref();
const status = ref("");
const pageable = ref({
  pn: 1,
  ps: 10,
  total: 0
});

const handleSizeChange = async (e: any) => {
  pageable.value.ps = e;
  getplatformuserlist();
};

const handleCurrentChange = async (e: any) => {
  pageable.value.pn = e;
  getplatformuserlist();
};

const visibleColumns = ref<{ [key: string]: boolean }>({});

const toggleColumn = (column: any) => {
  console.log("点击的列对象:", column);
  const columnLabel = column.rawColumnKey; // 获取列名
  console.log("当前 visibleColumns:", visibleColumns.value);

  if (columnLabel) {
    visibleColumns.value[columnLabel] = !visibleColumns.value[columnLabel]; // 切换列的显示状态
    console.log(`列 ${columnLabel} 的显示状态：`, visibleColumns.value[columnLabel]);
  }
};
const headdata = ref();
const head = ref();

const getplatformuserlist = async () => {
  let obj = {
    powerId: status.value,
    eId: emsDeviceId.value,
    startTime: timevalue.value[0],
    endTime: timevalue.value[1],
    peek: quipment.value,
    pageNum: pageable.value.pn,
    pageSize: pageable.value.ps
  };
  const { data } = await tdengineyuanshilURL(obj);
  tableData.value = data;
  console.log(tableData.value.list[0]);

  head.value = Object.keys(tableData.value.list[0]);
  head.value.forEach((item: string) => {
    if (!visibleColumns.value[item]) {
      visibleColumns.value[item] = true; // 默认显示所有列
    }
  });
  headdata.value = head.value;

  console.log(visibleColumns.value);

  pageable.value.total = tableData.value.page.totald;
};

const currentDate = ref();
const ontranslate = async (e: any) => {
  console.log(e);
  let obj = {
    peekType: e
  };
  await updateURL(obj);
  await getplatformuserlist();
};

const selectaccountNumberlist = async () => {
  const { data } = await selectaccountNumber({});
  console.log(data);
  translate.value = data;
};

const shortcuts = [
  {
    text: "过去7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  },
  {
    text: "过去1个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    }
  },
  {
    text: "过去3个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    }
  }
];

onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
  }
  const today = new Date();
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(today.getDate() - 7);
  const sevenDaysAgoDate = sevenDaysAgo.toISOString().split("T")[0];

  timevalue.value = [sevenDaysAgoDate, currentDate.value];
  console.log(timevalue.value);

  getplatformuserlist();
  poststationstationName();
  selectaccountNumberlist();
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
