<template>
  <el-dialog
    v-model="visible"
    :title="type === 'add' ? '新增' : '修改'"
    :before-close="fnClose"
  >
    <el-form ref="formRef" :rules="rules" :model="form" label-width="240px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="管控部门" prop="DEPARTMENT_ID">
            <layout-department
              v-model="form.DEPARTMENT_ID"
              @update:model-value="fnDepartmentChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管控责任人" prop="USER_ID">
            <el-input v-model="form.USER_ID" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="风险点（单元）" prop="RISK_UNIT_ID">
            <el-select v-model="form.RISK_UNIT_ID" @change="fnRiskUnitChange">
              <el-option
                v-for="item in unitList"
                :key="item.RISKUNIT_ID"
                :label="item.DEPT_NAME + '-' + item.RISKUNITNAME"
                :value="item.RISKUNIT_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="辨识部位" prop="IDENTIFICATION_ID">
            <el-select v-model="form.IDENTIFICATION_ID">
              <el-option
                v-for="item in partsList"
                :key="item.IDENTIFICATIONPARTS_ID"
                :label="item.PARTSNAME"
                :value="item.IDENTIFICATIONPARTS_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="存在风险" prop="RISK_DESCR">
            <el-input
              v-model="form.RISK_DESCR"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="事故发生的可能性" prop="LIKELIHOOD">
            <el-select v-model="form.LIKELIHOOD">
              <el-option :value="10" label="完全可以预料" />
              <el-option :value="6" label="相当可能" />
              <el-option :value="3" label="可能，但不经常" />
              <el-option :value="1" label="可能性小，完全意外" />
              <el-option :value="0.5" label="很不可能，可以设想" />
              <el-option :value="0.2" label="极不可能" />
              <el-option :value="0.1" label="实际不可能" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分值">
            {{ form.LIKELIHOOD }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="人员暴露于危险环境中的频繁程度" prop="EXPOSURE">
            <el-select v-model="form.EXPOSURE">
              <el-option :value="10" label="连续暴露" />
              <el-option :value="6" label="每天工作时间内暴露" />
              <el-option :value="3" label="每周一次或偶然暴露" />
              <el-option :value="2" label="每月一次暴露，完全意外" />
              <el-option :value="1" label="每年几次暴露" />
              <el-option :value="0.5" label="非常罕见暴露" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分值">
            {{ form.EXPOSURE }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="一旦发生事故可能造成的后果" prop="CONSEQUENCE">
            <el-select v-model="form.CONSEQUENCE">
              <el-option :value="100" label="10人以上死亡" />
              <el-option :value="40" label="3～9人死亡" />
              <el-option :value="15" label="1～2人死亡" />
              <el-option :value="7" label="严重" />
              <el-option :value="3" label="重大，伤残" />
              <el-option :value="1" label="引人注意" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分值">
            {{ form.CONSEQUENCE }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风险分级" prop="LEVEL_NAME">
            {{ form.LEVEL_NAME }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总分值" prop="DANGER">
            {{ form.DANGER }}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管控措施" prop="MEASURES">
            <el-input
              v-model="form.MEASURES"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="事故类型" prop="ACCIDENTS">
            <el-select v-model="form.ACCIDENTS" multiple>
              <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="24">
          <el-form-item label="应急处置措施" prop="EME_MEASURES">
            <el-input
              v-model="form.EME_MEASURES"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管控措施分类1" prop="MANAGEMENT_CONTROL_ONE">
            <el-select
              v-model="form.MANAGEMENT_CONTROL_ONE"
              @change="form.MANAGEMENT_CONTROL_TWO = ''"
            >
              <el-option
                v-for="item in controlList1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管控措施分类2" prop="MANAGEMENT_CONTROL_TWO">
            <el-select v-model="form.MANAGEMENT_CONTROL_TWO">
              <el-option
                v-for="item in controlList2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="管控措施分类3" prop="MANAGEMENT_CONTROL_THREE">
            <el-input
              v-model="form.MANAGEMENT_CONTROL_THREE"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="fnClose">取消</el-button>
      <el-button type="primary" @click="fnSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, watchEffect } from "vue";
import { useVModels } from "@vueuse/core";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import {
  layoutFnGetAccidentType,
  layoutFnGetControlMeasures1,
  layoutFnGetControlMeasures2,
} from "@/assets/js/data_dictionary.js";
import {
  getIdentifyingPartsListAll,
  getRiskPointListAllById,
  setRiskControlLedgerAdd,
  setRiskControlLedgerEdit,
} from "@/request/risk_control.js";
import LayoutDepartment from "@/components/department/index.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  type: {
    type: String,
    required: true,
    default: "",
  },
});
const emits = defineEmits(["update:visible", "update:form", "get-data"]);
const { visible, form } = useVModels(props, emits);
const rules = {
  DEPARTMENT_ID: [
    { required: true, message: "部门不能为空", trigger: "change" },
  ],
  USER_ID: [{ required: true, message: "管控责任人不能为空", trigger: "blur" }],
  RISK_UNIT_ID: [
    { required: true, message: "风险点（单元）不能为空", trigger: "change" },
  ],
  IDENTIFICATION_ID: [
    { required: true, message: "辨识部位不能为空", trigger: "change" },
  ],
  RISK_DESCR: [
    { required: true, message: "存在风险不能为空", trigger: "blur" },
  ],
  LIKELIHOOD: [
    { required: true, message: "事故发生的可能性不能为空", trigger: "change" },
  ],
  EXPOSURE: [
    {
      required: true,
      message: "人员暴露于危险环境中的频繁程度不能为空",
      trigger: "change",
    },
  ],
  CONSEQUENCE: [
    {
      required: true,
      message: "一旦发生事故可能造成的后果不能为空",
      trigger: "change",
    },
  ],
  LEVELID: [{ required: true, message: "风险分级不能为空", trigger: "blur" }],
  MEASURES: [{ required: true, message: "管控措施不能为空", trigger: "blur" }],
  EME_MEASURES: [
    { required: true, message: "应急处置措施不能为空", trigger: "blur" },
  ],
  ACCIDENTS: [
    { required: true, message: "事故类型不能为空", trigger: "change" },
  ],
};
const formRef = ref(null);
const unitList = ref([]);
const partsList = ref([]);
const controlList2 = ref([]);
const controlList1 = await layoutFnGetControlMeasures1();
const controlList2All = await layoutFnGetControlMeasures2();
const fnGetUnitList = async () => {
  const resData = await getRiskPointListAllById({
    DEPARTMENT_ID: form.value.DEPARTMENT_ID,
  });
  unitList.value = resData.unitList;
};
const fnGetPartsList = async () => {
  const resData = await getIdentifyingPartsListAll({
    RISK_UNIT_ID: form.value.RISK_UNIT_ID,
  });
  partsList.value = resData.partsList;
};
const fnDepartmentChange = () => {
  form.value.RISK_UNIT_ID = "";
  form.value.IDENTIFICATION_ID = "";
  unitList.value = [];
  partsList.value = [];
};
const fnRiskUnitChange = () => {
  form.value.IDENTIFICATION_ID = "";
  partsList.value = [];
};
const accidentTypeList = await layoutFnGetAccidentType();
const fnGetLevelName = (LIKELIHOOD, EXPOSURE, CONSEQUENCE) => {
  const DANGER = (LIKELIHOOD * EXPOSURE * CONSEQUENCE).toFixed(2);
  if (DANGER > 320) {
    form.value.LEVELID = "levelA";
    form.value.LEVEL_NAME = "重大风险/A级";
  } else if (DANGER > 160) {
    form.value.LEVELID = "levelB";
    form.value.LEVEL_NAME = "较大风险/B级";
  } else if (DANGER > 70) {
    form.value.LEVELID = "levelC";
    form.value.LEVEL_NAME = "一般风险/C级";
  } else {
    form.value.LEVELID = "levelD";
    form.value.LEVEL_NAME = "低风险/D级";
  }
  form.value.DANGER = DANGER;
};
watch(
  [
    () => props.form.LIKELIHOOD,
    () => props.form.EXPOSURE,
    () => props.form.CONSEQUENCE,
  ],
  ([LIKELIHOOD, EXPOSURE, CONSEQUENCE]) => {
    if (!LIKELIHOOD || !EXPOSURE || !CONSEQUENCE) return;
    fnGetLevelName(LIKELIHOOD, EXPOSURE, CONSEQUENCE);
  }
);
watchEffect(() => {
  if (form.value.DEPARTMENT_ID) fnGetUnitList();
  if (form.value.RISK_UNIT_ID) fnGetPartsList();
  if (form.value.MANAGEMENT_CONTROL_ONE) fnControlList1Change();
});
const fnControlList1Change = () => {
  controlList2.value = [];
  const id = form.value.MANAGEMENT_CONTROL_ONE;
  let BZ = "";
  for (let i = 0; i < controlList1.value.length; i++) {
    if (controlList1.value[i].id === id) {
      BZ = controlList1.value[i].BZ;
      break;
    }
  }
  for (let i = 0; i < controlList2All.value.length; i++) {
    if (controlList2All.value[i].TBFIELD === BZ) {
      controlList2.value.push(controlList2All.value[i]);
    }
  }
};
const fnClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const ACCIDENTS_NAME = accidentTypeList.value
      .filter((item) => form.value.ACCIDENTS.includes(item.BIANMA))
      .map((item) => item.NAME)
      .join(",");
    const params = {
      ...form.value,
      CHECK_CONTENT: form.value.MEASURES,
      ACCIDENTS: form.value.ACCIDENTS.join(","),
      ACCIDENTS_NAME,
    };
    if (props.type === "add") await setRiskControlLedgerAdd(params);
    else await setRiskControlLedgerEdit(params);
    ElMessage.success("操作成功");
    fnClose();
    emits("get-data");
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss"></style>
