<template>
  <el-card>
    <el-space wrap :size="30">
      <div class="search-input">
        <span class="lable">类型：</span>
        <el-select
          v-model="state.typeVal"
          clearable
          size="mini"
          style="width: 100px"
          placeholder="全部"
          popper-class="select"
          @change="typechange"
        >
          <el-option
            v-for="item in state.typeList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>
      </div>
      <div class="search-input" v-if="!isStation">
        <span class="lable">场站：</span>
        <el-select
          v-model="state.stationId"
          clearable
          style="width: 150px"
          size="mini"
          placeholder="全部"
          popper-class="select"
          @change="getWindturbineList()"
        >
          <el-option
            v-for="item in stationList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </div>
      <div class="search-input" v-show="state.isshowwindturbineName">
        <span class="lable">机组：</span>
        <el-select
          v-model="state.windturbineId"
          clearable
          style="width: 150px"
          size="mini"
          placeholder="全部"
          popper-class="select"
        >
          <el-option
            v-for="item in state.windturbineList"
            :key="item.id"
            :value="item.id"
            :label="item.windturbineCode"
          >
          </el-option>
        </el-select>
      </div>
      <div class="search-input">
        <span class="lable">关键字：</span>
        <el-input
          v-model="state.keywords"
          style="width: 100px"
          size="mini"
        ></el-input>
      </div>
      <div class="search-input">
        <span class="lable">日期：</span>
        <el-date-picker
          v-model="state.dateTime"
          size="mini"
          type="datetimerange"
          range-separator="-"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始"
          end-placeholder="结束"
        >
        </el-date-picker>
      </div>

      <el-button type="primary" size="mini" @click="getAlarmHistoryt"
        >查询</el-button
      >
      <el-button size="mini" type="primary" @click="export2Excel"
        :disabled="state.tableData?.length == 0 ? true : false">
        导出</el-button
      >
    </el-space>
  </el-card>
  <el-table
    :data="state.tableData"
    height="70vh"
    style="width: 100%; margin-top: 10px"
  >
    <el-table-column prop="alertTime" label="时间" width="180px">
      <template #default="scope">
        {{ formatTime(scope.row.alertTime) }}
      </template>
    </el-table-column>

    <el-table-column prop="stationName" label="场站" width="180px" />
    <el-table-column
      label="机组"
      prop="windturbineName"
      v-if="state.isshowwindturbineName"
      width="180px"
    />
    <el-table-column prop="alertText" label="报警信息" />
    <el-table-column prop="rank" label="级别" width="80px">
      <template #default="scope">
        {{ tableFilter(scope.row.rank) }}
      </template>
    </el-table-column>
    <el-table-column prop="messageType" label="类型" width="80px">
      <template #default="scope">
        {{ messageTypeFilter(scope.row.messageType) }}
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination">
    <el-pagination
      background
      layout="total, prev, pager, next"
      hide-on-single-page
      :current-page="query.page"
      :page-size="query.limit"
      :total="query.pageTotal"
      @current-change="handlePageChange"
    ></el-pagination>
  </div>
</template>

<script setup>
import { watch, reactive, nextTick, computed, onMounted } from "vue";
import dayjs from "dayjs";
import { alarm_history,new_alarm_history, fetchWindturbineList } from "/@/api/api.js";
import { ElMessage } from "element-plus";
import { initWebSocket } from "/@/websocket/indextest";
import { outExportExcel } from "/@/utils/exportExcel"; //引入文件
import { useStore } from "vuex";

const store = useStore();
const endtime = new Date();
const starttime = new Date(endtime - 1 * 24 * 60 * 60 * 1000);
const stationList = computed(() => store.state.stationList);
const isStation = computed(() => store.getters.isStation);

onMounted(() => {});

watch(
  () => stationList,
  (val, old) => {
    val.value[0] &&
      nextTick(async () => {
        state.stationId = val.value[0]?.id;
        state.dateTime[0] = formatTime(starttime);
        state.dateTime[1] = formatTime(endtime);
        await getWindturbineList();
        await getAlarmHistoryt();
      });
  },
  {
    deep: true,
    immediate: true,
  }
);
const state = reactive({
  typeList: [
    // {
    //   label: "升压站",
    //   value: "SYZ",
    // },
    {
      label: "自定义",
      value: "custom",
    },
    {
      label: "风机",
      value: "windturbine",
    },
  ],
  typeVal: "",
  stationId: "",
  windturbineList: [],
  windturbineId: "",
  keywords: "",
  dateTime: [],
  startDate: null,
  endDate: null,
  tableData: [],
  isshowwindturbineName: true,
});
const query = reactive({
  page: 1,
  limit: 15,
  pageTotal: null,
});

// 获取历史记录表
const getAlarmHistoryt = async () => {
  let params = {
    pagenum: query.page,
    pagesize: query.limit,
    stationid: state.stationId,
    windturbineid: state.typeVal == "SYZ" ? "" : state.windturbineId,
    category1: state.typeVal,
    category2: "",
    rank: null,
    keyword: state.keywords,
    starttime: state.dateTime[0],
    endtime: state.dateTime[1],
  };
  const { data } = await alarm_history(params);
  query.pageTotal = data?.total;
  state.tableData = data?.records;
};
const typechange = () => {
  state.isshowwindturbineName = state.typeVal == "SYZ" ? false : true;
};
//get 风机
const getWindturbineList = async () => {
  state.windturbineList = [];
  state.windturbineId = "";
  const res = await fetchWindturbineList(state.stationId);
  state.windturbineList = res;
};

// 批量导出
const export2Excel = async () => {
  let params = {
    pagenum: 1,
    pagesize: 999999,
    stationid: state.stationId,
    windturbineid: state.typeVal == "SYZ" ? "" : state.windturbineId,
    category1: state.typeVal,
    category2: "",
    rank: null,
    keyword: state.keywords,
    starttime: state.dateTime[0],
    endtime: state.dateTime[1],
  };

  if (endtime - starttime > 6 * 24 * 60 * 60 * 1000) {
    this.$message({
      message: "导出时间范围不能大于7天",
      type: "warning",
    });
  } else {
    const file = await new_alarm_history(params);
    let blob = new Blob([file], {
      type: "application/zip", // 这边的类型需要改
    });
    const stationName = stationList.value.find((ele) => {
      return ele.id === state.stationId;
    }).name;
    const fileName = `${stationName} ${state.dateTime[0].replace(/_/g,':')} ~ ${state.dateTime[1].replace(/_/g,':')} 数据表`;

    let url = window.URL.createObjectURL(blob);
    let link = document.createElement("a");
    link.style.display = "none";
    link.download = fileName; 
    link.href = url;
    document.body.appendChild(link);
    link.click();
    ElMessage.success(`导出成功!`);
  }
};
// 分页导航
const handlePageChange = (val) => {
  query.page = val;
  getAlarmHistoryt();
};
// 时间格式化
const formatTime = (val) => {
  return dayjs(val).format("YYYY-MM-DD HH:mm:ss");
};
// 格式化
const obj = {
  1: "低级",
  2: "中低级",
  3: "中级",
  4: "中高级",
  5: "高级",
  SYZ: "升压站",
  custom: "自定义",
  windturbine: "风机",
};
const messageTypeObj = {
  1: "触发",
  3: "解除",
};
const tableFilter = (val) => {
  return obj[val];
};
const messageTypeFilter = (val) => {
  return messageTypeObj[val];
};
</script>

<style lang="scss" scoped>
</style>