<template>
  <!--暂降 -->
  <el-dialog
    :close-on-click-modal="false"
    draggable
    v-model="machineVisible"
    title="暂降事件"
    width="1000px"
  >
    <div class="tableBox">
      <el-form
        :inline="true"
        style="display: flex; justify-content: space-between"
      >
        <el-form-item label="关键字筛选">
          <el-input
            clearable
            style="width: 150px"
            v-model="searchValue"
            size="small"
            placeholder="电站、测点、用户信息"
          ></el-input>
          <el-popover placement="bottom" :width="550" trigger="click">
            <template #reference>
              <el-button
                size="small"
                :icon="DArrowRight"
                type="primary"
                style="margin-left: 10px"
                >更多</el-button
              >
            </template>

            <el-form label-width="auto">
              <!-- <el-form-item label="关键字筛选">
                <el-input
                  clearable
                  style="width: 150px"
                  v-model="searchValue"
                  size="small"
                  placeholder="电站、测点、用户信息"
                ></el-input>
              </el-form-item> -->
              <el-form-item label="运维单位">
                <el-tree-select
                  v-model="deptsIndex"
                  :data="deptsList"
                  :render-after-expand="false"
                  clearable
                  size="small"
                  style="width: 150px"
                  :props="{
                    value: 'id',
                    label: 'name',
                    children: 'children',
                  }"
                />
                <!-- <el-select
                  v-model="deptsIndex"
                  placeholder="请选择运维单位"
                  clearable
                  size="small"
                  :teleported="false"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in deptsList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="触发类型">
                <el-select
                  clearable
                  size="small"
                  :teleported="false"
                  v-model="eventForm.eventType"
                  placeholder="请选择触发类型"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in eventTypeList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="残余电压百分比">
                <el-input-number
                  v-model="eventForm.eventValueMin"
                  :min="0"
                  style="width: 150px"
                  size="small"
                  :max="100"
                  :precision="1"
                  :step="1"
                  @change="
                    (e) => (e == null ? (eventForm.eventValueMin = 1) : null)
                  "
                  ><template #suffix>
                    <span>%</span>
                  </template></el-input-number
                >
                <span>　< 残余电压 <　</span>

                <el-input-number
                  v-model="eventForm.eventValueMax"
                  :min="0"
                  style="width: 150px"
                  size="small"
                  :max="100"
                  :precision="1"
                  :step="1"
                  @change="
                    (e) => (e == null ? (eventForm.eventValueMax = 1) : null)
                  "
                  ><template #suffix>
                    <span>%</span>
                  </template></el-input-number
                >
              </el-form-item>
              <el-form-item label="暂降持续事时间">
                <el-input-number
                  v-model="eventForm.eventDurationMin"
                  :min="0"
                  style="width: 150px"
                  size="small"
                  :max="1000000"
                  :precision="1"
                  :step="1"
                  @change="
                    (e) => (e == null ? (eventForm.eventDurationMin = 1) : null)
                  "
                  ><template #suffix>
                    <span>ms</span>
                  </template></el-input-number
                >
                <span>　< 持续时间 <　</span>

                <el-input-number
                  v-model="eventForm.eventDurationMax"
                  :min="0"
                  style="width: 150px"
                  size="small"
                  :max="1000000"
                  :precision="1"
                  :step="1"
                  @change="
                    (e) => (e == null ? (eventForm.eventDurationMax = 1) : null)
                  "
                  ><template #suffix>
                    <span>ms</span>
                  </template></el-input-number
                >
              </el-form-item>
            </el-form>
          </el-popover>
        </el-form-item>

        <el-form-item style="margin-right: -10px">
          <el-button size="small" :icon="Search" type="primary" @click="init()"
            >查询</el-button
          >
          <el-button size="small" :icon="RefreshLeft" @click="clearInit()"
            >重置</el-button
          >
          <el-button
            type="primary"
            :icon="Download"
            @click="exportTable"
            size="small"
            style="margin-right: 10px"
            >导出
          </el-button>
          <el-button
            style="margin-right: 10px"
            v-if="displayValue == 1"
            size="small"
            :icon="HelpFilled"
            type="primary"
            @click="handleAggregation"
            >溯源</el-button
          >
        </el-form-item>
      </el-form>
      <!-- <div style="float: right; margin-bottom: 9px" v-if="displayValue == 1">
        <el-button
          size="small"
          :icon="HelpFilled"
          type="primary"
          @click="handleAggregation"
          >聚合</el-button
        >
      </div> -->
      <el-table
        :scrollbar-always-on="true"
        :data="tableData"
        height="443px"
        size="small"
        v-loading="loading"
        element-loading-background="#343849c7"
        :header-cell-style="{ textAlign: 'center' }"
        border
      >
        <!-- <el-table-column type="index" align="center" label="序号" width="70" /> -->
          <el-table-column label="序号" align="center" type="index" width="70">
          <template #default="scope">
            <span>{{
              (form.pageNum - 1) * form.pageSize + scope.$index + 1
              }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="startTime"
          align="center"
          label="发生时间"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column
          prop="stationName"
          align="center"
          label="变电站"
          width="120"
        />
        <el-table-column
          prop="lineName"
          align="center"
          label="监测点"
          width="120"
        />
        <el-table-column
          prop="objName"
          label="用户"
          align="center"
          show-overflow-tooltip
        >
          <template v-slot="scope">
            <span>{{ scope.row.objName ? scope.row.objName : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="eventType"
          align="center"
          label="触发类型"
          width="90"
        />
        <el-table-column
          prop="featureAmplitude"
          align="center"
          label="残余电压(%)"
          width="90"
        >
          <template v-slot="scope">
            <span>{{ (scope.row.featureAmplitude * 100).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="duration"
          align="center"
          label="持续时间(S)"
          width="90"
        />
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.stop="trendCharts(scope.row)"
              >波形</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      size="small"
      style="margin-top: 10px"
      :currentPage="form.pageNum"
      :page-size="form.pageSize"
      :page-sizes="[10, 20, 50, 100, 200]"
      background
      :layout="'sizes,total, ->, prev, pager, next, jumper'"
      :total="total"
      @size-change="onTableSizeChange"
      @current-change="onTableCurrentChange"
    ></el-pagination>
  </el-dialog>
  <!-- 波形图 -->
  <el-dialog
    :close-on-click-modal="false"
    draggable
    v-model="trendVisible"
    v-if="trendVisible"
    title="波形"
    width="70%"
    @close="handleCloseTrend"
  >
    <waveForm ref="waveFormRef" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, inject, onMounted, watch } from "vue";
import {
  getEventList,
  processEvents,
  loginDeptTree,
  getDicDataByTypeCode,
} from "@/api/manage_wx";
import { HelpFilled } from "@element-plus/icons-vue";
import waveForm from "@/components/BX/waveForm.vue";
import {
  DArrowRight,
  Search,
  RefreshLeft,
  Download,
} from "@element-plus/icons-vue";
import * as XLSX from "xlsx";

// 定义 emit
const emit = defineEmits(["aggregation-success"]);

const machineVisible = ref(false);
const form = reactive({
  pageNum: 1,
  pageSize: 20,
});
const total = ref(0); // 假设总条数为100
const loading = ref(false);
const tableData = ref([]);
import { useStore } from "vuex";

const store = useStore();

const displayValue = ref();

const trendVisible = ref(false);

const waveFormRef = ref();

const open = async (val) => {
  displayValue.value = val;
  machineVisible.value = true;
  await init();
};

// 查询
const searchValue = ref("");
const deptsIndex = ref("");
const deptsList = ref([]); //部门列表
const eventTypeList = ref([]); //触发类型
const eventForm: any = reactive({
  eventValueMin: null,
  eventValueMax: null,
  eventDurationMin: null,
  eventDurationMax: null,
  eventType: null,
});

const clearInit = async () => {
  searchValue.value = "";
  eventForm.eventValueMin = null;
  eventForm.eventValueMax = null;
  eventForm.eventDurationMin = null;
  eventForm.eventDurationMax = null;
  eventForm.eventType = null;
  deptsIndex.value = null;

  await init();
};

// 部门
const initDept = () => {
  loginDeptTree({
    deptIndex: store.state.deptId,
  }).then((res: any) => {
    deptsList.value = res.data;
  });
};

// 触发类型
const dicDataByTypeCode = () => {
  getDicDataByTypeCode({
    dictTypeCode: "Event_Statis",
  }).then((res: any) => {
    eventTypeList.value = res.data;
  });
};

const init = async () => {
  loading.value = true;
  getEventList({
    deptId: store.state.deptId,
    searchBeginTime: store.state.timeValue[0],
    searchEndTime: store.state.timeValue[1],
    pageNum: form.pageNum,
    pageSize: form.pageSize,
    searchValue: searchValue.value,
    ...eventForm,
    eventValueMin:
      eventForm.eventValueMin == null ? null : eventForm.eventValueMin / 100,
    eventValueMax:
      eventForm.eventValueMax == null ? null : eventForm.eventValueMax / 100,
  }).then((res) => {
    tableData.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  });
};

const handleAggregation = (row: any) => {
  machineVisible.value = false;
  ElMessageBox.confirm(
    `是否确认对当前用户部门${store.state.timeValue[0]}至${store.state.timeValue[1]}之间的暂降事件进行溯源?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      processEvents({
        deptId: store.state.deptId,
        searchBeginTime: store.state.timeValue[0],
        searchEndTime: store.state.timeValue[1],
      }).then((res: any) => {
        if (res.code == "A0000") {
          ElMessage({
            type: "success",
            message: res.message,
          });
          // 通知父组件执行 initialAggregation
          emit("aggregation-success");
        } else {
          ElMessage({
            type: "warning",
            message: res.message,
          });
        }
      });
    })
    .catch((error) => {});
};

//点击波形图
const trendCharts = (row: any) => {
  row.eventdetail_index = row.eventId;
  machineVisible.value = false;
  trendVisible.value = true;
  setTimeout(() => {
    waveFormRef.value?.open({
      ...row,
      bdname: row.stationName,
      pointname: row.lineName,
      timeid: row.startTime,
      eventvalue: row.featureAmplitude,
      persisttime: row.duration,
    });
  }, 500);
};

// 关闭波形图
const handleCloseTrend = () => {
  trendVisible.value = false;
  machineVisible.value = true;
};

const onTableSizeChange = (size: number) => {
  form.pageSize = size;
  init();
};
const onTableCurrentChange = (page: number) => {
  form.pageNum = page;
  init();
};

// 暂降溯源导出
const exportTable = async () => {
  let columnExpor: any = [
    [
      "发生时间",
      "变电站",
      "监测点",
      "用户",
      "触发类型",
      "残余电压(%)",
      "持续时间(S)",
    ],
  ];

  let list = [];

  await getEventList({
    deptId: store.state.deptId,
    searchBeginTime: store.state.timeValue[0],
    searchEndTime: store.state.timeValue[1],
    searchValue: searchValue.value,
    ...eventForm,
    eventValueMin:
      eventForm.eventValueMin == null ? null : eventForm.eventValueMin / 100,
    eventValueMax:
      eventForm.eventValueMax == null ? null : eventForm.eventValueMax / 100,
    pageNum: 1,
    pageSize: total.value,
  }).then((res) => {
    let data = res.data.records.map((item) => {
      return [
        item.startTime,
        item.stationName,
        item.lineName,
        item.objName,
        item.eventType,
        (item.featureAmplitude * 100).toFixed(2),
        item.duration,
      ];
    });
    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, "暂降事件");

    // 写出文件
    XLSX.writeFile(workbook, "暂降事件" + ".xlsx");
  });
};

onMounted(() => {
  initDept();
  dicDataByTypeCode();
});
defineExpose({ open });
</script>
<style lang="scss" scoped>
@use "@/assets/scss/index.scss";
.tableBox {
  padding: 0px !important;
}
.formBox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.formLeft {
  display: flex;
  align-items: center;
  color: #fff;
}
</style>
