<template>
  <el-dialog v-model="dialogVisible" :title="dialogType == 'add' ? '新增辨识' : '查看辨识'" width="1200px"
    :before-close="closeConfirm">
    <el-form :disabled="dialogType != 'add'" ref="formRef" class="el-form-box" :model="formData" label-width="160px"
      :rules="rules">
      <el-form-item label="辨识单元:" prop="sitetypeInherent" style="width: 100%">
        <el-input :disabled="true" v-model="formData.sitetypeInherent" style="width: 280px"></el-input>
      </el-form-item>
      <el-form-item label="风险单元:" prop="activityfacility" style="width: 100%">
        <el-input :disabled="true" v-model="formData.activityfacility" style="width: 280px"></el-input>
      </el-form-item>
      <el-form-item label="风险描述:" prop="descriptionInherent" style="width: 100%">
        <el-input v-model="formData.descriptionInherent" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
          show-word-limit maxlength="500" />
      </el-form-item>
      <el-form-item label="可能产生的后果:" prop="consequenseInherent" style="width: 100%">
        <el-select v-model="formData.consequenseInherent" multiple placeholder="请选择可能产生的后果">
          <el-option v-for="item in D_BZ_KNFXHGLX" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="风险严重程度:" prop="sscoreInherent">
        <el-input-number v-model.number="formData.sscoreInherent" :min="1" :max="5" :step="1" :precision="0"
          style="width: 280px"></el-input-number>
      </el-form-item>
      <el-form-item label="风险等级:" prop="risklevelInherent">
        <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDJS" v-model="formData.risklevelInherent" style="width: 280px"
          selectType="select" placeholder='请选择风险等级' />
      </el-form-item>
      <el-form-item label="现有可控措施:" prop="existingMeasuresCurrent" style="width: 100%">
        <el-input type="textarea" rows="2" v-model="formData.existingMeasuresCurrent" placeholder="请输入现有措施"
          style="width:100%">
        </el-input>
      </el-form-item>
      <el-form-item label="可能存在的风险隐患:" prop="consequenseCurrent" style="width: 100%">
        <el-select v-model="formData.consequenseCurrent" multiple placeholder="请选择可能产生的后果">
          <el-option v-for="item in D_BZ_KNFXHGLX" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="L:" prop="lscore" style="width: 100%">
        <el-input-number v-model.number="formData.lscore" :min="1" :max="5" :step="1" :precision="0"
          style="width: 280px"></el-input-number>
      </el-form-item>
      <el-form-item label="S:" prop="sscore" style="width: 100%">
        <el-input-number v-model.number="formData.sscore" disabled :min="1" :max="5" :step="1" :precision="0"
          style="width: 280px"></el-input-number>
      </el-form-item>
      <el-form-item label="R:" prop="RScore">
        <span v-if="dialogType == 'add'" style="color:#000;display: inline-block;margin:auto ;width: 280px">{{
          formData.lscore &&
            formData.sscore ?
            (formData.lscore * formData.sscore) : '' }}</span>
        <el-input v-else v-model="formData.RScore" disabled style="width: 280px"></el-input>
      </el-form-item>
      <el-form-item label="现有风险等级:" prop="risklevelCurrent">
        <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDJS" v-model="formData.risklevelCurrent" style="width: 280px"
          selectType="select" placeholder='请选择风险等级' />
      </el-form-item>
      <el-form-item label="辨识人:" prop="identifyActualUserName" style="width: 100%">
        <el-input :disabled="true" v-model="formData.identifyActualUserName" style="width: 280px"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 保存按钮在左边 -->
        <el-button type="primary" v-if="dialogType == 'add'" :loading="btnLoading"
          @click="handleSave(formRef)">保存</el-button>
        <el-button @click="closeConfirm">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, getCurrentInstance, defineEmits, watch } from 'vue';
import { postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from 'element-plus';
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
const emits = defineEmits(['ok', 'close']);
const { D_BZ_KNFXHGLX, D_BZ_FXDJS, D_BZ_LSR_L, D_BZ_LSR_S } = proxy.$dict("D_BZ_KNFXHGLX", "D_BZ_FXDJS", "D_BZ_LSR_L", "D_BZ_LSR_S")
const formRef = ref(null);
const btnLoading = ref(false);
const dialogType = ref('add');
const rules = reactive({
  sitetypeInherent: [{ required: true, message: "风险等级不能为空", trigger: "blur" }],
  activityfacility: [{ required: true, message: "风险等级不能为空", trigger: "blur" }],
  descriptionInherent: [{ required: true, message: "风险描述不能为空", trigger: "blur" }],
  consequenseInherent: [{ required: true, message: "可能产生的后果不能为空", trigger: "blur" }],
  sscoreInherent: [{ required: true, message: "风险严重程度不能为空", trigger: "blur" }],
  risklevelInherent: [{ required: true, message: "风险等级不能为空", trigger: "blur" }],
  existingMeasuresCurrent: [{ required: true, message: "现有可控措施不能为空", trigger: "blur" }],
  consequenseCurrent: [{ required: true, message: "可能存在的风险隐患不能为空", trigger: "blur" }],
  lscore: [{ required: true, message: "可能性(L)不能为空", trigger: "blur" }],
  sscore: [{ required: true, message: "严重程度(S)不能为空", trigger: "blur" }],
  RScore: [{ required: true, message: "风险等级(R)不能为空", trigger: "blur" }],
  risklevelCurrent: [{ required: true, message: "请选择风险等级", trigger: "blur" }],
  identifyActualUserName: [{ required: true, message: "辨识人不能为空", trigger: "blur" }],
});

/** 弹框显示状态 */
const dialogVisible = ref(false);

/** 表单数据
 * @param {Object} formDataObj 表单数据对象
 * @param {String} formDataObj.risklevel 风险等级
 * @param {String} formDataObj.consequense 可能产生的后果
 * @param {String} formDataObj.description 危险源描述

 */
const formData = ref({
  risklevel: '',
  consequense: [],
  description: '',
});

const str2Arr = (str) => {
  if (Array.isArray(str)) return str;
  if (!str?.length) return [];
  if (typeof str === 'string') return str.split(',');
  return [];
}
/** 打开弹框
 */
const openDialog = (formDataObj, type) => {
  dialogVisible.value = true;
  dialogType.value = type;
  if (dialogType.value === 'view') {
    formData.value = {
      ...formDataObj,
    };
    formData.value.consequenseCurrent = formData.value.consequenseCurrent.split(',')
    formData.value.consequenseInherent = formData.value.consequenseInherent.split(',')
  } else {
    formRef.value.resetFields();
    formData.value = {
      ...formDataObj
    };
  }
};

/** 关闭弹框 */
const closeDialog = () => {
  dialogVisible.value = false;
  emits('close');
};
const closeConfirm = () => {
  closeDialog();
}
/** 数组转换为字符串 */
const Array2String = (arr) => {
  if (!Array.isArray(arr)) return '';
  return arr.join(',')
}
/** 保存表单数据 */
const handleSave = (formRef) => {
  if (!formRef) return;
  formRef.validate(valid => {
    if (valid) {
      // data.consequense = data.consequense ? data.consequense.toString() : '';
      const params = {
        ...formData.value,
        riskseverity: formData.value.sscore,
        consequense: Array2String(formData.value.consequense)
      }
      btnLoading.value = true;
      if (formData.value.id) {
        postApi(params, "/mosty-jcgl/danger2Baseinfo/edit").then((res) => {
          ElMessage.success('修改成功');
          emits('ok', formData.value);
          dialogVisible.value = false;
        }).finally(() => {
          btnLoading.value = false;
        })

      } else {
        postApi(params, "/mosty-jcgl/danger2Baseinfo/add").then((res) => {
          ElMessage.success('新增成功');
          emits('ok', formData.value);
          dialogVisible.value = false;
        }).finally(() => {
          btnLoading.value = false;
        })

      }
    } else {
      ElMessage.error('请检查表单!');
    }
  });
};
// 监听S风险严重程度的变化，自动设置风险等级
watch(() => formData.value.sscore, (newVal) => {
  if (!newVal) return;

  const riskLevelMap = {
    1: '1', // 较小
    2: '2', // 一般
    3: '3', // 较大
    4: '4', // 重大
    5: '5'  // 特别重大
  };

  formData.value.risklevel = riskLevelMap[newVal] || '';
});
// 暴露方法供外部调用
defineExpose({ openDialog });

</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  /* 保存按钮在左边 */
}

.el-form-box {
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
}
</style>
