<template>
  <div>
    <div class="title">
      <el-select
        v-model="Singlevalue"
        collapse-tags
        :placeholder="$t('Alarm.Selectstation')"
        popper-class="custom-header"
        :max-collapse-tags="1"
        class="Space_content"
        size="large"
        @change="postemsDevice"
      >
        <el-option v-for="(item, index) in cities" :key="index" :label="item.stationName" :value="item.id" />
        <template #prefix>
          {{ (cities.find(s => s.id === Singlevalue) || {}).stationName }}
        </template>
      </el-select>
      <!-- <div class="title_"></div> -->
      <!-- <el-select
        v-model="emsDeviceId"
        collapse-tags
        placeholder="选择编号"
        popper-class="custom-header"
        :max-collapse-tags="1"
        class="Space_content"
        size="large"
        @change="getstationrealtime"
      >
        <template #prefix>
          {{ (emsDevice.find(s => s.id === emsDeviceId) || {}).id }}
        </template>
        <el-option v-for="item in emsDevice" :key="item.id" :label="item.emsDeviceId" :value="item.id" />
      </el-select> -->
    </div>
    <div class="faultalarm">
      <el-card>
        <template #header>
          <div class="card-header">
            <div>{{ $t("Alarm.Selectstation") }}</div>
          </div>
        </template>
        <div class="chart">
          <div ref="todaysalarm" class="todaysalarm"></div>
          <div ref="alarmlevel" class="alarmlevel"></div>
          <div ref="equipmenttype" class="equipmenttype"></div>
        </div>
        <div class="Alarmlist">
          <div class="Alarmlist_Alarm">{{ $t("Alarm.AlarmList") }}</div>
          <div class="screen">
            <div class="screen_1">
              <div>{{ $t("Alarm.Equipmentnumber") }}：</div>
              <el-select
                v-model="emsDeviceId"
                :placeholder="$t('Alarm.Pleaseprovide')"
                size="large"
                style="width: 240px"
                clearable
              >
                <el-option v-for="item in emsDevice" :key="item.id" :label="item.emsDeviceId" :value="item.id" />
              </el-select>
            </div>
            <div class="screen_1">
              <div>{{ $t("Alarm.DeviceType") }}：</div>
              <el-select v-model="quipment" :placeholder="$t('Alarm.Pleaseselect')" size="large" style="width: 240px" clearable>
                <el-option v-for="item in quipmentlist" :key="item.daviceClass" :label="item.name" :value="item.daviceClass" />
              </el-select>
            </div>
            <div class="screen_1">
              <div>{{ $t("Alarm.Alarmlevel") }}：</div>
              <el-select v-model="alarm" :placeholder="$t('Alarm.Pleaselevel')" size="large" style="width: 240px" clearable>
                <el-option v-for="item in alarmlist" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </div>
            <div class="screen_1">
              <div>{{ $t("Alarm.state") }}：</div>
              <el-select v-model="alarmstatus" :placeholder="$t('Alarm.thestatus')" size="large" style="width: 240px" clearable>
                <el-option v-for="item in alarmstatuslist" :key="item.todayId" :label="item.name" :value="item.todayId" />
              </el-select>
            </div>
            <!-- <div class="screen_1">
              <div>处理建议：</div>
              <el-select v-model="proposal" placeholder="请选择处理建议" size="large" style="width: 240px">
                <el-option v-for="item in proposallist" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
              </el-select>
            </div> -->
          </div>
          <div class="screentime">
            <div class="screen_1">
              <div>{{ $t("Alarm.TimeRange") }}：</div>
              <el-date-picker
                size="large"
                v-model="timevalue"
                type="daterange"
                :shortcuts="shortcuts"
                :start-placeholder="$t('Alarm.StartTime')"
                :end-placeholder="$t('Alarm.EndTime')"
                :default-value="timevalue"
                value-format="YYYY-MM-DD hh:mm:ss"
                :disabled-date="pickerOptions"
              />
            </div>
            <div class="screen_1">
              <el-button type="primary" @click="getpostpageInfo">{{ $t("Alarm.Query") }}</el-button>
              <el-button @click="onexport">{{ $t("Alarm.export") }}</el-button>
              <el-button @click="onreset">{{ $t("Alarm.Reset") }}</el-button>
            </div>
          </div>
          <div class="eltable">
            <el-table :data="tableData.records" style="width: 100%" border>
              <el-table-column prop="eid" label="设备编号" width="240" />
              <el-table-column prop="deviceName" label="设备类型" width="180" />
              <el-table-column prop="alarmname" label="告警等级" width="180" />
              <el-table-column prop="title" label="告警内容" />
              <!-- <el-table-column prop="kehu" label="客户告警" /> -->
              <!-- <el-table-column prop="handlingdictName" label="处理建议" /> -->
              <el-table-column prop="startDate" label="发生时间" />
              <el-table-column prop="endDate" label="复位时间" />
              <el-table-column prop="todayname" label="状态">
                <template #default="scope">
                  {{ scope.row.todayname == 1 ? "已恢复" : "未恢复" }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="example_block">
            <Pagination
              :pageable="pageable"
              :handle-size-change="handleSizeChange"
              :handle-current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<!--

-->
<script setup lang="ts">
import { onMounted, Ref, ref } from "vue";
import {
  stationstationName,
  postemsSystemsingleStation,
  todayAlarm,
  postalarmLevel,
  postdeviceClass,
  posthandlingSugg,
  postpageInfo,
  pageInfoexcelURL
} from "@/api/home/Multisite";
import Pagination from "@/components/ProTable/components/Pagination.vue";

import * as echarts from "echarts";
import { Station } from "@/api/interface";

const currentDate = ref();
const Singlevalue = ref("");
const cities: Ref<Station.todo[]> = ref([]);
const emsDevice: Ref<any[]> = ref([]);
const emsDeviceId = ref("");
const poststationstationName = async () => {
  const { data } = await stationstationName({});
  Singlevalue.value = data[0].id;
  cities.value = data;
  postemsDevice(Singlevalue.value);
};
const postemsDevice = async (value: any) => {
  emsDevice.value = [];
  const { data } = await postemsSystemsingleStation({}, value);
  // emsDeviceId.value = data[0].id;
  emsDevice.value = data;
  getstationrealtime();
};
const getstationrealtime = async () => {
  gettodayAlarm();
  getalarmLevel();
  getpostdeviceClass();
  getpostpageInfo();
};
// 告警列表筛选
const quipmentlist = ref();
const alarmlist = ref();
const alarmstatuslist = ref();
const proposallist = ref();
// 告警图表

const todaysalarm = ref();
const alarmlevel = ref();
const equipmenttype = ref();
// 今日告警
const gettodayAlarm = async () => {
  const { data } = await todayAlarm({ stationId: Singlevalue.value, emsId: emsDeviceId.value });
  let list = data.map(function (item) {
    return {
      value: item.cnt, // 将 cnt 键修改为 value
      name: item.name,
      todayId: item.todayId
    };
  });
  alarmstatuslist.value = list;
  setTimeout(function () {
    baropPiechart(list);
  }, 500);
};
const baropPiechart = (list: string | any[]) => {
  let piechart = echarts.init(todaysalarm.value);
  window.addEventListener(
    "resize",
    () => {
      piechart.resize();
    },
    false
  );
  let option1 = {
    tooltip: {
      trigger: "item"
    },
    title: [
      {
        text: "今日告警",
        right: "55px", // 设置标题水平居中
        top: "40px", // 设置标题距离容器顶部的距离
        textStyle: {
          fontSize: 14,
          fontWeight: "bold"
        }
      }
    ],
    legend: {
      show: true,
      orient: "vertical",
      right: "0%",
      bottom: "40%",
      icon: "circle",
      textStyle: {
        fontSize: 14,
        rich: {
          a: {
            fontSize: 14
          }
        }
      },
      formatter: function (name: string) {
        for (let index = 0; index < list.length; index++) {
          if (name == list[index].name) {
            return `${name + " " + " " + "" + " "} {a|${list[index].value}} 条`;
          }
        }
      }
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["30%", "50%"],
        avoidLabelOverlap: false,
        label: {
          fontSize: 0,
          show: false
        },

        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: list
      }
    ]
  };

  piechart.setOption(option1);
};
// 告警等级-
const getalarmLevel = async () => {
  const { data } = await postalarmLevel({ stationId: Singlevalue.value, emsId: emsDeviceId.value });
  let list = data.map(function (item) {
    return {
      value: item.cnt, // 将 cnt 键修改为 value
      name: item.name,
      code: item.code
    };
  });
  alarmlist.value = list;
  setTimeout(function () {
    gradechart(list);
  }, 500);
};
// 告警等级

