<template>
  <el-dialog
    v-model="visible"
    :title="type === 'add' ? '新增' : '修改'"
    :on-close="fnClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="文件名" prop="NAME">
        <el-input v-model="form.NAME" />
      </el-form-item>
      <el-form-item label="附件" prop="file">
        <layout-upload
          v-model:file-list="form.file"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
          delete-to-server
          :limit="99"
        />
      </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 { useVModels } from "@vueuse/core";
import { ref } from "vue";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import LayoutUpload from "@/components/upload/index.vue";
import { setAdd, setEdit } from "@/request/risk_statement.js";
import { setUploadImg } from "@/request/api.js";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  type: {
    type: String,
    required: true,
    default: "",
  },
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  listType: {
    type: Array,
    required: true,
    default: () => [],
  },
});
const emits = defineEmits(["update:visible", "update:form", "get-data"]);
const { visible, form } = useVModels(props, emits);
const rules = {
  NAME: [{ required: true, message: "请输入文件名", trigger: "blur" }],
  file: [{ 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);
    const resData =
      props.type === "add"
        ? await setAdd({
            ...form.value,
            TYPE: props.listType[0],
          })
        : await setEdit({
            ...form.value,
            TYPE: props.listType[0],
          });
    const formData = new FormData();
    for (let i = 0; i < form.value.file.length; i++) {
      if (form.value.file[i].raw)
        formData.append("FFILE", form.value.file[i].raw);
    }
    formData.append("FOREIGN_KEY", resData.pd.RISKWARNING_ID);
    formData.append("TYPE", props.listType[1]);
    await setUploadImg(formData);
    ElMessage.success("操作成功");
    fnClose();
    emits("get-data");
  },
  { atBegin: true }
);
</script>

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