<template>
  <el-form ref="formRef" :rules="rules" :model="form" label-width="240px">
    <el-row>
      <el-col :span="24" v-if="!infoIsEmpty">
        <el-form-item label="管控部门" prop="DEPTNAME">
          <el-input :model-value="info.DEPTNAME" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="infoIsEmpty">
        <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>
      <template v-if="!infoIsEmpty">
        <el-col :span="24">
          <el-form-item label="风险点（单元）" prop="RISKUNITNAME">
            <el-input :model-value="info.RISKUNITNAME" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="辨识部位" prop="PARTSNAME">
            <el-input :model-value="info.PARTSNAME" disabled />
          </el-form-item>
        </el-col>
      </template>
      <template v-if="infoIsEmpty">
        <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>
      </template>
      <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>
      <template v-if="control">
        <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>
      </template>
    </el-row>
  </el-form>
</template>

<script setup>
import { ref, watch, watchEffect } from "vue";
import { useVModel } from "@vueuse/core";
import {
  layoutFnGetAccidentType,
  layoutFnGetControlMeasures1,
  layoutFnGetControlMeasures2,
} from "@/assets/js/data_dictionary.js";
import useFormValidate from "@/assets/js/useFormValidate.js";
import LayoutDepartment from "@/components/department/index.vue";
import { isEmpty } from "lodash-es";
import {
  getIdentifyingPartsListAll,
  getRiskPointListAllById,
} from "@/request/risk_control.js";

defineOptions({
  name: "LayoutRiskAdd",
});
const props = defineProps({
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  info: {
    type: Object,
    default: () => ({}),
  },
  control: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:form"]);
const form = useVModel(props, "form", emits);
const rules = {
  USER_ID: [{ required: true, message: "管控责任人不能为空", trigger: "blur" }],
  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",
    },
  ],
  LEVEL_NAME: [
    { required: true, message: "风险分级不能为空", trigger: "change" },
  ],
  MEASURES: [{ required: true, message: "管控措施不能为空", trigger: "blur" }],
  EME_MEASURES: [
    { required: true, message: "应急处置措施不能为空", trigger: "blur" },
  ],
  ACCIDENTS: [
    { required: true, message: "事故类型不能为空", trigger: "change" },
  ],
  DEPARTMENT_ID: [
    { required: true, message: "部门不能为空", trigger: "change" },
  ],
  RISK_UNIT_ID: [
    { required: true, message: "风险点（单元）不能为空", trigger: "change" },
  ],
  IDENTIFICATION_ID: [
    { required: true, message: "辨识部位不能为空", trigger: "change" },
  ],
};
const formRef = ref(null);
const infoIsEmpty = ref(isEmpty(props.info));
const unitList = ref([]);
const partsList = ref([]);
const controlList2 = ref([]);
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);
  }
);
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 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 fnDepartmentChange = () => {
  form.value.RISK_UNIT_ID = "";
  form.value.IDENTIFICATION_ID = "";
  unitList.value = [];
  partsList.value = [];
};
const fnRiskUnitChange = () => {
  form.value.IDENTIFICATION_ID = "";
  partsList.value = [];
};
watchEffect(() => {
  if (form.value.DEPARTMENT_ID) fnGetUnitList();
  if (form.value.RISK_UNIT_ID) fnGetPartsList();
  if (form.value.MANAGEMENT_CONTROL_ONE) fnControlList1Change();
});
const fnReset = () => {
  formRef.value.resetFields();
};
const fnFormValidate = async () => {
  await useFormValidate(formRef);
};
const fnAccidentsName = () => {
  return accidentTypeList.value
    .filter((item) => form.value.ACCIDENTS.includes(item.BIANMA))
    .map((item) => item.NAME)
    .join(",");
};
defineExpose({
  reset: fnReset,
  formValidate: fnFormValidate,
  accidentsName: fnAccidentsName,
});
const accidentTypeList = await layoutFnGetAccidentType();
const controlList1 = props.control && (await layoutFnGetControlMeasures1());
const controlList2All = props.control && (await layoutFnGetControlMeasures2());
</script>

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