<template>
  <el-dialog
    :close-on-click-modal="false"
    draggable
    v-model="dialogVisible"
    :title="title"
    width="85%"
  >
    <el-descriptions class="margin-top" :column="3" border  label-width="90px">
      <el-descriptions-item label="用户">
        {{ obj.customerName }}
      </el-descriptions-item>
      <el-descriptions-item label="对象类型" >
        {{ obj.smallObjType }}
      </el-descriptions-item>
      <el-descriptions-item label="供电区域" >
        {{ obj.gdName }}
      </el-descriptions-item>
      <el-descriptions-item label="上级电站" :span="3">

        <template v-if="obj.substationName">
          <el-tag
                  v-for="(item, index) in obj.substationName.split(';')"
                  :key="index"
                  style="margin-right: 5px;"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="上级母线" :span="3">
        <template v-if="obj.busbarName">
          <el-tag type="success"
              v-for="(item, index) in obj.busbarName.split(';')"
              :key="index"
              style="margin:5px"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-descriptions-item>
    </el-descriptions>


    <div class="formFlex">

      <el-button
        type="primary"
        :icon="Download"
        @click="exportTable"
        size="small"
        >导出
      </el-button>
    </div>
    <div class="tableBox" style="padding: 0">
      <el-table
        :scrollbar-always-on="true"
        :data="dataList"
        height="500px"
        stripe
        size="small"
        v-loading="loading"
        element-loading-background="#343849c7"
        :header-cell-style="{ textAlign: 'center' }"
        border
      >
        <el-table-column label="序号" align="center" type="index" width="70">
          <template #default="scope">
            <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="timeid"
          align="center"
          label="发生时间"
          width="190"
          sortable
        >
          <template #default="scope"
            >{{ scope.row.timeid }}.{{ scope.row.ms }}
          </template>
        </el-table-column>
         <el-table-column
          prop="gdName"
          label="供电区域"
          align="center"
           width="170"
          show-overflow-tooltip
        />
        <el-table-column
          prop="bdname"
          align="center"
          label="变电站"
          show-overflow-tooltip
          sortable
            width="170"
        />


        <el-table-column
          prop="busName"
          label="上级母线"
          align="center"
          width="170"
          show-overflow-tooltip
        />
        <el-table-column
            prop="pointname"
            align="center"
            label="监测点"
            show-overflow-tooltip
            width="170"
        />
         <el-table-column
          prop="objName"
          align="center"
          label="用户"
          show-overflow-tooltip
        >
          <template #default="scope">{{ scope.row.objName || "/" }}</template>
        </el-table-column>

        <el-table-column
          prop="wavetype"
          align="center"
          width="90"
          label="触发类型"
        >
          <template #default="scope">
            {{ filteWavetype(scope.row.wavetype) }}
            <!-- </el-tag> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="eventvalue"
          align="center"
          label="残余电压"
          width="100"
          sortable
        >
          <template #default="scope">
            {{ Math.floor(scope.row.eventvalue * 10000) / 100 }}%
          </template>
        </el-table-column>
        <el-table-column
          prop="persisttime"
          align="center"
          label="持续时间"
         width="100"
          sortable
        >
          <template #default="scope">
            {{ Math.floor(scope.row.persisttime * 1000) / 1000 }}s</template
          >
        </el-table-column>

        <el-table-column
          prop="onLineRate"
          label="操作"
          align="center"
          width="80"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              @click="trendCharts(scope.row)"
            >
              波形
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        :currentPage="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 200]"
        size="small"
        background
        :layout="'sizes,total, ->, prev, pager, next, jumper'"
        :total="total"
        @size-change="onTableSizeChange"
        @current-change="onTableCurrentChange"
      />
    </div>

  </el-dialog>
  <!-- 趋势图 -->
    <el-dialog
      :close-on-click-modal="false"
      draggable
      v-model="trendVisible"
      v-if="trendVisible"
      title="波形"
      width="70%"
        @close="  dialogVisible = true;"
    >
      <waveForm ref="waveFormRef" />
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from "vue";
import table2excel from "js-table2excel";
import * as XLSX from "xlsx";
import waveForm from "@/components/BX/waveForm.vue";
import {
  rightImportOpenDetail,
  userEventList,
  getDicTree,
} from "@/api/statistics/index";
import { Download, Search } from "@element-plus/icons-vue";

