<template>
  <el-dialog
    :close-on-click-modal="false"
    draggable
    v-model="dialogVisible"
    :title="title"
    width="70%"
    @close="close"
  >
    <el-form :inline="true" class="formFlex">
      <div>
<!--        <el-form-item label="用户信息">
          <el-input
            clearable
            style="width: 140px"
            v-model="searchValue"
            size="small"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>-->
        <el-form-item label="运维单位">
          <el-select
            v-model="deptsIndex"
            placeholder="请选择运维单位"
            size="small"
            clearable
            style="width: 140px"
          >
            <el-option
              v-for="item in deptsList"
              :label="item.deptsname"
              :value="item.deptsIndex"
              :key="item.deptsIndex"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供电区域">
          <el-select
            v-model="gdIndex"
            placeholder="请选择供电区域"
            size="small"
            clearable
            style="width: 140px"
          >
            <el-option
              v-for="item in gdList"
              :label="item.name"
              :value="item.gdIndex"
              :key="item.gdIndex"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级电站">
          <el-select
            filterable
            v-model="bdIndex"
            placeholder="请选择上级电站"
            size="small"
            clearable
            style="width: 140px"
          >
            <el-option
              v-for="item in bdList"
              :label="item.name"
              :value="item.subIndex"
              :key="item.subIndex"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="对象大类">
          <el-select
            size="small"
            v-model="bigObjType"
            clearable
            placeholder="请选择对象大类"
            style="width: 140px"
          >
            <el-option
              v-for="item in bigObjTypeList.filter((item) => item.level == 2)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对象小类">
          <el-select
            size="small"
            clearable
            v-model="smallObjType"
            placeholder="请选择对象小类"
            style="width: 140px"
          >
            <el-option
              v-for="item in smallObjTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>-->
      </div>
      <div class="mt5">
        <el-button type="primary" :icon="Search" @click="init" size="small"
          >查询
        </el-button>
        <el-button
          type="primary"
          :icon="Download"
          @click="exportTable"
          size="small"
          >导出
        </el-button>
      </div>
    </el-form>
    <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"
            label="暂降发生时间"
            align="center"
            width="170"
            show-overflow-tooltip
            sortable
        >
          <template #default="scope"
          >{{ scope.row.timeid }}.{{ scope.row.ms }}
          </template>
        </el-table-column>
        <el-table-column
          prop="wavetype"
          label="暂降类型"
          align="center"
          width="70"
        >
          <template #default="{ row }">
            {{ filteWavetype(row.wavetype) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="eventvalue"
          label="残余电压"
          align="center"
          sortable
          width="90"
        >
          <template #default="{ row }">
            {{ Math.floor(row.eventvalue * 10000) / 100 }}%
          </template>
        </el-table-column>

        <el-table-column
          prop="persisttime"
          label="持续时间"
          align="center"
          sortable
          width="100"
        >
          <template #default="{ row }">
            {{ Math.floor(row.persisttime * 1000) / 1000 }}s
          </template>
        </el-table-column>
        <el-table-column
          prop="gdName"
          label="供电区域"
          align="center"
          width="160"
        />
        <el-table-column
          prop="bdname"
          label="变电站"
          align="center"
          width="160"
        />


        <el-table-column
          prop="busName"
          label="监测母线"
          align="center"

        />
        <el-table-column
            prop="pointname"
            label="监测点"
            align="center"
            width="160"
        />
        <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="closeBox"
  >
    <waveForm ref="waveFormRef" />
  </el-dialog>
</template>

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

import { useStore } from "vuex";
const emit = defineEmits(["closeDialog"]);
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 bigObjType = ref("");
const smallObjType = ref("");
const searchValue = ref("");
const deptsIndex = ref("");
const gdIndex = ref("");
const bdIndex = ref("");
const deptsList = ref([]);
const gdList = ref([]);
const bdList = ref([]);
const eventIds = ref([]);
const flag = ref(true);
const bigObjTypeList = ref([]);

const open = async (ids: any) => {
  eventIds.value = ids;
  await regionDevCount({
    deptId: store.state.deptId,
    type: store.state.timeType,
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
  }).then((res: any) => {
    deptsList.value = res.data;
  });
  await gdSelect().then((res: any) => {
    gdList.value = res.data;
  });

  await bdSelect().then((res: any) => {
    bdList.value = res.data;
  });

  pageNum.value = 1;
  pageSize.value = 20;
  searchValue.value = ""; // 清空搜索框
  dialogVisible.value = true;
  deptsIndex.value = ""; // 清空搜索框
  gdIndex.value = "";
  bdIndex.value = "";
  setTimeout(async () => {
    await init();
  }, 100);
};
const init = async () => {
  loading.value = true;

  await rightEventOpenForDetail({
    bigObjType: bigObjType.value,
    smallObjType: smallObjType.value,
    deptId: deptsIndex.value || store.state.deptId,
    gdIndex: gdIndex.value,
    bdId: bdIndex.value,
    type: store.state.timeType,
    searchValue: searchValue.value,
    searchBeginTime: store.state.timeValue[0],
    searchEndTime: store.state.timeValue[1],
    pageNum: pageNum.value,
    pageSize: pageSize.value,

    eventIds: eventIds.value,
  }).then((res) => {
    dataList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  });
};

const onTableSizeChange = (size: number) => {
  pageSize.value = size;
  pageNum.value = 1;
  init();
};
onMounted(() => {
  getDicTree({
    code: "CUSTOM_USER",
  }).then((res) => {
    bigObjTypeList.value = res.data;
  });
});
const smallObjTypeList: any = computed(() => {
  smallObjType.value = "";
  return bigObjTypeList.value.filter((item: any) => {
    return item.parentId == bigObjType.value && item.level == 3;
  });
});

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 rightEventOpenForDetail({
    bigObjType: bigObjType.value,
    smallObjType: smallObjType.value,
    deptId: store.state.deptId,
    type: store.state.timeType,
    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.objName,
        filteWavetype(item.wavetype),
        item.timeid + "." + item.ms,
        Math.floor(item.eventvalue * 10000) / 100 + "%",
        item.persisttime + "s",
        item.gdName,
        item.bdname,
        item.pointname,
        item.busName,
      ];
    });
    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;
  flag.value = false;
  trendVisible.value = true;
  setTimeout(() => {
    waveFormRef.value?.open(row);
  }, 500);
};
const close = () => {
  if (flag.value) emit("closeDialog");
};
const closeBox = () => {
  dialogVisible.value = true;
  setTimeout(() => {
    flag.value = true;
  }, 500);
};

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: space-between;
}
</style>
