<template>
  <el-dialog
    :close-on-click-modal="false"
    draggable
    v-model="dialogVisible"
    :title="title"
    width="85%"
  >
    <el-form :inline="true" class="formFlex">
      <div>
        <el-form-item label="用户">
          <el-input
            clearable
            style="width: 130px"
            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: 130px"
          >
            <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: 130px"
          >
            <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: 130px"
          >
            <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: 130px"
          >
            <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: 130px"
          >
            <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 :icon="RefreshLeft" @click="reset" 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
        :data="dataList"
        height="500px"
        stripe
        :scrollbar-always-on="true"
        size="small"
        v-loading="loading"
        element-loading-background="#343849c7"
        :header-cell-style="{ textAlign: 'center' }"
        border
      >
        <el-table-column label="序号" align="center" type="index" width="60">
          <template #default="scope">
            <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="300"
          prop="customerName"
          label="用户"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="smallObjType"
          label="对象类型"
          align="center"
          sortable
          width="200"
        >
          <template #default="{ row }">
            {{ formatterObj(row.smallObjType) }}
          </template></el-table-column
        >
        <el-table-column
          prop="powerSupplyArea"
          label="供电区域"
          align="center"
          width="150"
        >
          <template #default="{ row }">
            {{ formatter(row.powerSupplyArea) }}
          </template></el-table-column
        >

        <el-table-column
          prop="substationName"
          label="上级电站"
          show-overflow-tooltip
          align="center"
          width="250"
        >
          <template #default="{ row }">
            <div v-if="row.substationName">
              <div
                v-for="(item, index) in row.substationName.split(';')"
                :key="index"
              >
                {{ item }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="info"
          label="上级母线"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div v-if="row.info">
              <div v-for="(item, index) in row.info.split(';')" :key="index">
                {{ item }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="eventCount"
          label="暂降次数"
          align="center"
          width="100"
          sortable
        >
          <template #default="scope">
            <div class="clickable-cell" @click="handleCellClick(scope.row)">
              {{ scope.row.eventCount }}
            </div>
          </template>
        </el-table-column>

        <!--        <el-table-column prop="status" label="通讯状态" align="center">
          <template #default="scope">
            <el-tag
              v-if="scope.row.status == 1"
              type="success"
              size="mini"
              :disable-transitions="false"
              effect="dark"
              >在线</el-tag
            >
            <el-tag
              v-else
              type="danger"
              size="mini"
              :disable-transitions="false"
              effect="dark"
              >离线</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="onLineRate"
          label="终端在线率(%)"
          align="center"
        />-->
      </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>
  <!-- 弹框 -->
  <FrequencyPopUp ref="frequencyPopUpRef" @closeDialog="dialogVisible = true" />
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import FrequencyPopUp from "@/views/VoltageSag_BJ/components/popUpFrame/frequencyPopUp.vue";
import table2excel from "js-table2excel";
import * as XLSX from "xlsx";
import {
  rightEventDevOpen,
  getDicTree,
  regionDevCount,
  gdSelect,
  bdSelect,
} from "@/api/statistics/index";
import { Download, Search, RefreshLeft } from "@element-plus/icons-vue";
import { useStore } from "vuex";
const store = useStore();
const dialogVisible = ref(false);
const loading = ref(false);
const title = ref("受影响用户_详情");
const dataList = 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 frequencyPopUpRef = ref();
const bigObjTypeList = ref([]);

const open = async (deptID: string = "") => {
  reset();
  pageNum.value = 1;
  pageSize.value = 20;

  bigObjType.value = deptID; // 清空搜索框
  dialogVisible.value = true;
  loading.value = true;
  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;
  });



  await init();
};
const init = async () => {
  loading.value = true;
  await rightEventDevOpen({
    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],
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }).then((res) => {
    dataList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  });
};

