<template>
  <div style="width: 100%; height: 100%">
    <el-row type="flex" justify="space-between">
      <div class="handle-box" style="margin-bottom: 10px">
        <el-button size="mini" round class="buttons" @click="handleInsert">
          新增记录
        </el-button>
        <el-button size="mini" round class="buttons" @click="export2Excel">
          批量导出</el-button
        >
        <el-button size="mini" round class="buttons" @click="outExe">
          模板下载</el-button
        >
        <el-upload
          style="display: inline; margin-left: 10px"
          action="/sharding/warning2/import"
          :headers="token"
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :on-error="handleError"
        >
          <el-button
            size="mini"
            round
            class="buttons"
            @click="exportShow = true"
          >
            批量导入</el-button
          >
        </el-upload>
      </div>
      <div style="display: flex; flex-direction: row; margin-bottom: 10px">
        <el-select
          v-if="!isStation"
          v-model="query.stationId"
          clearable
          size="mini"
          style="width: 150px"
          placeholder="全部场站"
          popper-class="select"
          @change="changeStation()"
        >
          <el-option
            v-for="item in stationList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-select
          v-model="query.modelId"
          clearable
          size="mini"
          style="width: 150px"
          placeholder="全部机型"
          popper-class="select"
        >
          <el-option
            v-for="item in state.modelList"
            :key="item"
            :value="item"
            :label="item"
          ></el-option>
        </el-select>

        <el-input
          placeholder="请输入名称"
          v-model="query.name"
          style="width: 150px; margin-right: 10px"
          size="mini"
          clearable
        ></el-input>
        <el-button
          icon="el-icon-search"
          size="mini"
          round
          class="buttons"
          @click="getData"
          >搜索</el-button
        >
      </div>
    </el-row>
    <div class="wind-table">
      <el-table
        :data="state.tableData"
        size="mini"
        style="width: 100%"
        stripe
        height="calc(100% - 43px)"
      >
        <el-table-column label="序列号" align="center" prop="id" />
        <el-table-column label="统一编码" align="center" prop="uniformCode">
          <template #default="scope">{{
            // ednaValueConvert(scope.row.ednaValue)
            scope.row.uniformCode
          }}</template>
        </el-table-column>
        <el-table-column
          label="描述"
          align="left"
          prop="description"
          width="180"
        />
        <el-table-column
          label="停机类型"
          align="center"
          prop="characteristic"
        />
        <el-table-column label="风机型号" align="center" prop="modelId" />
        <el-table-column label="报警类型" align="center" prop="alarmTypeName" />
        <el-table-column label="故障编码" align="center" prop="nemCode" />
        <el-table-column label="报警级别" align="center">
          <template #default="scope">{{
            levelIdConvert(scope.row.rank)
          }}</template>
        </el-table-column>
        <el-table-column label="报警分类" align="center" min-width="50">
          <template #default="scope">{{
            warningClassIfyIdConvert(scope.row.deviceType)
          }}</template>
        </el-table-column>
        <el-table-column label="是否可以复位" align="center" min-width="50">
          <template #default="scope">{{
            scope.row.resetTable ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" min-width="50">
          <template #default="scope">{{
            scope.row.enabled == 1 ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column
          label="关联部件"
          align="center"
          min-width="50"
          prop="componentsName"
        />

        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button
              type="text"
              style="color: #05bb4c"
              icon="el-icon-lx-edit"
              @click="handleEditClick(scope.row)"
            >
              编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          :page-sizes="[19, 50, 100, 200, 500]"
          @size-change="
            (value) => {
              query.pageSize = value;
              query.pageNum = 1;
              getData();
            }
          "
          :current-page="query.pageNum"
          :page-size="query.pageSize"
          :total="total"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <windturbinecomponents
      @close="dialogclose"
      :isVisible="state.visible"
      :form="state.form"
    />
  </div>
</template>
<script setup>
import {
  windturbinebj_fetchTableData,
  getWtModel,
  getWpList,
} from "@/api/zhbj/index.js";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
import { ref, onMounted, provide, computed, reactive, watch } from "vue";
import { useStore } from "vuex";
import { ElMessageBox, ElMessage } from "element-plus";
import windturbinecomponents from "./windturbine_components.vue";
const token = { token: sessionStorage.getItem("token") };
const store = useStore();
const stationList = ref([]);

