<template>
  <el-dialog    :close-on-click-modal="false" draggable v-model="dialogVisible" :title="title" width="70%">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane
        :label="item.name"
        v-for="(item, index) in column"
        :name="item.key"
      >
        <el-form :inline="true" class="formFlex">
          <div>
            <el-form-item label="关键字筛选">
              <el-input
                clearable
                style="width: 150px"
                v-model="searchValue"
                @input="handleSearch"
                @clear="handleClear"
                size="small"
                placeholder="请输入搜索内容"
              ></el-input>
            </el-form-item>
            <el-form-item label="通讯状态" v-if="activeName == '0'">
              <el-select
                v-model="runFlag"
                placeholder="请选择通讯状态"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="正常" value="1"></el-option>
                <el-option label="中断" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="触发类型" v-if="activeName == '1'">
              <el-select
                v-model="wavetype"
                placeholder="请选择触发类型"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="扰动" value="0"></el-option>
                <el-option label="暂降" value="1"></el-option>
                <el-option label="暂升" value="2"></el-option>
                <el-option label="中断" value="3"></el-option>
                <el-option label="其他" value="4"></el-option>
                <el-option label="录波" value="5"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="触发类型" v-if="activeName == '1'">
              <el-select
                v-model="eventSeverity"
                placeholder="请选择触发类型"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="告警" value="1"></el-option>
                <el-option label="预警" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否远程通知" v-if="activeName == '1'">
              <el-select
                v-model="msgEventInfoSize"
                placeholder="请选择是否远程通知"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否处置" v-if="activeName == '2'">
              <el-select
                v-model="isHandle"
                placeholder="请选择是否处置"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发送结果" v-if="activeName == '2'">
              <el-select
                v-model="sendResult"
                placeholder="请选择"
                size="small"
                clearable
                @change="
                  handleSearch();
                  handleClear();
                "
                style="width: 100px"
              >
                <el-option label="成功" value="1"></el-option>
                <el-option label="失败" value="0"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <el-button
            type="primary"
            :icon="Download"
            @click="exportTable"
            size="small"
            >导出
          </el-button>
        </el-form>
        <div class="tableBox" style="padding: 0">
          <el-table
      :scrollbar-always-on="true"       :data="
              displayData.slice((pageNum - 1) * pageSize, pageNum * pageSize)
            "
            height="500px"
            stripe
            size="small"
              @sort-change="handleSortChange"
            :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
              v-for="(k, i) in item.columns"
              :prop="k.prop"
              show-overflow-tooltip
              :align="k.align || 'center'"
              :label="k.label"
              :width="k.width"
              :formatter="formatter"
              sortable
            >
              <template #default="{ row }">
                <span v-if="k.prop === 'lookFlag' || k.prop === 'isHandle'">
                  <el-tag
                    :type="row[k.prop] == 1 ? 'primary' : 'warning'"
                    size="small"
                    effect="dark"
                  >
                    {{ row[k.prop] == 1 ? "是" : "否" }}
                  </el-tag>
                </span>
                <span v-else-if="k.prop === 'sendResult'">
                  <el-tag
                    :type="row[k.prop] == 1 ? 'success' : 'danger'"
                    size="small"
                    effect="dark"
                  >
                    {{ row[k.prop] == 1 ? "成功" : "失败" }}
                  </el-tag>
                </span>
                <span v-else-if="k.prop === 'eventSeverity'">
                  <el-tag
                    :type="row[k.prop] == 1 ? 'danger' : 'warning'"
                    size="small"
                    effect="dark"
                  >
                    {{ row[k.prop] == 1 ? "告警" : "预警" }}
                  </el-tag>
                </span>
                <span v-else-if="k.prop === 'runFlag'">
                  <el-tag
                    :type="row[k.prop] == 0 ? 'danger' : 'success'"
                    size="small"
                    effect="dark"
                  >
                    {{ row[k.prop] == 0 ? "中断" : "正常" }}
                  </el-tag>
                </span>
                <span v-else-if="k.prop === 'devFlag'">
                  <el-tag
                    :type="
                      row[k.prop] == 0
                        ? 'success'
                        : row[k.prop] == 1
                        ? 'warning'
                        : row[k.prop] == 2
                        ? 'danger'
                        : row[k.prop] == 3
                        ? 'warning'
                        : 'info'
                    "
                    size="small"
                    effect="dark"
                  >
                    {{
                      row[k.prop] == 0
                        ? "投运"
                        : row[k.prop] == 1
                        ? "检修"
                        : row[k.prop] == 2
                        ? "停运"
                        : row[k.prop] == 3
                        ? "调试"
                        : row[k.prop] == 4
                        ? "退运"
                        : ""
                    }}
                  </el-tag>
                </span>
                <span v-else-if="k.prop === 'wavetype'">
                  <!-- <el-tag
                    :type="'primary'"
                    :color="
                      row[k.prop] == 0
                        ? '#E67E22'
                        : row[k.prop] == 1
                        ? '#F39C12'
                        : row[k.prop] == 2
                        ? '#7E57C2'
                        : row[k.prop] == 3
                        ? '#C62828'
                        : row[k.prop] == 4
                        ? '#757575'
                        : row[k.prop] == 5
                        ? '#1E88E5'
                        : ''
                    "
                    size="small"
                    effect="dark"
                  > -->
                  {{
                    row[k.prop] == 0
                      ? "扰动"
                      : row[k.prop] == 1
                      ? "暂降"
                      : row[k.prop] == 2
                      ? "暂升"
                      : row[k.prop] == 3
                      ? "中断"
                      : row[k.prop] == 4
                      ? "其他"
                      : row[k.prop] == 5
                      ? "录波"
                      : ""
                  }}
                  <!-- </el-tag> -->
                </span>
              </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="displayData.length"
            @size-change="onTableSizeChange"
            @current-change="onTableCurrentChange"
          />
        </div>
      </el-tab-pane>
      <!-- <el-tab-pane label="暂降次数" name="2">Config</el-tab-pane>
      <el-tab-pane label="远程通知数" name="3">Role</el-tab-pane> -->
    </el-tabs>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import * as XLSX from "xlsx";