const handleCellClick = (event: any) => {
  frequencyPopUpRef.value?.open(event.eventIds);
  dialogVisible.value = false;
};

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

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 exportTable = async () => {
  // 表头
  const columnExpor = [
    ["用户", "对象类型", "供电区域", "上级电站", "上级母线", "暂降次数", "暂降发生时刻", "暂降类型","残余电压(%)","持续时间(s)","所属电站","监测母线"]
  ];

  await rightEventDevOpen({
    // 请求参数保持不变
    bigObjType: bigObjType.value,
    smallObjType: smallObjType.value,
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
    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,
    exportFlag: true
  }).then((res) => {
    // 所有行数据（包含表头和内容）
    const allRows = [...columnExpor];
    // 合并单元格配置（存储合并规则）
    const merges = [];
    // 当前行索引（从表头后开始计算，表头占1行）
    let currentRowIndex = 1;

    // 遍历每个主对象
    res.data.records.forEach((item) => {
      // 1. 提取基础信息（要合并的列）
      const baseInfo = [
        item.customerName,               // 列0：用户
        formatterObj(item.smallObjType), // 列1：对象类型
        formatter(item.powerSupplyArea), // 列2：供电区域
        item.substationName,             // 列3：上级电站
        item.info,                       // 列4：上级母线
        item.eventCount                  // 列5：暂降次数
      ];

      // 2. 处理事件列表
      const events = item.eventList || [];
      const eventCount = events.length;
      // 总合并行数 = 基础信息行 + 事件行数
      const mergeRows = eventCount > 0 ? eventCount + 1 : 1;

      // 3. 添加基础信息行（第一行）
      allRows.push([
        ...baseInfo,
        eventCount > 0 ? "（以下为暂降详情）" : "无暂降事件", // 暂降发生时刻列（提示文本）
        "" // 暂降类型列留空
      ]);

      // 4. 添加事件行（若有）
      events.forEach((event) => {
        // 事件行的基础信息列留空（后续会合并到基础信息行）
        allRows.push([
          "", "", "", "", "", "", // 基础信息列留空
          `${event.timeid}.${event.ms}`, // 暂降发生时刻
          filteWavetype(event.wavetype),  // 暂降类型
           `${Number(event.eventvalue).toFixed(2)}`,
          `${event.persisttime}`,
          `${event.stationName}`,
          `${event.busBarName}`,
        ]);
      });

      // 5. 配置合并规则（基础信息列纵向合并）
      if (mergeRows > 1) {
        // 对列0到列5（基础信息列）设置合并
        for (let col = 0; col < 6; col++) {
          merges.push({
            s: { r: currentRowIndex, c: col }, // 合并起始位置（行，列）
            e: { r: currentRowIndex + mergeRows - 1, c: col } // 合并结束位置
          });
        }
      }

      // 6. 更新当前行索引（跳过已处理的行）
      currentRowIndex += mergeRows;
    });

    // 7. 创建工作表并应用合并规则
    const worksheet = XLSX.utils.aoa_to_sheet(allRows);
    // 设置列宽
    worksheet["!cols"] = [
      { wch: 15 }, // 用户
      { wch: 12 }, // 对象类型
      { wch: 12 }, // 供电区域
      { wch: 15 }, // 上级电站
      { wch: 12 }, // 上级母线
      { wch: 10 }, // 暂降次数
      { wch: 20 }, // 暂降发生时刻
      { wch: 15 }  // 暂降类型
    ];
    // 应用合并规则
    worksheet["!merges"] = merges;

    // 8. 导出文件
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, title.value);
    XLSX.writeFile(workbook, `${title.value}.xlsx`);
  });
};

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 reset = () => {
  searchValue.value = "";
  deptsIndex.value = "";
  gdIndex.value = "";
  bdIndex.value = "";
  bigObjType.value = "";
  smallObjType.value = "";
};

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;
}
.clickable-cell {
  cursor: pointer;
  text-decoration: underline;
  text-underline-offset: 2px; /* 下划线偏移量 */
  text-decoration-color: #fff; /* 下划线颜色 */
  text-decoration-thickness: 1px; /* 下划线粗细 */
}
</style>
