<template>
  <div class="custom-config">
    <div class="form-wrapper">
      <div class="btns" style="margin-bottom: 10px">
        <el-button class="buttons" size="mini" round @click="handleInsert">
          新增记录
        </el-button>
        <el-button class="buttons" size="mini" round @click="export2Excel">
          批量导出</el-button
        >
        <el-button class="buttons" size="mini" round @click="outExe">
          模板下载</el-button
        >
        <el-upload
          style="display: inline; margin-left: 10px"
          :action="url + 'alertrule/import'"
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :on-error="handleError"
        >
          <el-button
            class="buttons"
            size="mini"
            round
            @click="exportShow = true"
          >
            批量导入</el-button
          >
        </el-upload>
      </div>
      <div class="search-wrapper">
        <el-select
          v-model="query.category"
          size="mini"
          class="search-item"
          popper-class="select"
          @change="categorychanged"
        >
          <el-option key="1" label="风机报警" value="windturbine"></el-option>
          <!-- <el-option
            key="2"
            label="升压站报警"
            value="booststation"
          ></el-option> -->
          <el-option key="3" label="光伏报警" value="inverter"></el-option>
        </el-select>
        <el-select
          v-model="query.wpId"
          clearable
          size="mini"
          class="search-item"
          :placeholder="'全部场站'"
          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
          v-model="query.relatedparts"
          clearable
          size="mini"
          class="search-item"
          placeholder="所属部件"
        >
          <el-option
            v-for="item in fetchList"
            :key="item.id"
            :label="item.name"
            :value="item.nemCode"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="query.enabled"
          clearable
          size="mini"
          class="search-item"
          placeholder="是否可用"
        >
          <el-option
            v-for="item in state.isEnabled"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="query.modelId"
          clearable
          size="mini"
          class="search-item"
          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-select
          v-model="query.rank"
          clearable
          size="mini"
          class="search-item"
          placeholder="全部级别"
          popper-class="select"
        >
          <el-option
            v-for="item in state.rankList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select> -->
        <el-input
          placeholder="请输入名称"
          v-model="query.name"
          size="mini"
          class="search-item"
          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% - 42px - 45px)"
      >
        <el-table-column
          v-for="item in state.tableHeader"
          :key="item.code"
          :label="item.title"
          :align="
            item.code == 'description' ||
            item.code == 'expression' ||
            item.code == 'name' ||
            item.code == 'modelId' ||
            item.code == 'relatedPartsName'
              ? 'left'
              : 'center'
          "
          :prop="item.code"
          :minWidth="item.width ? item.width : 60"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-if="item.code == 'rank'">
              {{ rankConvert(scope.row.rank) }}
            </span>
            <span v-else-if="item.code == 'category'">
              {{ categoryConvert(scope.row.category) }}
            </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
          :current-page="query.pageNum"
          :page-size="query.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next"
          :page-sizes="[22, 50, 100, 200, 500]"
          @size-change="
            (value) => {
              query.pageSize = value;
              query.pageNum = 1;
              getData();
            }
          "
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <customcomponents
      @close="dialogclose"
      :isVisible="state.visible"
      :dialogOptions="state.form"
      :rankList="state.rankList"
      :modelListAll="state.modelListAll"
      :fetchListAll="state.fetchListAll"
    />
  </div>
