<script name="importProjectDialog" setup>
import { ref, getCurrentInstance, watch } from 'vue'
import { fileFormatVerification, handleFileSuccess, handleFilePreview, handleFileError } from '@/utils/uploadAction.js'
import store from '@/store'
import { annualPlanImport } from '@/http/apis/projectStoreManage/annualPlanStore'
const { proxy } = getCurrentInstance(),
  uploadUrl = store.dictStore.uploadUrl,
  props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    }
  }),
  emits = defineEmits(['close']),
  formRef = ref(),
  form = ref({}),
  rules = {
    file: [{ required: true, message: '请上传文件', trigger: 'blur' }]
  },
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        // const postData = {
        //   fileUrl: form.value.file?.map(i => i.response.data)[0].accessUrl
        // }
        await annualPlanImport(form.value.file)
        proxy.$message.success('提交成功！')
        emits('close', true)
      }
    })
  }
watch(
  () => props.visible,
  async val => {
    if (val) {
      console.log(val)
    } else {
      formRef.value.resetFields()
    }
  }
)
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="导入"
    width="600px"
    destroy-on-close
    @close="emits('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-suffix=":"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="导入文件" prop="file">
            <el-upload
              v-model:file-list="form.file"
              class="w-full"
              :action="uploadUrl"
              :limit="1"
              :on-success="res => handleFileSuccess(res, form.file, true)"
              :on-error="handleFileError"
              :on-preview="handleFilePreview"
              :before-upload="
                file =>
                  fileFormatVerification(file, {
                    types: [
                      'application/vnd.ms-excel',
                      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    ]
                  })
              "
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            >
              <el-button type="primary">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持.xlsx、.xls</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>
