<template>
  <div class="history-config">
    <div class="form-wrapper">
      <div class="btns" 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 class="search-wrapper">
        <el-select
          class="search-item"
          v-model="query.alarmType"
          size="mini"
          popper-class="select"
          @change="categorychanged"
        >
          <el-option key="2" label="升压站" value="booststation"></el-option>
          <el-option key="1" label="风机" value="windturbine"></el-option>
          <el-option key="3" label="光伏" value="inverter"></el-option>
        </el-select>
        <el-select
          class="search-item"
          v-model="query.wpId"
          clearable
          size="mini"
          :placeholder="
            query.alarmType == 'booststation' ? '全部升压站' : '全部场站'
          "
          popper-class="select"
          @change="changeStation"
        >
          <el-option
            v-for="item in stationList"
            :key="item.id"
            :value="item.id"
            :label="item.aname"
          ></el-option>
        </el-select>
        <el-select
          class="search-item"
          v-if="query.alarmType != 'booststation'"
          v-model="query.modelId"
          clearable
          size="mini"
          placeholder="全部机型"
          popper-class="select"
        >
          <el-option
            v-for="item in modelList"
            :key="item.id"
            :value="item.id"
            :label="item.aname"
          ></el-option>
        </el-select>
        <el-input
          class="search-item"
          placeholder="请输入名称"
          v-model="query.name"
          size="mini"
          clearable
        ></el-input>
        <el-button class="buttons" round size="mini" @click="getData"
          >搜 索</el-button
        >
      </div>
    </div>
    <div class="table-wrapper">
      <div class="leftContent">
        <span>{{ pageTitle }}</span>
      </div>
      <el-table
        :data="state.tableData"
        stripe
        height="calc(100% - 52px - 42px)"
      >
        <el-table-column
          v-for="item in query.alarmType == 'windturbine' ||
          query.alarmType == 'inverter'
            ? state.tableHeader
            : state.tableHeader1"
          :key="item.code"
          :label="item.title"
          align="center"
          :prop="item.code"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-if="item.code == 'rank'">
              {{ rankConvert(scope.row.rank) }}
            </span>
            <span v-else-if="item.code == 'alarmType'">
              {{ alarmTypeConvert("alarmType", scope.row.alarmType) }}
            </span>
            <span v-else-if="item.code == 'deviceType'">
              {{ alarmTypeConvert("deviceType", scope.row.deviceType) }}
            </span>
            <span v-else-if="item.code == 'enable'">
              {{ enabledConvert(scope.row.enable) }}
            </span>
            <span v-else>
              {{ scope.row[item.code] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button
              type="text"
              style="color: #05bb4c"
              size="mini"
              @click="handleEditClick(scope.row)"
            >
              编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          :current-page="query.pageNum"
          :page-size="query.pageSize"
          :page-sizes="[22, 50, 100, 200, 500]"
          :total="total"
          @size-change="
            (value) => {
              query.pageSize = value;
              query.pageNum = 1;
              getData();
            }
          "
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <windturbinecomponents
      :title="state.title"
      @close="dialogclose"
      :isVisible="state.visible"
      :form="state.form"
    />
  </div>
</template>
<script setup>
import {
  windturbinebj_fetchTableData,
  getStationinfo,
  fetchRelatePartAndAlarmType,
  fetchModel,
  getWpList,
} from "@/api/zhbj/index.js";
import { outExportExcel } from "@/tools/excel/exportExcel.js"; //引入文件
import {
  ref,
  onMounted,
  provide,
  computed,
  reactive,
  watch,
  nextTick,
} from "vue";
import { useStore } from "vuex";
import { ElMessageBox, ElMessage } from "element-plus";
import windturbinecomponents from "@/views/IntegratedAlarm/alarmConfig/components/windturbine_components.vue";
const pageTitle = "报警配置";
const store = useStore();
const token = { token: store.state.user.authToken };
onMounted(() => {
  getWpArray();
  getequipmentmodel_list();
  getData();
});
const query = reactive({
  pageNum: 1,
  pageSize: 22,
  wpId: "",
  modelId: "",
  name: "",
  alarmType: "windturbine",
});
const state = reactive({
  title: "",
  tableData: [],
  modelList: [],
  modelListAll: {}, //型号所有列表
  visible: false,
  form: {},
  tableHeader: [
    { title: "编码", code: "id" },
    { title: "场站", code: "stationName" },
    // { title: "设备", code: "deviceId", },
    { title: "机型", code: "modelId" },
    { title: "报警描述", code: "description" },
    { title: "设备部件", code: "componentsName" },
    { title: "特性", code: "characteristic" },
    { title: "设备类型", code: "deviceType" },
    { title: "报警类型", code: "alarmType" },
    // { title: "级别", code: "rankName" },
    { title: "是否启用", code: "enable" },
    { title: "是否可复位", code: "resetTableName" },
  ],
  tableHeader1: [
    { title: "编码", code: "id" },
    { title: "升压站", code: "stationName" },
    // { title: "规则名称", code: "name" },
    // { title: "表达式", code: "expression" },

    { title: "类型", code: "alarmType" },
    // { title: "级别", code: "rank" },
    { title: "是否启用", code: "enable" },
    { title: "描述", code: "description" },
  ],
});
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await fetchModel();
  state.modelListAll = data;
};
// 场站列表/升压站列表
const stationList = ref([]);
const categorychanged = async (value) => {
  query.alarmType = value;
  query.wpId = "";
  query.modelId = "";
  getWpArray();
  getData();
};
const getWpArray = async () => {
  const { data } = await getWpList(query.alarmType);
  stationList.value = data;
};
//型号列表
const modelList = computed(() => {
  if (query.wpId == "") {
    return [];
  } else {
    return state.modelListAll[query.wpId];
  }
});
const isStation = computed(() => store.getters.isStation);

let total = ref(0);
const hisTable = ref();
const getData = async () => {
  const { data: res } = await windturbinebj_fetchTableData(query);
  res.records.forEach((ele) => {
    ele.rankName = getRankName(ele.rank);
    ele.resetTableName = ele.resetTable ? "是" : "否";
  });
  state.tableData = res.records;
  console.log(hisTable.value);
  total.value = res.total;
};

const getRankName = (rank) => {
  if (rank === 1) {
    return "低级";
  } else if (rank === 2) {
    return "低中级";
  } else if (rank === 3) {
    return "中级";
  } else if (rank === 4) {
    return "中高级";
  } else if (rank === 5) {
    return "高极";
  }
};
//changeStation
const changeStation = async () => {
  query.modelId = "";
  getData();
};
const dialogclose = () => {
  state.visible = false;
  getData();
};

const handleInsert = () => {
  state.visible = true;
  state.title = "新增";
};
const handleEditClick = (row) => {
  state.title = "编辑";
  let obj = Object.assign({}, row);
  obj && (obj.manufacturerCode = "");
  state.form = obj;
  state.visible = true;
};

// 分页导航
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, wpId, modelId } = query;
  const res = await windturbinebj_fetchTableData({
    pageNum: 1,
    pageSize: 999999,
    name,
    wpId,
    modelId,
  });

  ElMessage.success(`导出成功!`);
  outExportExcel(
    tableHeader,
    tableKey,
    res.data.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 rankConvert = (val) => {
  if (val == 1) {
    return "低级";
  } else if (val == 2) {
    return "低中级";
  } else if (val == 3) {
    return "中级";
  } else if (val == 4) {
    return "中高级";
  } else if (val == 5) {
    return "高级";
  }
};
// 类型
const alarmTypeConvert = (type, val) => {
  if (type === "alarmType") {
    if (val === "windturbine") {
      return "风机";
    } else if (val === "booststation") {
      return "升压站";
    } else if (val === "inverter") {
      return "光伏";
    } else if (val === "custom") {
      return "自定义";
    }
  } else {
    if (val === "windturbine") {
      return "风机";
    } else if (val === "booststation") {
      return "升压站";
    } else if (val === "inverter") {
      return "光伏";
    }
  }
};
// 状态
const enabledConvert = (val) => {
  if (val === false) {
    return "停用";
  } else if (val === true) {
    return "启用";
  }
};
// 报警分类
const warningClassIfyIdConvert = (val) => {
  switch (val) {
    case "bj":
      return "变桨";

    case "bpq":
      return "变频器";

    case "clx":
      return "齿轮箱";

    case "fdj":
      return "发电机";

    case "hh":
      return "滑环";

    case "jcjr":
      return "机舱加热";

    case "lq":
      return "冷却";

    case "ph":
      return "偏航";

    case "rh":
      return "润滑";

    case "yy":
      return "液压";

    case "zz":
      return "主轴";

    case "other":
      return "其它";

    case "kz":
      return "控制";

    case "yl":
      return "叶轮";

    case "jc":
      return "机舱";

    case "xb":
      return "箱变";

    case "dw":
      return "电网";

    case "td":
      return "塔底";

    case "fsy":
      return "风速仪";
  }
};
// 是否可以复位
const isresetConvert = (val) => {
  switch (val) {
    case 0:
      return "是";
    case 1:
      return "否";
  }
};

// 统一编码
const ednaValueConvert = (val) => {
  if (val === 0) {
    return "";
  } else if (val < 100 && val > 0) {
    return "DI0" + val;
  } else if (val >= 100) {
    return "DI" + val;
  }
};
// 关联部件
const relatePartConvert = (val) => {
  switch (val) {
    case "YP":
      return "叶片";
    case "LG":
      return "轮毂";
    case "TZ":
      return "塔架";
    case "JC":
      return "机舱";
    case "KZXT":
      return "控制系统";
    case "BJXT":
      return "变桨系统";
    case "PHXT":
      return "偏航系统";
    case "CLX":
      return "齿轮箱";
    case "FDJ":
      return "发电机";
    case "BPQ":
      return "变频器";
    case "YYXT":
      return "液压系统";
    case "FZXT":
      return "辅助系统";
    case "CFXT":
      return "测风系统";
    case "DWXT":
      return "电网系统";
    case "TDG":
      return "塔底柜";
    case "CDL":
      return "传动链";
    case "QT":
      return "其他";
    default:
  }
};
</script>
<style scoped lang="less">
.history-config {
  height: 100%;
  width: 100%;
  padding: 0 20px;
  padding-bottom: 10px;
  .form-wrapper {
    display: flex;
    padding-top: 10px;
    justify-content: space-between;
    .search-wrapper::v-deep {
      display: flex;
      align-items: center;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #b3b3b3;
      margin-bottom: 10px;
      .search-item {
        margin-right: 10px;
        max-width: 190px;
      }
    }

    .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;
    }
  }
  .el-table::v-deep {
    .el-table__body-wrapper {
      height: calc(100% - 45px) !important;
    }
  }
  .pagination-wrapper ::v-deep {
    text-align: right;
    margin-top: 10px;
  }
}

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