</template>
<script setup>
import {
  custombj_fetchTableData,
  getStationinfo,
  fetchRelatePartAndAlarmType,
  fetchModel,
  fetchBooststation,
  custombj_importTemplate,
  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 { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import customcomponents from "@/views/IntegratedAlarm/alarmConfig/components/custom_components.vue";
const pageTitle = "预警配置";
const store = useStore();
const token = { token: store.state.user.authToken };
const url = process.env.VUE_APP_ALARM;
const router = useRouter();
const query = reactive({
  pageNum: 1,
  pageSize: 22,
  name: "",
  wpId: "",
  rank: "",
  modelId: "",
  category: "windturbine",
  enabled: "",
  relatedparts: "",
});
const state = reactive({
  tableData: [],
  fetchListAll: [], //部件及预警类型
  modelListAll: {}, //型号所有列表
  isEnabled: [
    {
      id: false,
      name: "否",
    },
    {
      id: true,
      name: "是",
    },
  ],
  rankList: [
    {
      id: 1,
      name: "低",
    },
    {
      id: 2,
      name: "中低",
    },
    {
      id: 3,
      name: "中",
    },
    {
      id: 4,
      name: "中高",
    },
    {
      id: 5,
      name: "高",
    },
  ],
  visible: false,
  form: {},
  tableHeader: [
    { title: "编码", code: "id" },
    { title: "场站", code: "stationName", width: "100" },
    { title: "机型", code: "modelId" },
    { title: "规则名称", code: "name", width: "150" },
    { title: "表达式", code: "expression", width: "150" },
    { title: "描述", code: "description", width: "150" },
    { title: "所属部件", code: "relatedPartsName" },
    // { title: "级别", code: "rank" },
    { title: "类型", code: "category" },
    { title: "是否启用", code: "enable" },
  ],
  tableHeader1: [
    { title: "编码", code: "id" },
    { title: "升压站", code: "stationName" },
    { title: "规则名称", code: "name" },
    { title: "表达式", code: "expression" },
    { title: "描述", code: "description" },
    // { title: "级别", code: "rank" },
    { title: "类型", code: "category" },
    { title: "是否启用", code: "enable" },
  ],
});
//型号列表
const modelList = computed(() => {
  if (query.wpId == "") {
    return [];
  } else {
    return state.modelListAll[query.wpId];
  }
});
//部件列表
const fetchList = computed(() => {
  if (query.wpId == "") {
    return [];
  } else {
    if (query.wpId.includes("FDC")) {
      return state.fetchListAll?.fjbj;
    } else {
      return state.fetchListAll?.gfbj;
    }
  }
});

// 场站列表/升压站列表
const stationList = ref([]);
let total = ref(0);
onMounted(() => {
  getWpArray();
  getfetchRelatePart();
  getequipmentmodel_list();
  getData();
});

const dialogclose = () => {
  state.visible = false;
  state.form = {};
  getData();
};
const getWpArray = async () => {
  const { data } = await getWpList(query.category);
  stationList.value = data;
};
const getData = async () => {
  const { data } = await custombj_fetchTableData(query);
  state.tableData = data.records;
  total.value = data.total;
};
//所属部件
const getfetchRelatePart = async () => {
  const { data } = await fetchRelatePartAndAlarmType();
  state.fetchListAll = data;
  //   if (router && router.currentRoute.value.query.name) {
  //     let queryName = router.currentRoute.value.query.name;
  //     query.relatedparts = queryName;
  //   }
  //   getData();
};
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await fetchModel();
  state.modelListAll = data;
};
const handleEditClick = (row) => {
  let obj = Object.assign({}, row);
  state.form = obj;
  state.visible = true;
};
const handleInsert = () => {
  state.form = {
    category: "windturbine",
    enable: true,
    stationId: "",
    expression: "",
  };
  state.visible = true;
};

//changeStation
const changeStation = async () => {
  query.modelId = "";
  query.relatedparts = "";
};
//categorychanged
const categorychanged = async () => {
  getWpArray();
  this.clean();
  getData();
};

// 分页导航
const handlePageChange = (val) => {
  query.pageNum = val;
  getData();
};

// 批量导出
const export2Excel = async () => {
  let tableHeader = [];
  let tableKey = [];
  const { data } = await custombj_fetchTableData({
    pageNum: 1,
    pageSize: total.value,
    ...query,
  });
  ElMessage.success(`导出成功!`);
  if (query.category == "windturbine") {
    tableHeader = state.tableHeader.map((item) => item.title);
    tableKey = state.tableHeader.map((item) => item.code);
  } else if (query.category == "booststation") {
    tableHeader = state.tableHeader1.map((item) => item.title);
    tableKey = state.tableHeader1.map((item) => item.code);
  }
  outExportExcel(
    tableHeader,
    tableKey,
    data.records.map((item) => {
      return {
        ...item,
        category: categoryConvert(item.category),
        enable: enabledConvert(item.enable),
      };
    }),
    "自定义预警配置导出excel"
  );
};
// 模板下载
const outExe = () => {
  custombj_importTemplate().then((response) => {
    const link = document.createElement("a");
    const blob = new Blob([response], {
      type: "application/vnd.ms-excel",
    });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.download = "自定义报警模板.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};
// 批量导入
const handleSuccess = (response) => {
  if (response.code == "200") {
    ElMessage.success("导入成功!");
    getData();
  } else {
    ElMessage.error(response.msg);
  }
};
// 批量导入中
const handleProgress = (response) => {};
// 批量导入失败
const handleError = (response) => {
  ElMessage.success("导入失败!");
};
// 清空字段
const clean = () => {
  query.modelId = "";
  query.relatedparts = "";
  query.wpId = "";
  query.enabled = "";
  query.rank = "";
  query.name = "";
  query.pageNum = 1;
  state.tableData = [];
  total.value = 0;
};

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 categoryConvert = (val) => {
  if (val === "windturbine") {
    return "风机";
  } else if (val === "inverter") {
    return "光伏";
  }
};
// 状态
const enabledConvert = (val) => {
  if (val === false) {
    return "停用";
  } else if (val === true) {
    return "启用";
  }
};
</script>
<style scoped lang="less">
.custom-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;
      .el-button + .el-button {
        margin-left: 10px;
      }
    }

    .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;
  }
}
</style>