const gradechart = (list: string | any[]) => {
  let grade = echarts.init(alarmlevel.value);
  window.addEventListener(
    "resize",
    () => {
      grade.resize();
    },
    false
  );
  let option1 = {
    tooltip: {
      trigger: "item"
    },
    title: [
      {
        text: "告警等级",
        right: "55px", // 设置标题水平居中
        top: "40px", // 设置标题距离容器顶部的距离
        textStyle: {
          fontSize: 14,
          fontWeight: "bold"
        }
      }
    ],
    legend: {
      show: true,
      orient: "vertical",
      right: "0%",
      bottom: "30%",
      icon: "circle",
      textStyle: {
        fontSize: 14,
        rich: {
          a: {
            fontSize: 14
          }
        }
      },
      formatter: function (name: string) {
        for (let index = 0; index < list.length; index++) {
          if (name == list[index].name) {
            return `${name + " " + " " + "" + " "} {a|${list[index].value}} 条`;
          }
        }
      }
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["30%", "50%"],
        avoidLabelOverlap: false,
        label: {
          fontSize: 0,
          show: false
        },

        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: list
      }
    ]
  };

  grade.setOption(option1);
};
// 设备类型
const getpostdeviceClass = async () => {
  const { data } = await postdeviceClass({ stationId: Singlevalue.value, emsId: emsDeviceId.value });
  let list = data.map(function (item) {
    return {
      value: item.cnt, // 将 cnt 键修改为 value
      name: item.name,
      daviceClass: item.daviceClass
    };
  });

  quipmentlist.value = list;
  setTimeout(function () {
    equipmentchart(list);
  }, 500);
};
// 设备类型
const equipmentchart = (list: string | any[]) => {
  console.log(list);

  let equipment = echarts.init(equipmenttype.value);
  window.addEventListener(
    "resize",
    () => {
      equipment.resize();
    },
    false
  );
  let option1 = {
    tooltip: {
      trigger: "item"
    },
    title: [
      {
        text: "设备类型",
        left: "320px", // 设置标题水平居中
        top: "40px", // 设置标题距离容器顶部的距离
        textStyle: {
          fontSize: 14,
          fontWeight: "bold"
        }
      }
    ],
    legend: [
      {
        show: true,
        left: "320px",
        bottom: "0%",
        icon: "circle",
        orient: "vertical",
        textStyle: {
          fontSize: 14,
          rich: {
            a: {
              fontSize: 14
            }
          }
        },
        data: list,
        formatter: function (name: string) {
          console.log(list);

          for (let index = 0; index < list.length; index++) {
            if (name == list[index].name) {
              return `${name + " " + " " + "" + " "} {a|${list[index].value}} 条`;
            }
          }
        }
      }
    ],
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["30%", "50%"],
        avoidLabelOverlap: false,
        label: {
          fontSize: 0,
          show: false
        },

        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: list
      }
    ]
  };

  equipment.setOption(option1);
};
const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};

