<template>
  <div class="titleBox">暂降事件列表</div>

  <el-form inline="true" class="positioning">
    <el-form-item label="关键字筛选" style="margin-right: 10px">
      <el-input clearable style="width: 150px" v-model="searchValue" size="small" placeholder="电站、测点、用户信息"></el-input>
    </el-form-item>

    <el-form-item style="margin-right: 10px">
      <el-popover placement="bottom" :width="550" trigger="click">
        <template #reference>
          <el-button size="small" :icon="DArrowRight" type="primary" style="margin-right: 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-select v-model="deptsIndex" placeholder="请选择运维单位" clearable size="small" :teleported="false"
              style="width: 150px">
              <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 clearable size="small" :teleported="false" v-model="eventForm.eventtype" placeholder="请选择触发类型"
              style="width: 150px">
              <el-option v-for="item in eventTypeList" :label="item.label" :value="item.value"
                :key="item.value"></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-button style="margin-right: 10px" size="small" :icon="Search" type="primary"
        @click="init(true)">查询</el-button>
      <el-button size="small" type="warn" style="margin-right: 10px" :icon="RefreshLeft"
        @click="clearInit()">重置</el-button>
      <el-button type="primary" :icon="Download" @click="  exportVisible = true;" size="small">导出
      </el-button>
    </el-form-item>
  </el-form>
  <div class="tableBox" v-loading="loading" element-loading-background="#343849c7">
    <el-table :scrollbar-always-on="true" :data="dropList" height="270px" stripe highlight-current-row size="small"
      :header-cell-style="{ textAlign: 'center' }" border @current-change="handleCurrentChange">
      <el-table-column type="index" width="60" align="center" label="序号">
        <template #default="scope">
          {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="timeid" align="center" label="发生时间" width="160" sortable>
        <template #default="scope">{{ scope.row.timeid }}.{{ scope.row.ms }}
        </template>
      </el-table-column>
      <el-table-column prop="bdname" align="center" label="变电站" show-overflow-tooltip sortable />
      <el-table-column prop="busName" align="center" label="母线" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="pointname" align="center" label="监测点" show-overflow-tooltip />
      <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="70" label="触发类型">
        <template #default="scope">

          {{ filteWavetype(scope.row.wavetype) }}

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

      <el-table-column prop="address" align="center" label="操作" width="80">
        <template #default="scope">

          <el-button size="small" type="primary" link @click.stop="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 :close-on-click-modal="false" draggable v-model="dialogVisible" title="详情" width="950">
    <div class="titleBox1">暂降事件信息</div>
    <el-descriptions :column="3" size="small" style="margin-bottom: 10px" label-width="120px" border>
      <el-descriptions-item label="发生时间">{{ dataRow.timeid + "." + dataRow.ms }}
      </el-descriptions-item>
      <el-descriptions-item label="变电站">{{ dataRow.bdname }}
      </el-descriptions-item>
      <el-descriptions-item label="监测点">{{ dataRow.pointname }}
      </el-descriptions-item>
      <el-descriptions-item label="用户">{{ dataRow.objName || "/" }}
      </el-descriptions-item>
      <el-descriptions-item label="残余电压">
        {{ Math.floor(dataRow.eventvalue * 10000) / 100 }}%
      </el-descriptions-item>
      <el-descriptions-item label="持续时间">
        {{ dataRow.persisttime }}s
      </el-descriptions-item>
    </el-descriptions>
    <div class="titleBox1 mt20">反馈信息</div>
    <el-descriptions :column="3" size="small" style="margin-bottom: 10px" label-width="120px" border>
      <el-descriptions-item label="是否影响敏感用户">
        <el-tag type="primary" v-if="detailList.isSensitive == 1" size="small" effect="dark">是
        </el-tag>
        <el-tag type="primary" v-else effect="dark">否</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="影响敏感用户名称" v-if="detailList.isSensitive == 1">{{ detailList.objName || "/" }}
      </el-descriptions-item>
      <el-descriptions-item label="影响原因" v-if="detailList.isSensitive == 1">
        {{ detailList.influenceFactors || "/" }}
      </el-descriptions-item>
      <el-descriptions-item label="处理时间">{{ detailList.dealDate || "/" }}
      </el-descriptions-item>
      <el-descriptions-item label="处理方案">{{ detailList.dealScheme || "/" }}
      </el-descriptions-item>
      <el-descriptions-item label="备注">{{ detailList.remark || "/" }}
      </el-descriptions-item>
    </el-descriptions>
    <div class="titleBox1 mt20">短信发送信息</div>
    <div class="tableBox" style="padding: 0">
      <el-table :scrollbar-always-on="true" :data="detailList.msgList" height="300px" size="small" stripe
        :header-cell-style="{ textAlign: 'center' }" border>
        <el-table-column prop="sendTime" align="center" label="发送时间" width="160" sortable />
        <el-table-column prop="userName" align="center" label="接收人" width="100" sortable />
        <el-table-column prop="phone" align="center" label="手机号" width="100" sortable />

        <el-table-column prop="msgContent" label="发送内容" />
      </el-table>
    </div>
  </el-dialog>
  <!-- 趋势图 -->
  <el-dialog :close-on-click-modal="false" draggable v-model="trendVisible" v-if="trendVisible" title="波形" width="70%">
    <waveForm ref="waveFormRef" />
  </el-dialog>
  <!-- 导出 -->
  <el-dialog :close-on-click-modal="false" draggable v-model="exportVisible" title="导出" width="500"
    @close="exportClose">
    <div class="mb10 ml20 mt10">
      <el-radio-group v-model="exportRadio" size="small">
        <el-radio-button label="默认导出" value="0" />
        <el-radio-button label="按时间段导出" value="1" />
        <el-radio-button label="按时间点导出" value="2" />
      </el-radio-group>

      <div class="mt10">

        <el-form label-width="auto">

          <!-- <el-form-item label="重要敏感用户:" v-if="exportRadio != '0'">
            <el-tree-select v-model="treeData" :data="treeList" multiple :render-after-expand="false" show-checkbox    size="small"
              style="width: 200px" />
          </el-form-item> -->
          <el-form-item label="时间段:" v-if="exportRadio == '1'">
            <el-date-picker v-model="timePeriod" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              size="small" end-placeholder="结束时间" :disabled-date="disabledDate" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>

          <el-form-item label="时间点:" v-if="exportRadio == '2'">
            <el-date-picker v-model="timePoint" type="datetime" placeholder="请选择时间" :disabled-date="disabledDate"
              size="small" style="width: 200px;" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="聚合精度(秒):" v-if="exportRadio == '2'">
            <el-input-number v-model="timeInterval" :min="0" :step="1" size="small" style="width: 200px;" />

          </el-form-item>
        </el-form>
      </div>
    </div>


    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" class="mr10" @click="exportClose" :icon="Close">取消</el-button>
        <el-button type="primary" :icon="Check" size="small"
          @click="exportRadio == '0' ? exportTable() : exportTable2()" :loading="exportLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, getCurrentInstance, reactive, computed } from "vue";

import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import waveForm from "@/components/BX/waveForm.vue";
import { DArrowRight, Search, RefreshLeft, Download, Close, Check } from "@element-plus/icons-vue";
import { getDateRange } from "@/utils/index"; //引入封装好的
import * as XLSX from "xlsx";
const store = useStore();
import {
  eventPage,
  eventMsgDetail,
  msgHandle,
  regionDevCount,
  eventPageExport
} from "@/api/statistics/index";
const emit = defineEmits(["handleCurrentChange"]);
const dropList = ref([]);
const waveFormRef = ref();
const detailList: any = ref({});
const dataRow: any = ref({});
const treeData: any = ref([]);
const treeList: any = ref([]);
const trendVisible = ref(false);
const form: any = ref({
  eventIndex: "", //id
  isSensitive: 1, //是否影响敏感用户不可为空
  influenceFactors: "", //原因
  dealDate: "", //处理时间
  dealScheme: "", //方案”
  remark: "", //备注
});
const pageNum = ref(1);
const pageSize = ref(20);
const formRef = ref();
const searchValue = ref("");
const exportRadio = ref('0');
const timePeriod = ref([]);
const timePoint = ref('');
const timeInterval = ref(60);

const feedbackVisible = ref(false); //反馈
const dialogVisible = ref(false);
const exportVisible = ref(false);
const exportLoading = ref(false);
const flag = ref(0);
const total = ref(0);

const eventForm: any = reactive({
  eventValueMin: null,
  eventValueMax: null,
  eventDurationMin: null,
  eventDurationMax: null,
  eventtype: null,
});
// 禁用未来时间的函数
const disabledDate = (time) => {
  // 禁用当前时间之后的所有时间
  return time.getTime() > Date.now();
};
const typeMap = {
  "0": "扰动",
  "1": "暂降",
  "2": "暂升",
  "3": "中断",
  "4": "其他",
  "5": "录波",
};
const eventTypeList = computed(() => {
  const availableTypes = store.state.eventTypeList.map((type) => String(type));
  // 过滤并生成选项（只包含availableTypes中的类型）
  return availableTypes
    .filter((type) => typeMap.hasOwnProperty(type)) // 确保类型在映射中存在
    .map((type) => ({
      value: type, // 选项值（字符串类型，与case匹配）
      label: typeMap[type], // 选项文本
    }));
});

const deptsIndex = ref("");
const deptsList = ref([]);
// 反馈
const feedback = (row: any) => {
  form.value = {
    eventIndex: row.eventdetail_index, //id
    isSensitive: 1, //是否影响敏感用户不可为空
    influenceFactors: "", //原因
    dealDate: getDateRange(6), //处理时间
    dealScheme: "", //方案”
    remark: "", //备注
  };
  feedbackVisible.value = true;
};
const loading = ref(false);
// 提交反馈
const onSubmit = () => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      msgHandle(form.value).then((res) => {
        ElMessage({
          message: "反馈成功",
          type: "success",
        });
        init();
        feedbackVisible.value = false;
      });
    }
  });
};
// 详情
const detail = (row: any) => {
  dataRow.value = row;
  eventMsgDetail({ eventId: row.eventdetail_index }).then((res) => {
    detailList.value = res.data;
    dialogVisible.value = true;
  });
};
//点击趋势图
const trendCharts = (row: any) => {
  trendVisible.value = true;
  setTimeout(() => {
    waveFormRef.value?.open(row);
  }, 500);
};
// 过滤数据
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 handleCurrentChange = (val: any) => {
  emit("handleCurrentChange", val?.bdname);
};
const onTableSizeChange = (val: any) => {
  pageSize.value = val;
  init();
};
const onTableCurrentChange = (val: any) => {
  pageNum.value = val;
  init();
};



