<template>
  <div>
    <el-card>
      <el-form
        :model="searchForm"
        label-width="90px"
        @submit.prevent="fnResetPaginationTransfer"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="关键字" prop="KEYWORDS">
              <el-input
                v-model="searchForm.KEYWORDS"
                placeholder="请输入关键字"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="风险分级">
              <el-select v-model="searchForm.LEVELID">
                <el-option
                  v-for="item in riskClassificationList"
                  :key="item.BIANMA"
                  :label="item.NAME"
                  :value="item.BIANMA"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管控部门" prop="DEPTIDS">
              <layout-department
                v-model="searchForm.DEPTIDS"
                multiple
                show-checkbox
                collapse-tags
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="管控责任人" prop="gkzrName">
              <el-input v-model="searchForm.gkzrName" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="事故类型">
              <el-select v-model="searchForm.BIANMA">
                <el-option
                  v-for="item in accidentTypeList"
                  :key="item.BIANMA"
                  :label="item.NAME"
                  :value="item.BIANMA"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="10px">
              <el-button type="primary" native-type="submit">搜索</el-button>
              <el-button native-type="reset" @click="fnResetPaginationTransfer">
                重置
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="10px" class="end">
              <el-button @click="fnImportDialogChangeShow"> 导入 </el-button>
              <el-button @click="fnExport">导出</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <layout-card>
      <layout-table
        ref="tableRef"
        :data="list"
        v-model:pagination="pagination"
        @get-data="fnGetDataTransfer"
        row-key="RISKPOINT_ID"
      >
        <el-table-column reserve-selection type="selection" width="55" />
        <el-table-column label="序号" width="70">
          <template v-slot="{ $index }">
            {{ serialNumber(pagination, $index) }}
          </template>
        </el-table-column>
        <el-table-column prop="DEPT_NAME_ALL" label="管控部门" />
        <el-table-column prop="RISKUNITNAME" label="风险点（单元）" />
        <el-table-column prop="PARTSNAME" label="辨识部位" />
        <el-table-column prop="LEVELID" label="风险分级">
          <template v-slot="{ row }">
            <span v-if="row.LEVELID === 'levelD'" class="text-blue">
              低风险/D级
            </span>
            <span v-else-if="row.LEVELID === 'levelC'" class="text-yellow">
              一般风险/C级
            </span>
            <span v-else-if="row.LEVELID === 'levelB'" class="text-orange">
              较大风险/B级
            </span>
            <span v-else-if="row.LEVELID === 'levelA'" class="text-red">
              重大风险/A级
            </span>
          </template>
        </el-table-column>
        <el-table-column label="事故类型">
          <template v-slot="{ row }">
            {{ row.ACCIDENTS_NAME.replace(/,/g, "、") }}
          </template>
        </el-table-column>
        <el-table-column prop="USER_ID" label="管控责任人" />
        <el-table-column label="操作" width="150">
          <template v-slot="{ row }">
            <el-button
              v-if="buttonJurisdiction.edit"
              type="primary"
              text
              link
              @click="
                router.push({
                  path: '/risk_control/ledger/allocation',
                  query: { RISKPOINT_ID: row.RISKPOINT_ID },
                })
              "
            >
              配置
            </el-button>
            <el-button
              v-if="buttonJurisdiction.edit"
              type="primary"
              text
              link
              @click="fnAddOrEdit(row.RISKPOINT_ID, 'edit')"
            >
              编辑
            </el-button>
            <el-button
              v-if="buttonJurisdiction.del"
              type="primary"
              text
              link
              @click="fnDelete(row.RISKPOINT_ID)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #button>
          <el-button
            v-if="buttonJurisdiction.add"
            type="primary"
            @click="fnAddOrEdit('', 'add')"
          >
            新增
          </el-button>
          <el-button
            v-if="buttonJurisdiction.del"
            type="danger"
            @click="fnBatchDelete"
          >
            批量删除
          </el-button>
        </template>
      </layout-table>
    </layout-card>
    <layout-import-file
      v-model:visible="data.importDialogVisible"
      template-url="template/riskpointExcelTemplate.xls"
      @submit="fnSubmitImport"
    />
    <add
      v-model:visible="data.addOrEditDialog.visible"
      v-model:form="data.addOrEditDialog.form"
      control
      :type="data.addOrEditDialog.type"
      @get-data="fnResetPaginationTransfer"
    />
  </div>
</template>

