<template>
  <el-card>
    <el-row type="flex" justify="space-between">
      <div class="handle-box" style="margin-bottom: 10px">
        <el-button
          type="primary"
          icon="el-icon-lx-add"
          class="handle-edit mr10"
          @click="handleInsert"
        >
          新增记录
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-lx-down"
          class="handle-edit mr10"
          @click="export2Excel"
        >
          批量导出</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-lx-down"
          class="handle-edit mr10"
          @click="outExe"
        >
          模板下载</el-button
        >
        <el-upload
          class="handle-edit mr10"
          style="display: inline"
          :action="baseURL + 'alertrule/import'"
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :on-error="handleError"
        >
          <el-button
            type="primary"
            icon="el-icon-lx-top"
            @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.category"
          class="mr10"
          style="width: 150px"
          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
          class="mr10"
          style="width: 150px"
          :placeholder="
            query.category == 'windturbine' ? '全部场站' : '全部升压站'
          "
          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-if="query.category == 'windturbine'"
          v-model="query.relatedparts"
          clearable
          class="mr10"
          style="width: 150px"
          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
          class="mr10"
          style="width: 150px"
          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-if="query.category == 'windturbine'"
          v-model="query.modelId"
          clearable
          class="mr10"
          style="width: 150px"
          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
          class="mr10"
          style="width: 150px"
          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"
          style="width: 150px"
          class="mr10"
          clearable
        ></el-input>
        <el-button icon="el-icon-search" type="primary" @click="getData"
          >搜索</el-button
        >
      </div>
    </el-row>
    <el-table
      :data="state.tableData"
      border
      class="table"
      header-cell-name="table-header"
      :highlight-current-row="true"
      height="calc(100% - 42px - 45px)"
    >
      <el-table-column
        v-for="item in query.category == 'windturbine'
          ? state.tableHeader
          : state.tableHeader1"
        :key="item.code"
        :label="item.title"
        align="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="primary"
            plain
            round
            size="mini"
            icon="el-icon-lx-edit"
            :disabled="notEdit"
            @click="handleEditClick(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page="query.pageNum"
        :page-size="query.pageSize"
        :page-sizes="[4, 50, 100, 200, 500]"
        :total="total"
        @size-change="
          (value) => {
            query.pageSize = value;
            query.pageNum = 1;
            getData();
          }
        "
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <customcomponents
      @close="dialogclose"
      :isVisible="state.visible"
      :form="state.form"
      :rankList="state.rankList"
      :modelListAll="state.modelListAll"
      :fetchListAll="state.fetchListAll"
    />
  </el-card>
</template>
<script setup>
import {
  custombj_fetchTableData,
  getStationinfo,
  fetchRelatePartAndAlarmType,
  fetchModel,
  fetchBooststation,
  custombj_importTemplate,
  getWpList,
} from "/@/api/api.js";
import { baseURL } from "/@/api/apiConfig.js";
import { outExportExcel } from "/@/utils/exportExcel"; //引入文件
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 "./custom_components.vue";
import { common } from "/@/composables/common";
const { notEdit } = common();
const token = { token: sessionStorage.getItem("token") };
const store = useStore();
const router = useRouter();
const isStation = computed(() => store.getters.isStation);
const query = reactive({
  pageNum: 1,
  pageSize: 4,
  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,
    "自定义预警配置导出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 === "booststation") {
    return "升压站";
  }
};
// 状态
const enabledConvert = (val) => {
  if (val === false) {
    return "停用";
  } else if (val === true) {
    return "启用";
  }
};
</script>
<style scoped lang="scss">
:deep.el-card {
  height: 100%;
  .el-card__body {
    height: calc(100% - 40px);
  }
}
.mr10 {
  margin-right: 10px;
}

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