const quipment = ref();
const alarm = ref("");
// const proposal = ref("");
const alarmstatus = ref("");
const timevalue: Ref<any> = ref([]);
const shortcuts = ref([
  {
    text: "过去7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  },
  {
    text: "过去1个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    }
  },
  {
    text: "过去3个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    }
  }
]);
// 处理建议

const getposthandlingSugg = async () => {
  const { data } = await posthandlingSugg({});
  proposallist.value = data;
};
// 数据列表
const tableData = ref();
// 查询
const pageable = ref({
  ps: 10,
  pn: 1,
  total: 0
});
const handleSizeChange = async (e: any) => {
  pageable.value.ps = e;
  getpostpageInfo();
};
const handleCurrentChange = async (e: any) => {
  pageable.value.pn = e;

  getpostpageInfo();
};
const getpostpageInfo = async () => {
  let obj = {
    stationId: Singlevalue.value,
    emsId: emsDeviceId.value,
    pn: pageable.value.pn,
    ps: pageable.value.ps,
    alarmId: alarm.value,
    // handlingId: proposal.value,
    todayId: alarmstatus.value,
    startDate: timevalue.value[0],
    endDate: timevalue.value[1],
    devicesId: quipment.value
  };
  const { data } = await postpageInfo(obj);
  tableData.value = data;
  pageable.value.total = tableData.value.total;
};
const onexport = async () => {
  let obj = {
    stationId: Singlevalue.value,
    emsId: emsDeviceId.value,
    alarmId: alarm.value,
    // handlingId: proposal.value,
    todayId: alarmstatus.value,
    startDate: timevalue.value[0],
    endDate: timevalue.value[1],
    devicesId: quipment.value
  };
  const { data } = await pageInfoexcelURL(obj);
  downloadxlsx(data);
};
const downloadxlsx = (data: any) => {
  let fileUrl = `download/${data.msg}`;
  const date = new Date();
  const hours = formatTime(date.getHours());
  const minutes = formatTime(date.getMinutes());
  const seconds = formatTime(date.getSeconds());
  let fileName = `${currentDate.value} ${hours}：${minutes}：${seconds}故障报表.xlsx`;
  fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
      // 创建一个临时的URL对象
      const url = URL.createObjectURL(blob);
      // 创建一个隐藏的<a>标签，并设置其href属性为临时URL
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName; // 设置下载的文件名
      a.style.display = "none";
      // 将<a>标签添加到文档中，并模拟点击下载
      document.body.appendChild(a);
      a.click();
      // 下载完成后，移除<a>标签和临时URL对象
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    })
    .catch(error => {
      console.error("下载文件时出错:", error);
    });
};
const formatTime = (time: number) => {
  return time < 10 ? `0${time}` : time; // 如果时间小于 10，在前面加上 0
};
// 重置
const onreset = async () => {
  quipment.value = "";
  alarm.value = "";
  alarmstatus.value = "";
  // proposal.value = "";
  timevalue.value[0] = "";
  timevalue.value[1] = "";
  emsDeviceId.value = "";
  getpostpageInfo();
};
onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
  }
  poststationstationName();
  getposthandlingSugg();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
<!--

-->
