<template>
  <el-dialog v-model="dialogVisible" title="风险信息" width="1200px" :before-close="closeConfirm">
    <el-form ref="formRef" class="el-form-box" :model="formData" label-width="160px" :rules="rules">
      <el-form-item label="风险单元类型:" prop="sitetype">
        <el-input v-model="formData.sitetype" style="width: 280px" disabled></el-input>

        <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDYLX" v-model="formData.sitetype" style="width: 280px"
          selectType="radio" disabled placeholder='请选择风险单元类型' /> -->
      </el-form-item>
      <el-form-item label="风险单元名称:" prop="activityfacility">
        <el-input v-model="formData.activityfacility" style="width: 280px" disabled></el-input>
      </el-form-item>
      <el-form-item label="风险描述:" prop="description" style="width: 100%">
        <el-input v-model="formData.description" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" show-word-limit
          maxlength="500" />
      </el-form-item>
      <el-form-item label="可能产生的后果:" prop="consequense" style="width: 100%">
        <el-select v-model="formData.consequense" 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="type">
        <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXLX" v-model="formData.type" disabled style="width: 280px"
          selectType="radio" placeholder='请选择风险单元类型' />
      </el-form-item> -->
      <el-form-item label="S风险严重程度:" prop="sscore">
        <el-input-number v-model.number="formData.sscore" :min="1" :max="5" :step="1" :precision="0"
          style="width: 280px"></el-input-number>
      </el-form-item>
      <el-form-item label="风险等级:" prop="risklevel">
        <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDJS" disabled v-model="formData.risklevel" style="width: 280px"
          selectType="select" placeholder='请选择风险等级' />
      </el-form-item>
      <el-form-item label="备注:" prop="bz" style="width: 100%">
        <el-input v-model="formData.bz" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" show-word-limit
          maxlength="500" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 保存按钮在左边 -->
        <el-button type="primary" :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_FXDJ, D_BZ_FXYZCD, D_BZ_FXLX, D_BZ_KNFXHGLX, D_BZ_FXDJS } = proxy.$dict("D_BZ_FXDJ", "D_BZ_FXDYLX", "D_BZ_FXLX", "D_BZ_KNFXHGLX", "D_BZ_FXYZCD", "D_BZ_FXDJS")

const formRef = ref(null);
const btnLoading = ref(false);
const rules = reactive({
  activityfacility: [{ required: true, message: "活动或设施不能为空", trigger: "blur" }],
  sitetype: [{ required: true, message: "风险单元类型不能为空", trigger: "blur" }],
  risklevel: [{ required: true, message: "风险等级不能为空", trigger: "blur" }],

  consequense: [{ required: true, message: "可能产生的后果不能为空", trigger: "blur" }],
  description: [{ required: true, message: "危险源描述不能为空", trigger: "blur" }],
  // type: [{ required: true, message: "风险类型不能为空", trigger: "blur" }],
  // jcpl:[{ required: true, message: "检查频率不能为空", trigger: "blur" }]
});

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

/** 表单数据
 * @param {Object} formDataObj 表单数据对象
 * @param {String} formDataObj.activityfacility 活动或设施
 * @param {String} formDataObj.sitetype 风险单元类型
 * @param {String} formDataObj.risklevel 风险等级
 * @param {String} formDataObj.consequense 可能产生的后果
 * @param {String} formDataObj.description 危险源描述
 * @param {String} formDataObj.type 风险类型
 * @param {String} formDataObj.jcpl 检查频率
 * @param {String}formDataObj.bz 备注
 */
const formData = ref({
  activityfacility: '',
  sitetype: '',
  risklevel: '',
  consequense: [],
  description: '',
  type: '',
  jcpl: '',
  bz: ''
});
/** 根据左边树,获取需要的风险单位类型 */
const getNeedSiteType = (dm = '') => {
  const siteVal = dm.slice(0, 2)
  if (siteVal == '20') {
    return '02'
  } else if (siteVal == '30') {
    return '03'
  } else {
    return '01'
  }
}
const str2Arr = (str) => {
  if (Array.isArray(str)) return str;
  if (!str?.length) return [];
  if (typeof str === 'string') return str.split(',');
  return [];
}
/** 打开弹框
 * @param {Object} formDataObj 表单数据对象
 * @param {String} dialogType 弹框类型 'edit','add'
 */
const openDialog = (formDataObj, dialogType) => {
  dialogVisible.value = true;
  if (dialogType === 'edit') {
    formData.value = {
      ...formDataObj,
      consequense: str2Arr(formDataObj.consequense),
      type: '1', // 1:固有风险单元 2:现状风险
    };
  } else {
    formData.value = {
      ...formDataObj,
      consequense: str2Arr(formDataObj.consequense),
      type: '1', // 1:固有风险单元 2:现状风险
    };

  }
};

/** 关闭弹框 */
const closeDialog = () => {
  dialogVisible.value = false;
  emits('close');
};
const closeConfirm = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      closeDialog();
    })
    .catch(() => {
      // catch error
    })

}
/** 数组转换为字符串 */
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,
        type: '1', // 1:固有风险单元 2:现状风险
        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>