<script setup>
import { serialNumber } from "@/assets/js/utils.js";
import useListData from "@/assets/js/useListData.js";
import LayoutDepartment from "@/components/department/index.vue";
import {
  getRiskControlLedgerList,
  getRiskControlLedgerView,
  setRiskControlLedgerBatchDelete,
  setRiskControlLedgerDelete,
  setRiskControlLedgerImport,
} from "@/request/risk_control.js";
import { debounce } from "throttle-debounce";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, reactive } from "vue";
import LayoutImportFile from "@/components/import_file/index.vue";
import {
  layoutFnGetAccidentType,
  layoutFnGetRiskClassification,
} from "@/assets/js/data_dictionary.js";
import useButtonJurisdiction from "@/assets/js/useButtonJurisdiction.js";
import Add from "./components/add.vue";
import { useRouter } from "vue-router";

const { list, pagination, searchForm, fnGetData, fnResetPagination, tableRef } =
  useListData(getRiskControlLedgerList);
const router = useRouter();
const data = reactive({
  importDialogVisible: false,
  addOrEditDialog: {
    visible: false,
    type: "",
    form: {
      DEPARTMENT_ID: "",
      USER_ID: "",
      RISK_UNIT_ID: "",
      IDENTIFICATION_ID: "",
      RISK_DESCR: "",
      LIKELIHOOD: "",
      EXPOSURE: "",
      CONSEQUENCE: "",
      LEVEL_NAME: "",
      DANGER: "",
      MEASURES: "",
      ACCIDENTS: [],
      EME_MEASURES: "",
      MANAGEMENT_CONTROL_ONE: "",
      MANAGEMENT_CONTROL_TWO: "",
      MANAGEMENT_CONTROL_THREE: "",
    },
  },
});
const buttonJurisdiction = await useButtonJurisdiction("riskunit");
const riskClassificationList = await layoutFnGetRiskClassification();
const accidentTypeList = await layoutFnGetAccidentType();
const fnGetDataTransfer = () => {
  fnGetData({
    DEPTIDS: searchForm.value.DEPTIDS?.join(","),
  });
};
const fnResetPaginationTransfer = () => {
  fnResetPagination({
    DEPTIDS: searchForm.value.DEPTIDS?.join(","),
  });
};
const fnDelete = debounce(
  1000,
  async (RISKPOINT_ID) => {
    await ElMessageBox.confirm("确定要删除吗？", { type: "warning" });
    await setRiskControlLedgerDelete({ RISKPOINT_ID });
    ElMessage.success("删除成功");
    fnResetPaginationTransfer();
  },
  { atBegin: true }
);
const fnImportDialogChangeShow = () => {
  data.importDialogVisible = !data.importDialogVisible;
};
const fnSubmitImport = async (formData) => {
  const resData = await setRiskControlLedgerImport(formData);
  if (resData.resultStr) {
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: resData.resultStr,
      type: resData.resultType,
    });
  }
  fnImportDialogChangeShow();
  fnResetPaginationTransfer();
};
const fnExport = async () => {
  const selectionData = tableRef.value.getSelectionRows();
  if (selectionData.length === 0) {
    ElMessage.warning("请选择需要导出至excel报表的记录信息");
    return;
  }
  await ElMessageBox.confirm("确定要导出到excel吗？", { type: "warning" });
  const DATA_IDS = selectionData.map((item) => item.RISKPOINT_ID).join(",");
  window.location.href =
    import.meta.env[import.meta.env.DEV ? "VITE_PROXY" : "VITE_BASE_URL"] +
    "riskpoint/excel?" +
    "&KEYWORDS=" +
    (searchForm.value.KEYWORDS || "") +
    "&DATA_IDS=" +
    DATA_IDS;
};
const fnBatchDelete = debounce(
  1000,
  async () => {
    const selectionData = tableRef.value.getSelectionRows();
    if (selectionData.length === 0) {
      ElMessage.warning("请选中要删除的项");
      return;
    }
    await ElMessageBox.confirm("确定要删除选中的数据吗？", { type: "warning" });
    const DATA_IDS = selectionData.map((item) => item.RISKPOINT_ID).join(",");
    await setRiskControlLedgerBatchDelete({ DATA_IDS });
    ElMessage.success("删除成功");
    fnResetPaginationTransfer();
  },
  { atBegin: true }
);
const fnAddOrEdit = async (RISKPOINT_ID, type) => {
  data.addOrEditDialog.visible = true;
  await nextTick();
  data.addOrEditDialog.type = type;
  if (type === "edit") {
    const resData = await getRiskControlLedgerView({ RISKPOINT_ID });
    data.addOrEditDialog.form = resData.pd;
    data.addOrEditDialog.form.ACCIDENTS = resData.pd.ACCIDENTS.split(",");
  }
};
</script>

<style scoped></style>
