<template>
    <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="/sharding/alertrule2/import"
          :headers="token" :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">
          <el-option key="1" label="风机" value="1"></el-option>
          <el-option key="2" label="电气" value="2"></el-option>
        </el-select>
        <el-select v-if="!isStation" v-model="query.station" clearable class="mr10" 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 class="mr10" 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-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">
      <el-table-column label="编码" align="center" prop="id" min-width="50" />
      <el-table-column label="场站" align="center" prop="windPowerStation.name" min-width="50" />
      <el-table-column label="机型" align="center" prop="modelId" min-width="50" />
      <el-table-column label="名称" align="left" prop="name" min-width="50" />
      <el-table-column label="表达式" align="left">
        <template #default="scope">
          {{ scope.row.expressionShow }}
        </template>
      </el-table-column>
      <el-table-column label="级别" align="center" prop="rank" min-width="20">
        <template #default="scope">{{ rankConvert(scope.row.rank) }}</template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="category" min-width="20">
        <template #default="scope">{{
            categoryConvert(scope.row.category)
        }}</template>
      </el-table-column>
      <el-table-column label="描述" align="left">
        <template #default="scope">
          {{ scope.row.descriptionShow }}
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="enabled" min-width="20">
        <template #default="scope">
          {{ enabledConvert(scope.row.enabled) }}
        </template>
      </el-table-column>
      <el-table-column label="所属部件" align="center" prop="relatedParts" min-width="30">
        <template #default="scope">
          <span>{{ scope.row.datadictionary?.name }}</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 || scope.row.range == 1" @click="handleEditClick(scope.row)">编辑</el-button>
          <!-- <el-button type="primary" plain round size="mini" icon="el-icon-search" @click="handleViewClick(scope.$index, scope.row)">查看</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" hide-on-single-page :current-page="query.pagenum"
        :page-size="query.pagesize" :total="total" @current-change="handlePageChange"></el-pagination>
    </div>
    <customcomponents @close="dialogclose" :isVisible="state.visible" :form="state.form" />
</template>
<script setup>
import { custombj_fetchTableData, getStationinfo } from "/@/api/api.js";
import { outExportExcel } from "/@/utils/exportExcel"; //引入文件
import { ref, onMounted, provide, computed, reactive, watch } from "vue";
import { useStore } from "vuex";
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 stationList = computed(() => store.state.stationList);
const isStation = computed(() => store.getters.isStation);
const state = reactive({
  tableData: [],
  modelList: [],
  rankList: [
    {
      id: 1,
      name: "低",
    },
    {
      id: 2,
      name: "中低",
    },
    {
      id: 3,
      name: "中",
    },
    {
      id: 4,
      name: "中高",
    },
    {
      id: 5,
      name: "高",
    },
  ],
  visible: false,
  form: {},
});
const query = reactive({
  pagenum: 1,
  pagesize: 10,
  name: "",
  station: "",
  rank: "",
  modelId: "",
  category: "1",
});
let total = ref(0);
onMounted(() => {
  getData();
  getequipmentmodel_list()
});
const dialogclose = () => {
  state.visible = false
  getData()
}
const getData = async () => {
  const res = await custombj_fetchTableData(query);
  state.tableData = res.records;
  total.value = res.total;
};
const handleEditClick = (row) => {
  let obj = Object.assign({}, row)
  state.form = obj;
  state.visible = true;
};
const handleInsert = () => {
  state.visible = true;
};

//changeStation
const changeStation = async () => {
  query.modelId = "";
  await getequipmentmodel_list();
};
// 机型
const getequipmentmodel_list = async () => {
  const { data } = await getStationinfo(query.station);
  if (query.station == '') {
    let arr = []
    data.forEach(e => {
      arr.push(...e.modelList)
    });
    state.modelList = [...new Set(arr)]
  } else {
    state.modelList = data[0].modelList;
  }
};
// 分页导航
const handlePageChange = (val) => {
  query.pagenum = val;
  getData();
};
const tableHeader = [
  "id",
  "规则名称",
  "报警类别（1：风气；2：电气）",
  "报警级别（1：低；2：中低；3：中；4：中高；5：高）",
  "是否启用（0：停用；1：启用）",
  "风场",
  "风机类型",
  "所属部件",
  "表达式",
  "规则描述",
];

const tableKey = [
  "id",
  "name",
  "category",
  "rank",
  "enabled",
  "station",
  "modelId",
  "relatedParts",
  "expressionShow",
  "descriptionShow",
];
// 批量导出
const export2Excel = async () => {
  let { name, station, rank, modelId, category } = query;
  const res = await custombj_fetchTableData({
    pagenum: 1,
    pagesize: 999999,
    name,
    station,
    rank,
    modelId,
    category,
  });

  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 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 === "1") {
    return "风机";
  } else if (val === "2") {
    return "电气";
  }
};
// 状态
const enabledConvert = (val) => {
  if (val === 0) {
    return "停用";
  } else if (val === 1) {
    return "启用";
  }
};
</script>
<style scoped>
.mr10 {
  margin-right: 10px;
}

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