<template>
  <div
    class="custom-warning"
    v-loading="tableLoading"
    element-loading-text="加载中..."
    element-loading-background="rgba(4, 12, 11, 0.8)"
  >
    <div class="form-wrapper">
      <div class="search-wrapper">
        <div class="search-item">
          <span class="label">场站：</span>
          <div class="search-content">
            <el-select
              v-model="state.stationId"
              clearable
              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>
        <div class="search-item">
          <span class="label">日期：</span>
          <div class="search-content">
            <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="结束"
              popper-class="date-select"
            >
            </el-date-picker>
          </div>
        </div>
        <el-button class="buttons" round size="mini">查询</el-button>
      </div>
    </div>

    <div class="table-wrapper">
      <div class="leftContent">
        <span>{{ pageTitle }}</span>
      </div>
      <el-table
        size="mini"
        :data="state.tableData"
        height="calc(100% - 35px - 55px)"
        style="width: 100%"
        stripe
      >
          <el-table-column
            v-for="item in state.tableHeader"
            :label="item.title"
            :prop="item.code"
            :key="item.code"
            :width="item.width || ''"
            show-overflow-tooltip
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <p v-if="item.code === 'ts'">{{formatTime(scope.row[item.code])}}</p>
              <p v-else>{{scope.row[item.code]}}</p>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="200"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <el-button style="color: #05bb4c" type="text" @click="export2Excel(scope.row)">查看报告</el-button>
              <!--  @click="confirmItem([scope.row])" -->
            </template>
          </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          :current-page="query.page"
          :page-size="query.limit"
          :page-sizes="[21, 100, 500, 1000]"
          :total="query.pageTotal"
          @size-change="
            (value) => {
              query.page = 1;
              query.limit = value;
              getAlarmHistoryt();
            }
          "
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <HealthReport ref="healthReportRef"></HealthReport>
  </div>
</template>

<script setup>
import { getStation } from "@/api/performance";
import {
  watch,
  reactive,
  nextTick,
  computed,
  onMounted,
  ref,
  onActivated,
  onUpdated,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import HealthReport from "@com/other/healthReport/index.vue";
import {
  alarm_history,
  new_alarm_history,
  fetchWindturbineList,
  fetchModel,
  fetchRelatePartAndAlarmType,
  getWpList,
  confirmAlart,
} from "@/api/zhbj/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
import { useStore } from "vuex";
const pageTitle = "健康评价报告";
const store = useStore();
const route = useRoute();

onMounted(() => {
  state.dateTime = [
    dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"),
    dayjs().format("YYYY-MM-DD HH:mm:ss"),
  ];
  state.deviceId = route.query.deviceId || "";
  state.alarmId = route.query.alarmId || "";
  state.modelId = route.query.modelId || "";
  getStationList();
  getequipmentmodel_list();
  getfetchRelatePart();

  getAlarmHistoryt()
});

const healthReportRef = ref()

// 机型
const getequipmentmodel_list = async () => {
  const { data } = await fetchModel();
  state.modelListAll = data;
};
//所属部件
const getfetchRelatePart = async () => {
  const { data } = await fetchRelatePartAndAlarmType();
  state.fetchListAll = data;
};

const confirmItem = (alarmItem) => {
  ElMessageBox("您确定要执行此操作吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      confirmAlart(alarmItem)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("确认成功");
            store.commit("removeWarning", alarmItem);
            getAlarmHistoryt();
          }
        })
        .catch(() => {
          ElMessage.error("确认失败，请重试");
        });
    })
    .catch(() => {});
};

const getColumnStyle = (columnItem) => {
  let style = "color:";
  if (columnItem.endts) {
    style += "#05bb4c";
  } else {
    style += "var(--el-color-danger)";
  }
  return style;
};

const state = reactive({
  typeList: [
    // {
    //   label: "升压站",
    //   value: "booststation",
    // },
    // {
    //   label: "自定义",
    //   value: "custom",
    // },
    {
      label: "风机",
      value: "windturbine",
    },
    // {
    //   label: "光伏",
    //   value: "inverter",
    // },
  ],
  c: "windturbine",
  stationId: "",
  alarmId: "",
  typeVal: "windturbine",
  windturbineList: [],
  deviceId: "",
  modelListAll: {},
  fetchListAll: {},
  modelId: "", //型号
  components: "", //部件
  description: "", //描述
  dateTime: [],
  startDate: null,
  endDate: null,
  tableData: [],
  isshowwindturbineName: true,
  tableHeader: [
    { title: "场站", code: "stationname" },
    { title: "时间", code: "ts" },
  ]
});
// 场站列表/升压站列表
const stationList = ref([]);