import { Download } from "@element-plus/icons-vue";
import table2excel from "js-table2excel";
const dialogVisible = ref(false);

const title = ref("");
const activeName = ref("0");
const pageNum = ref(1);
const pageSize = ref(20);
const searchValue = ref("");
const runFlag = ref("");
const wavetype = ref("");
const eventSeverity = ref("");
const sendResult = ref("");
const isHandle: any = ref("");
const msgEventInfoSize: any = ref("");
// 计算属性：根据搜索条件过滤后的数据
const displayData = computed(() => {
  if (
    !searchValue.value.trim() &&
    !runFlag.value &&
    !wavetype.value &&
    !eventSeverity.value &&
    !msgEventInfoSize.value &&
    !sendResult.value &&
    !isHandle.value
  ) {
    return column.value[activeName.value].data;
  }

  const searchTerm = searchValue.value.trim().toLowerCase();

  return column.value[activeName.value].data.filter((row: any) => {
    if (runFlag.value && row.runFlag != runFlag.value) return false;
    if (wavetype.value && row.wavetype != wavetype.value) return false;
    if (sendResult.value && row.sendResult != sendResult.value) return false;
    if (eventSeverity.value && row.eventSeverity != eventSeverity.value)
      return false;
    if (
      msgEventInfoSize.value &&
      !(msgEventInfoSize.value == 1
        ? row.msgEventInfoSize > 0
        : row.msgEventInfoSize == 0)
    )
      return false;
    if (
      isHandle.value &&
      (isHandle.value == 0 ? row.isHandle == 1 : row.isHandle != isHandle.value)
    )
      return false;

    return Object.values(row).some((value) => {
      if (value === null || value === undefined) return false;
      return String(value).toLowerCase().includes(searchTerm);
    });
  });
});
const column: any = ref([
  {
    name: "监测点数",
    key: "0",
    data: [],
    columns: [
      { prop: "stationName", label: "变电站", sortable: true },
      { prop: "devName", label: "终端名称" },
      { prop: "busBarName", label: "母线名称" },
      { prop: "lineName", label: "监测点名称" },
      { prop: "runFlag", label: "通讯状态", width: 90 },
    ],
  },
  {
    name: "暂降次数",
    key: "1",
    data: [],
    columns: [
      {
        prop: "timeid",
        label: "发生时间",
        width: 180,
        sortable: true,
      },
      { prop: "bdname", label: "变电站", sortable: true },
      { prop: "pointname", label: "监测点" },
      { prop: "objName", label: "影响用户", width: 90 },
      { prop: "wavetype", label: "触发类型", width: 90 },
      {
        prop: "eventvalue",
        label: "残余电压",
        width: 100,
      },
      {
        prop: "persisttime",
        label: "持续时间",
        width: 100,
      },
      { prop: "eventSeverity", label: "告警类型", width: 90 },
      { prop: "msgEventInfoSize", label: "远程通知数", width: 110 },
    ],
  },
  // {
  //   name: "远程通知",
  //   key: "2",
  //   data: [],
  //   columns: [
  //     {
  //       prop: "sendTime",
  //       label: "发送时间",
  //       width: 180,
  //     },
  //     { prop: "userName", label: "接受人", width: 100 },
  //     { prop: "phone", label: "手机号", width: 100 },
  //     { prop: "msgContent", label: "发送内容", align: "left" },
  //     { prop: "isHandle", label: "是否反馈", width: 100 },
  //     { prop: "sendResult", label: "发送结果", width: 100 },
  //   ],
  // },
]);

