<template>
  <el-dialog
    v-model="visible"
    :title="type === 'edit' ? '修改' : '新增'"
    :before-close="fnClose"
  >
    <el-form ref="formRef" :rules="rules" :model="form" label-width="150px">
      <el-form-item label="部门" prop="DEPARTMENT_ID">
        <layout-department v-model="form.DEPARTMENT_ID" />
      </el-form-item>
      <el-form-item label="风险点（单元）名称" prop="RISKUNITNAME">
        <el-input v-model="form.RISKUNITNAME" />
      </el-form-item>
    </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 } from "vue";
import { useVModels } from "@vueuse/core";
import LayoutDepartment from "@/components/department/index.vue";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import { setRiskPointAdd, setRiskPointEdit } from "@/request/risk_control.js";

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 = {
  RISKUNITNAME: [
    { required: true, message: "风险点（单元）不能为空", trigger: "blur" },
  ],
  DEPARTMENT_ID: [
    { required: true, message: "管控部门不能为空", trigger: "change" },
  ],
};
const formRef = ref(null);
const fnClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    props.type === "add"
      ? await setRiskPointAdd({ ...form.value })
      : await setRiskPointEdit({ ...form.value });
    ElMessage.success("操作成功");
    fnClose();
    emits("get-data");
  },
  { atBegin: true }
);
</script>

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