const getStationList = async () => {
  //   const { data } = await getWpList(state.typeVal);
  //   stationList.value = data;
  const { data } = await getStation({
    companyids: 0,
    type: state.typeVal == "windturbine" ? -1 : -2,
  });

  stationList.value = data.data;
  //   if (state.deviceId) {
  //     let station = data.find((i) => {
  //       let st = i.id.split("_")[2];
  //       let dt = state.deviceId.split("_")[2];
  //       if (st == dt) {
  //         return i;
  //       }
  //     });
  //     state.stationId = station?.id;
  //   } else {
  //     state.stationId =
  //       state.typeVal == "windturbine" ? "SXJ_KGDL_DJY_FDC_STA" : data[0]?.id;
  //   }
  if (stationList.value.length) {
    await getWindturbineList();
    await getAlarmHistoryt();
  }
};

// watch(
//   () => stationList,
//   (val, old) => {
//     val?.value?.length &&
//       nextTick(async () => {
//         await getWindturbineList();
//         await getAlarmHistoryt();
//       });
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// );
watch(
  () => route,
  (val, old) => {
    state.deviceId = route.query.deviceId || "";
    state.alarmId = route.query.alarmId || "";
    state.modelId = route.query.modelId || "";
    // nextTick(async () => {
    //   if (route.params.deviceId && route.params.alarmId) {
    //     await getAlarmHistoryt();
    //   }
    // });
  },
  {
    deep: true,
    immediate: true,
  }
);
//型号列表
const modelList = computed(() => {
  if (state.stationId == "") {
    return [];
  } else {
    state.modelId = route.query.deviceId ? route.query.modelId : "";
    return state.modelListAll[state.stationId];
  }
});
//部件列表
const componentList = computed(() => {
  if (state.stationId == "") {
    return [];
  } else {
    if (state.stationId.includes("FDC")) {
      return state.fetchListAll?.fjbj;
    } else {
      return state.fetchListAll?.gfbj;
    }
  }
});
//get 风机
const getWindturbineList = async () => {
  state.deviceId = "";
  //   const { data } = await fetchWindturbineList(state.stationId);
  //   state.windturbineList = data;
  state.windturbineList = [
    {
      id: "SXJ_KGDL_XWT_F_WT_0001_EQ",
      nemCode: "#1",
      windpowerstationId: "SXJ_KGDL_XWT_FDC_STA",
      longitude: 112.415335,
      latitude: 40.281307,
      modelId: "SEC-W02B-1250kW",
      status: "NULL",
      projectId: "SXJ_KGDL_XWTF01_EG",
      lineId: "SXJ_KGDL_XWTF01_LN",
      firstIntegratedTime: "2008-07-27T16:00:00.000+0000",
      photo: "NULL",
      name: "01号风机",
      aname: "#1",
      isStandard: 1,
      regionId: "NX_FGS",
      companyId: "SXJ_KGDL_FLFD_ZGS",
      isable: 1,
      equipmentCategory: -1,
      parentId: "NULL",
      squareId: "NULL",
      spare1: "WT",
      spare2: "1",
      spare3: "NULL",
      spare4: "NULL",
      orderNum: 271,
      substationId: "SXJ_KGDL_XWTF01_SBS",
    },
  ];
};
const query = reactive({
  page: 1,
  limit: 21,
  pageTotal: null,
});
const tableLoading = ref(false);
// 获取历史记录表
const getAlarmHistoryt = async () => {
  //   if (route.params.deviceId && route.params.alarmId) {
  //     state.stationId = "";
  //   }
  //   tableLoading.value = true;
  //   let params = {
  //     pageNum: query.page,
  //     pageSize: query.limit,
  //     alarmId: state.alarmId,
  //     alarmType: "custom",
  //     deviceType: state.typeVal,
  //     stationid: state.stationId,
  //     deviceid:
  //       state.deviceId || (state.typeVal == "booststation" ? "" : state.deviceId),
  //     modelId: state.typeVal == "booststation" ? "" : state.modelId,
  //     components: state.components,
  //     description: state.description,
  //     begin: state.dateTime[0],
  //     end: state.dateTime[1],
  //   };
  //   const { data } = await alarm_history(params);
  //   tableLoading.value = false;
  //   query.pageTotal = data?.total;
  //   data?.ls?.forEach((ele) => {
  //     ele.isCloseName = ele.endts ? "已解除" : "未解除";
  //     ele.deviceTypeName = tableFilter(ele.deviceType);
  //     ele.endtsName = ele.endts > 0 ? formatTime(ele.endts) : "--";
  //   });
  //   state.tableData = data?.ls;
  state.tableData = new Array(5).fill({
    tbName: null,
    alarmId: "SQ_0125",
    alarmType: "windturbine",
    characteristic: "预警",
    components: "BPQ",
    confirmed: false,
    description: "变频器故障27",
    deviceId: "SXJ_KGDL_XWT_F_WT_0014_EQ",
    devicename: "14号风机",
    deviceType: "windturbine",
    enabled: true,
    lineid: "SXJ_KGDL_XWTF01_LN",
    linename: "一号风机线",
    modelId: "SEC-W02B-1250kW",
    projectid: "SXJ_KGDL_XWTF01_EG",
    projectname: "一期项目",
    rank: 3,
    resettable: false,
    stationid: "SXJ_KGDL_XWT_FDC_STA",
    stationname: "13风电场",
    subcomponents: "NULL",
    suffix: null,
    tagid: "FD-YYXWT-ShangQi.140623F1412MDL01BF399DB0122SP01RAW00",
    triggertype: 1463,
    uniformcode: "BJ0001",
    superTableName: null,
    ts: 1718160795000,
    val: 1,
    oval: null,
    endts: 0,
    timelong: 0,
    name: null,
    nemCode: "状态码1463",
    faultCause: "13.7s>信号<=14.2s",
    resolvent: "输入端142功率上升延迟300s",
    wpName: "13风电场",
    code: "#14",
    wpId: null,
    faultType: null,
    id: "sxj_kgdl_xwt_f_wt_0014_eq_sq_0125",
  });
};
//报警类型变化
const typechange = () => {
  state.alarmId = "";
  state.deviceId = "";
  state.isshowwindturbineName = state.typeVal == "booststation" ? false : true;
};