const formatter = (row: any, column: any) => {
  const value = row[column.property];
  if (column.property == "timeid") {
    return row.timeid + "." + row.ms;
  } else if (column.property == "eventvalue") {
    return Math.floor(row.eventvalue * 10000) / 100 + "%";
  } else if (column.property == "persisttime") {
    return row.persisttime + "s";
  } else if (column.property == "objName") {
    return row.objName || "/";
  } else if (column.property == "wavetype") {
    return row.wavetype == 0
      ? "扰动"
      : row.wavetype == 1
      ? "暂降"
      : row.wavetype == 2
      ? "暂升"
      : row.wavetype == 3
      ? "中断"
      : row.wavetype == 4
      ? "其他"
      : row.wavetype == 5
      ? "录波"
      : "";
  }
  return value;
};
const handleClick = () => {
  searchValue.value = "";
  runFlag.value = "";
  wavetype.value = "";
  sendResult.value = "";
  isHandle.value = "";
  msgEventInfoSize.value = "";
  eventSeverity.value = "";
  pageSize.value = 20;
  pageNum.value = 1;
};


// 处理排序变化
const handleSortChange = ({ prop, order }: any) => {
  // console.log("🚀 ~ handleSortChange ~ prop, order :", prop, order);
  if (prop && order) {
    // 根据当前排序条件对所有数据进行排序
    const list = dataListCopy.value[activeName.value].data.sort((a, b) => {
      if (order === "ascending") {
        return a[prop] > b[prop] ? 1 : -1;
      } else {
        return a[prop] < b[prop] ? 1 : -1;
      }
    });
    column.value[activeName.value].data = JSON.parse(JSON.stringify(list));
  }
};
const dataListCopy = ref([]);
const open = (row: any) => {
  activeName.value = "0";
  handleClick();
  let list = JSON.parse(JSON.stringify(row));
  title.value = list.title;
  column.value[0].data = list.lineList;
  column.value[1].data = list.eventList;
  // column.value[2].data = list.noticeList;
  dataListCopy.value = JSON.parse(JSON.stringify(column.value));
  dialogVisible.value = true;
};
// 导出
const exportTable = () => {
  let columnExpor: any = [[]];
  column.value[activeName.value].columns.forEach((item: any) => {
    columnExpor[0].push(item.label);
  });
  let list = JSON.parse(JSON.stringify(displayData.value)).filter(
    (item: any) => {
      item.eventvalue = Math.floor(item.eventvalue * 10000) / 100 + "%";
      item.persisttime = item.persisttime + "s";
      item.devFlag =
        item.devFlag == 0
          ? "投运"
          : item.devFlag == 1
          ? "检修"
          : item.devFlag == 2
          ? "停运"
          : item.devFlag == 3
          ? "调试"
          : item.devFlag == 4
          ? "退运"
          : "";
      item.wavetype =
        item.wavetype == 0
          ? "扰动"
          : item.wavetype == 1
          ? "暂降"
          : item.wavetype == 2
          ? "暂升"
          : item.wavetype == 3
          ? "中断"
          : item.wavetype == 4
          ? "其他"
          : item.wavetype == 5
          ? "录波"
          : "";
      item.eventSeverity = item.eventSeverity == 1 ? "告警" : "预警";
      item.objName = item.objName || "-";
      item.runFlag = item.runFlag == 0 ? "中断" : "正常";
      item.lookFlag = item.lookFlag == 1 ? "是" : "否";
      item.isHandle = item.isHandle == 1 ? "是" : "否";
      item.sendResult = item.sendResult == 1 ? "成功" : "失败";
      item.timeid = item.timeid + "." + item.ms;
      return item;
    }
  );
  list.forEach((item, i) => {
    columnExpor.push([]);
    column.value[activeName.value].columns.forEach((column) => {
      columnExpor[i + 1].push(item[column.prop]);
    });
  });

  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(columnExpor);
  worksheet["!cols"] = columnExpor.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");
  // let columnExpor: any = [];
  // column.value[activeName.value].columns.forEach((item: any) => {
  //   columnExpor.push({
  //     title: item.label,
  //     key: item.prop,
  //     type: "text",
  //   });
  // });
  // let list = JSON.parse(
  //   JSON.stringify(displayData.value)
  // ).filter((item: any) => {
  //   item.eventvalue = Math.floor(item.eventvalue * 10000) / 100 + "%";
  //   item.persisttime = item.persisttime + "s";
  //   item.devFlag =
  //     item.devFlag == 0
  //       ? "投运"
  //       : item.devFlag == 1
  //       ? "检修"
  //       : item.devFlag == 2
  //       ? "停运"
  //       : item.devFlag == 3
  //       ? "调试"
  //       : item.devFlag == 4
  //       ? "退运"
  //       : "";
  //   item.wavetype =
  //     item.wavetype == 0
  //       ? "扰动"
  //       : item.wavetype == 1
  //       ? "暂降"
  //       : item.wavetype == 2
  //       ? "暂升"
  //       : item.wavetype == 3
  //       ? "中断"
  //       : item.wavetype == 4
  //       ? "其他"
  //       : item.wavetype == 5
  //       ? "录波"
  //       : "";
  //   item.eventSeverity = item.eventSeverity == 1 ? "告警" : "预警";
  //   item.objName = item.objName || "-";
  //   item.runFlag = item.runFlag == 0 ? "中断" : "正常";
  //   item.lookFlag = item.lookFlag == 1 ? "是" : "否";
  //   item.isHandle = item.isHandle == 1 ? "是" : "否";
  //   item.sendResult = item.sendResult == 1 ? "成功" : "失败";
  //   item.timeid = item.timeid + "." + item.ms;
  //   return item;
  // });

  // setTimeout(() => {
  //   table2excel(
  //     columnExpor,
  //     list, // 导出原始数据
  //     column.value[activeName.value].name
  //   );
  // }, 500);
};
// 搜索处理函数
const handleSearch = () => {
  console.log("搜索触发:", searchValue.value);
  pageNum.value = 1; // 重置页码为1
};

// 清空搜索处理
const handleClear = () => {
  console.log("清空搜索");
  // searchValue.value = "";
  pageNum.value = 1;
};
const onTableSizeChange = (val: any) => {
  pageSize.value = val;
};
const onTableCurrentChange = (val: any) => {
  pageNum.value = val;
};

defineExpose({
  open,
});
</script>
<style lang="scss" scoped>
@use "@/assets/scss/index.scss";
:deep(.el-form-item) {
  margin-bottom: 10px;
}
.formFlex {
  display: flex;
  justify-content: space-between;
}
</style>
