<script setup name="upLoadReplayDialog">
import { watch, ref, getCurrentInstance } from 'vue'
import store from '@/store'
import {
  fileFormatVerification,
  handleFileSuccess,
  handleFilePreview,
  handleFileError,
  changFilesParam,
  handleFileExceed
} from '@/utils/uploadAction.js'
import { uploadReplay } from '@/http/apis/performanceEvaluation/inquirySheetManage'

const uploadUrl = store.dictStore.uploadUrl,
  { proxy } = getCurrentInstance(),
  props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    data: Object
  }),
  emits = defineEmits(['close']),
  form = ref({
    replyForm: []
  }),
  formRef = ref(),
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        const postData = {
          formId: props.data?.id,
          replyForm: form.value.replyForm?.length && JSON.stringify(changFilesParam(form.value.replyForm)) || undefined
        }
        await uploadReplay({
          ...postData
        })
        proxy.$message.success('提交成功！')
        emits('close', true)
      }
    })
  }
watch(
  () => props.visible,
  async val => {
    if (val) {
      form.value.replyForm = []
    }
  }
)

</script>
<template>
  <el-dialog
    :model-value="visible"
    title="上传回复单"
    width="600px"
    destroy-on-close
    @close="emits('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="120px"
      label-suffix=":"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="回复单" prop="replyForm" :rules="[{ required: true, message: '请上传文件', trigger: 'blur' }]">
            <el-upload
              v-model:file-list="form.replyForm"
              class="w-full"
              :action="uploadUrl"
              :limit="1"
              :on-exceed="handleFileExceed"
              :on-success="res => handleFileSuccess(res, form.replyForm, true)"
              :on-error="handleFileError"
              :on-preview="handleFilePreview"
              :before-upload="
                file =>
                  fileFormatVerification(file, {
                    types: ['pdf', 'png','jpeg','jpg']
                  })
              "
              accept=".pdf,.png,.jpeg"
            >
              <el-button type="primary">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持.png、.jpg、.jpeg、.pdf</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit(formRef)">
        提交
      </el-button>
      <el-button @click="emits('close')">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>
