<template>
  <el-dialog v-model="props.innerShow" width="700px" :before-close="handleClose" :title="props.title" append-to-body>
    <el-form ref="formRef" :model="form" label-position="right" label-width="150px" :rules="rules"
      style="width: 100%;display: block;" :inline="false" :disabled='!props.savebtnshow'>
      <!-- <el-form-item label="风险管控等级" prop="dangerControlLevel">
        <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_FXBS_GKCS_FXGKDJ" v-model="form.dangerControlLevel"
          :placeholder="'请选择风险管控等级'" style="width: 300px" />
      </el-form-item> -->
      <!-- <el-form-item label="风险动态监测情况" prop="dangerDynamicMonitorSituation">
        <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_FXBS_GKCS_FXDTJCQK"
          v-model="form.dangerDynamicMonitorSituation" :placeholder="'请选择风险动态监测情况'" style="width: 300px" />
      </el-form-item> -->
      <!-- 措施类型：仅在查看时显示 -->
      <el-form-item v-if="!props.savebtnshow" label="措施类型">
        <el-input :value="getDictLabel(D_FXBS_GKCS_AQCSLX, form.measuresType)" :readonly="true" placeholder="措施类型"
          style="width: 300px" />
      </el-form-item>
      <!-- 措施内容 -->
      <el-form-item label="措施内容" prop="measuresContent">
        <MOSTY.DictTree :zdbh="'D_FXBS_GKCS_AQCSLX'" v-model="form.measuresContent" :placeholder="'请选择措施内容'"
          style="width: 300px" :disabled="!props.savebtnshow" />
      </el-form-item>

      <!-- 计划完成时间 -->
      <el-form-item label="计划完成时间" prop="completeDatePlan">
        <el-date-picker v-model="form.completeDatePlan" type="date" placeholder="请选择计划完成时间" value-format="YYYY-MM-DD"
          style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formRef)" v-if='props.savebtnshow'>
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="handleClose" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
// 引入
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { postApi, getApi } from "@/api/tobAcco_api.js";

const { proxy } = getCurrentInstance();
const { D_FXBS_GKCS_FXGKDJ, D_FXBS_GKCS_AQCSLX, D_FXBS_GKCS_FXDTJCQK } = proxy.$dict("D_FXBS_GKCS_FXGKDJ", "D_FXBS_GKCS_AQCSLX", "D_FXBS_GKCS_FXDTJCQK");
const props = defineProps({
  innerShow: {
    type: Boolean,
    default: false
  },
  savebtnshow: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: "新增排查项"
  },
  formValue: {
    type: Object,
    default: {}
  },
  dict: {
    type: Object,
    default: { D_FXBS_GKCS_FXGKDJ: [], D_FXBS_GKCS_AQCSLX: [], D_FXBS_GKCS_SFBCYCS: [] }
  },
  editIndex: {
    type: Number,
    default: -1
  },
  planid: {
    type: String,
    default: ''
  },
});
const emits = defineEmits(["changeVi", "getList"]);

// 表单验证规则
const rules = {
  // dangerDynamicMonitorSituation: { required: true, message: '请选择风险动态监测情况', trigger: 'blur' },
  measuresContent: { required: true, message: '请选择措施内容', trigger: 'blur' },
  completeDatePlan: { required: true, message: '请选择计划完成时间', trigger: 'blur' },
  // dangerControlLevel: { required: true, message: '请选择风险管控等级', trigger: 'blur' },
}
// 数据
const formRef = ref(null);

const form = ref({
  dangerControlLevel: '',
  dangerDynamicMonitorSituation: '',
  measuresContent: '',
  completeDatePlan: '',
});
// 监听 props.formValue 变化
watch(() => props.formValue, (newVal) => {
  if (newVal) {
    form.value = {
      dangerControlLevel: newVal.dangerControlLevel || '',
      dangerDynamicMonitorSituation: newVal.dangerDynamicMonitorSituation || '',
      measuresContent: newVal.measuresContent || '',
      completeDatePlan: newVal.completeDatePlan || '',
      measuresType: newVal.measuresType || '', // 保存用于查看显示
      id: newVal.id || '',
    };
  } else {
    // 新增时重置表单
    resetForm();
  }
}, { immediate: true, deep: true });

// 重置表单
const resetForm = () => {
  form.value = {
    dangerControlLevel: '',
    dangerDynamicMonitorSituation: '',
    measuresContent: '',
    completeDatePlan: '',
    measuresType: '',
    id: '',
  };
};

// 获取字典标签的方法
const getDictLabel = (dictOptions, value) => {
  if (!value || !dictOptions || !Array.isArray(dictOptions)) return '';
  const item = dictOptions.find(item => item.value === value);
  return item ? item.label : value;
};
// 提交表单
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 构建参数
        const params = {
          planId: props.planid,
          identifyResultId: props.formValue.identifyResultId,
          dangerControlLevel: form.value.dangerControlLevel,
          dangerDynamicMonitorSituation: form.value.dangerDynamicMonitorSituation,
          measuresContent: form.value.measuresContent,
          completeDatePlan: form.value.completeDatePlan,
        };

        // 如果是编辑，添加id
        if (form.value.id) {
          params.id = form.value.id;
          delete params.identifyResultId
        }

        const apiUrl = form.value.id
          ? "/mosty-jcgl/tbDangerIdentifyControlMeasures/update"
          : "/mosty-jcgl/tbDangerIdentifyControlMeasures/save";

        await postApi(params, apiUrl);

        ElMessage.success(form.value.id ? "修改成功" : "新增成功");
        emits("changeVi", false);
        emits("getList");
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};
const handleClose = () => {
  if (!formRef.value) return;
  if (props.savebtnshow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("changeVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("changeVi", false);
  }

};

</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  color: #000000 !important;
}

.el-form {
  display: block !important;
}
</style>