// 查看报告
const export2Excel = () =>{
    healthReportRef.value.dialogVisible = true
}
// 分页导航
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: "高级",
  booststation: "升压站",
  custom: "自定义",
  windturbine: "风机",
  inverter: "光伏",
};
const messageTypeObj = {
  1: "触发",
  3: "解除",
};
const tableFilter = (val) => {
  return obj[val];
};
const messageTypeFilter = (val) => {
  return messageTypeObj[val];
};
</script>

<style scoped lang="less">
p {
  padding: 0;
  margin: 0;
}
.custom-warning {
  height: 100%;
  width: 100%;
  padding: 0 20px;
  padding-bottom: 10px;
  .form-wrapper ::v-deep {
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    position: relative;
    .search-wrapper {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #b3b3b3;
      margin-bottom: 10px;
      .search-item {
        display: flex;
        margin-right: 10px;
        max-width: 450px;
        align-items: center;
        .label {
          margin-right: 10px;
          text-align: right;
          white-space: nowrap;
          // width: 60px;
        }
        .search-content {
          flex: 1;
        }
      }
    }

    .btns {
      display: flex;
      justify-content: flex-end;
      margin-right: 10px;
      position: absolute;
      right: 0;
      top: 53px;
    }

    .buttons {
      background-color: rgba(5, 187, 76, 0.2);
      border: 1px solid #3b6c53;
      color: #b3b3b3;
      font-size: 14px;

      &:hover {
        background-color: rgba(5, 187, 76, 0.5);
        color: #ffffff;
      }
    }
  }
  .table-wrapper {
    height: calc(100% - 43px);
    width: 100%;
    .leftContent {
      width: 242px;
      height: 41px;
      display: flex;
      align-items: center;
      background: url("~@/assets/imgs/title_left_bg1.png") no-repeat;

      span {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #05bb4c;
        margin-left: 25px;
      }
    }
    .pagination-wrapper :deep {
      text-align: right;
      margin-top: 10px;
    }
  }
}
</style>