import { useStore } from "vuex";
const store = useStore();
const waveFormRef = ref();
const trendVisible = ref(false);
const dialogVisible = ref(false);
const loading = ref(false);
const title = ref("暂降事件_详情");
const dataList = ref([]); // 存储原始数据
const columns: any = ref([]);
const pageNum = ref(1); // 当前页
const pageSize = ref(20); // 每页条数
const total = ref(0); // 总条数
const key: any = ref("");
const searchValue = ref("");
const eventList = ref([]);
const obj: any = ref({}); // 初始化为空对象
const bigObjTypeList = ref([]);
const open = async (eventLis: any) => {
  pageNum.value = 1;
  pageSize.value = 20;
  searchValue.value = eventLis.customId; // 清空搜索框
  eventList.value = eventLis.eventList;
  dialogVisible.value = true;
  await init();
};
const init = async () => {
  loading.value = true;

  rightImportOpenDetail({
    deptId: store.state.deptId,
    searchValue: searchValue.value,
  }).then((res) => {
    obj.value = res.data;
    loading.value = false;
  });

  userEventList({
    deptId: store.state.deptId,
    type: store.state.timeType,
    searchValue: searchValue.value,
    searchBeginTime: store.state.timeValue[0],
    searchEndTime: store.state.timeValue[1],
    eventIds: eventList.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }).then((res) => {
    dataList.value = res.data.records;
    total.value = res.data.total;

  });
};

const formatterObj = (value: string) => {
  let tem = bigObjTypeList.value.find((it) => it.id == value);
  if (tem) {
    return tem.name;
  }
};

const onTableSizeChange = (size: number) => {
  pageSize.value = size;
  pageNum.value = 1;
  init();
};

const onTableCurrentChange = (page: number) => {
  pageNum.value = page;
  init();
};
const filteWavetype = (wavetype: string) => {
  switch (wavetype + "") {
    case "0":
      return "扰动";
    case "1":
      return "暂降";
    case "2":
      return "暂升";
    case "3":
      return "中断";
    case "4":
      return "其他";
    case "5":
      return "录波";
  }
};
// 导出
const exportTable = async () => {
  // 示例数据

  let columnExpor: any = [
    [
      "发生时间",
      "供电区域",
      "变电站",
      "监测母线",
      "监测点",
      "用户",
      "触发类型",
      "残余电压",
      "持续时间",
    ],
  ];

  let list = [];

  await userEventList({
    deptId: store.state.deptId,
    type: store.state.timeType,
    eventIds: eventList.value,
    searchValue: searchValue.value,
    searchBeginTime: store.state.timeValue[0],
    searchEndTime: store.state.timeValue[1],
    pageNum: 1,
    pageSize: total.value,
  }).then((res) => {
    let data = res.data.records.map((item) => {
      return [
         item.timeid + "." + item.ms,
        item.gdName,
        item.bdname,
        item.busName,
        item.pointname,
        item.objName,
        filteWavetype(item.wavetype),
        Math.floor(item.eventvalue * 10000) / 100 + "%",
        Math.floor(item.persisttime * 1000) / 1000 + "s",
      ];
    });
    list = [...columnExpor, ...data];
    // 创建工作表
    const worksheet = XLSX.utils.aoa_to_sheet(list);

    worksheet["!cols"] = list.map((col) => ({ wch: 20 }));

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, title.value);

    // 写出文件
    XLSX.writeFile(workbook, title.value + ".xlsx");
  });
};
//点击趋势图
const trendCharts = (row: any) => {
  dialogVisible.value = false;
  trendVisible.value = true;
  setTimeout(() => {
    waveFormRef.value?.open(row);
  }, 500);
};
onMounted(() => {
  getDicTree({
    code: "CUSTOM_USER",
  }).then((res) => {
    bigObjTypeList.value = res.data;
  });
});
defineExpose({
  open,
});
</script>

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

.form {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 10px;
}

.formFlex {
  display: flex;
  justify-content: end;
  margin: 10px 0;
}
</style>