const getStationList = async () => {
  const { data } = await getWpList("windturbine");
  stationList.value = data || [];
};
const isStation = computed(() => stationList.value.length);
const state = reactive({
  tableData: [],
  modelList: [],
  visible: false,
  form: {},
});
const query = reactive({
  pageNum: 1,
  pageSize: 19,
  stationId: "",
  modelId: "",
  name: "",
});
let total = ref(0);
onMounted(() => {
  getStationList();
  getData();
  getequipmentmodel_list();
});
const dialogclose = () => {
  state.visible = false;
  getData();
};
const getData = async () => {
  const { data } = await windturbinebj_fetchTableData(query);
  data.records.forEach((ele) => {
    ele.alarmTypeName = warningClassIfyIdConvert(ele.alarmType);
  });
  state.tableData = data.records;
  total.value = data.total;
};
const handleInsert = () => {
  state.visible = true;
};
const handleEditClick = (row) => {
  console.warn(row);
  let obj = Object.assign({}, row);
  state.form = obj;
  state.visible = true;
};
//changeStation
const changeStation = async () => {
  query.modelId = "";
  await getequipmentmodel_list();
};
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await getWtModel(query.stationId);
  state.modelList = data || [];
};
// 分页导航
const handlePageChange = (val) => {
  query.pagenum = val;
  getData();
};

const tableHeader = [
  "id",
  "报警级别（ZC_BJ：运转正常；YJ_BJ：运转状态超出标准范围；GZ_BJ：非正常停止运转；WH_BJ：停机维护；XD_BJ：限电/计划停机）",
  "制造商（HFYG_CS：合肥阳光电源有限公司；AMS_CS：艾默生；NRJD_CS：国电南瑞吉电新能源；MGSK_CS：美国赛康；LHDL_CS：联合动力；SYHC_CS：沈阳华创）",
  "名称",
  "上一级节点",
  "是否有子节点",
  "序列号",
  "类别 ：正常停机，正常启动，快速停机，紧急停机",
  "风机型号",
  "全部默认为1",
  "统一编码",
  "是否展示（0：是；1：否）",
  "报警分类（bj：变桨；bpq：变频器；clx：齿轮箱；fdj：发电机；hh：滑环；jcjr：机舱加热；lq：冷却；ph：偏航；rh：润滑；yy：液压；zz：主轴；other：其它；kz：控制；yl：叶轮；jc：机舱；xb：箱变；dw：电网；td：塔底；fsy：风速仪）",
  "消缺规定时间",
  "是否可以复位（0：是；1：否）",
  "报警类型编号",
  "故障编码",
  "关联部件",
];

const tableKey = [
  "id",
  "levelId",
  "manufacturerCode",
  "chineseText",
  "parentId",
  "isleaf",
  "sequenceNumber",
  "characteristic",
  "modelId",
  "codeName",
  "ednaValue",
  "display",
  "warningClassIfyId",
  "standardTime",
  "isreset",
  "warningTypeId",
  "faultCode",
  "relatedParts",
];
// 批量导出
const export2Excel = async () => {
  let { name, stationId, modelId } = query;
  const res = await windturbinebj_fetchTableData({
    pageNum: 1,
    pageSize: 999999,
    name,
    stationId,
    modelId,
  });

  ElMessage.success(`导出成功!`);
  outExportExcel(tableHeader, tableKey, res.records, "风机报警配置导出excel");
};
// 模板下载
const outExe = () => {
  const data = [];
  ElMessage.success(`导出成功!`);
  outExportExcel(tableHeader, tableKey, data, "风机报警模板");
};
// 批量导入
const handleSuccess = (response, file, fileList) => {
  ElMessage.success("导入成功!");
  getData();
};
const handleProgress = (response, file, fileList) => {};
const handleError = (response, file, fileList) => {
  ElMessage.success("导入失败!");
};
// 报警级别
const levelIdConvert = (val) => {
  switch (val) {
    case 1:
      return "低级";
    case 2:
      return "低中级";
    case 3:
      return "中级";
    case 4:
      return "中高级";
    case 5:
      return "限电/高级";
    default:
      return "";
  }
};
// 报警分类
const warningClassIfyIdConvert = (val) => {
  switch (val) {
    case "station":
      return "场站";
    case "windturbine":
      return "风机";
    case "booststation":
      return "升压站";
    default:
      return "";
  }
};

// 统一编码
const ednaValueConvert = (val) => {
  if (val === 0) {
    return "";
  } else if (val < 100 && val > 0) {
    return "DI0" + val;
  } else if (val >= 100) {
    return "DI" + val;
  }
};
</script>
<style scoped lang="less">
.wind-table {
  height: calc(100% - 40px);
}
.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;
  }
}
.el-select ::v-deep {
  margin-right: 10px;
}

.el-button + .el-button {
  margin-left: 10px;
}
.pagination {
  padding-top: 10px;
}
</style>