const initDept = () => {
  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;
  });
};

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(true);
};

const init = async (flag?: boolean) => {
  if (flag) {
    pageNum.value = 1;
    pageSize.value = 20;
  }
  loading.value = true;
  // 暂降事件列表
  await eventPage({
    deptId: deptsIndex.value || store.state.deptId,
    type: store.state.timeType,
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
    eventtype: null,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    searchValue: searchValue.value,
    ...eventForm,
    eventValueMin:
      eventForm.eventValueMin == null ? null : eventForm.eventValueMin / 100,
    eventValueMax:
      eventForm.eventValueMax == null ? null : eventForm.eventValueMax / 100,
  }).then((res) => {
    dropList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  });
};
const exportClose = () => {
  timePeriod.value = [];
  timePoint.value = '';
  exportRadio.value = '0';
  exportVisible.value = false;
}
// 导出
const exportTable = async () => {


  // 示例数据
  exportLoading.value = true;
  let columnExpor: any = [
    ["发生时间", "变电站", "母线", "监测点", "用户", "触发类型", "残余电压", '持续时间'],
  ];

  let list = [];

  await eventPage({
    deptId: deptsIndex.value || store.state.deptId,
    type: store.state.timeType,
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
    eventtype: null,
    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.timeid + '.' + item.ms,
        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, '暂降事件列表');

    // 写出文件
    XLSX.writeFile(workbook, '暂降事件列表' + ".xlsx");
  });
  exportLoading.value = false;
  exportClose()
}
const exportTable2 = async () => {
  let searchBeginTime = ''
  let searchEndTime = ''
  if (exportRadio.value == '1') {
    if (timePeriod.value.length == 0) {
      return ElMessage({
        message: "请选择时间段",
        type: "warning",
      });
    } else {
      searchBeginTime = timePeriod.value[0]
      searchEndTime = timePeriod.value[1]
    }
  } else if (exportRadio.value == '2') {
    if (timePoint.value == '') {
      return ElMessage({
        message: "请选择时间点",
        type: "warning",
      });
    } else {
      const result = calculateTimeOffsets(timePoint.value);
      searchBeginTime = result.before
      searchEndTime = result.after
    }
  }
  exportLoading.value = true;


  // 示例数据
  let columnExpor: any = [
    ["暂态事件发生时刻", "供电公司", "变电站", "母线", "电压等级", "残余电压", '持续时间', '所带重要敏感用户'],
  ];

  let list = [];

  await eventPageExport({
    deptId: deptsIndex.value || store.state.deptId,
    searchBeginTime: searchBeginTime,
    searchEndTime: searchEndTime,
  }).then((res) => {

    if (res.data.length == 0) {
      ElMessage({
        message: "暂无数据!",
        type: "warning",
      });
    } else {
      let data = res.data.map((item) => {
        return [
          item.timeid + '.' + item.ms,
          item.gdName,
          item.bdname,
          item.busName,
          item.busVoltageLevel,
          Math.floor(item.eventvalue * 10000) / 100 + '%',
          Math.floor(item.persisttime * 1000) / 1000 + 's',
          item.objName || "/",
        ];
      });
      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");
    }

  });
  exportLoading.value = false;
  exportClose()
}
// 计算时间
function calculateTimeOffsets(inputTime) {
  // 解析输入时间字符串
  const date = new Date(inputTime);
  // 计算时间偏移（1秒 = 1000毫秒，30秒 = 30000毫秒）
  const originalTime = date.getTime();
  const before = new Date(originalTime - timeInterval.value * 1000);
  const after = new Date(originalTime + timeInterval.value * 1000);

  // 格式化时间为 "yyyy-MM-dd HH:mm:ss" 格式
  const formatTime = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 返回结果
  return {
    before: formatTime(before),
    after: formatTime(after)
  };
}



onMounted(() => {
  //   renderChart();
  initDept();
});
defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
@use "@/assets/scss/index.scss";

.form {
  .react-right {
    width: 50px !important;
    line-height: 20px !important;
    font-size: 14px !important;
  }
}

:deep(.el-descriptions__content) {
  width: 20%;
}

.titleBox1 {
  background-color: #0a73ff40;

  height: 30px;
  line-height: 30px;
  font-weight: 600;
  padding-left: 10px;
  margin-bottom: 10px;
  border-left: 10px solid var(--el-color-primary);
}

:deep(.el-button + .el-button) {
  margin-left: 2px !important;
}

:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: #456a91de !important;
}

.positioning {
  position: absolute;
  top: 1px;
  right: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 5px;
}
</style>
