<template>
    <el-dialog
        v-model="dialogVisible"
        :title="`导入${parameter.title}`"
        :destroy-on-close="true"
        width="580px"
        draggable
    >
        <el-form class="drawer-multiColumn-form" style="margin-top: 10px" label-width="100px">
            <el-form-item label="文件上传：">
                <el-upload
                    action="#"
                    class="upload"
                    drag
                    :http-request="uploadZip"
                    accept=".zip"
                    :show-file-list="false"
                >
                    <slot name="empty">
                        <el-icon class="el-icon--upload">
                            <upload-filled />
                        </el-icon>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                    </slot>
                    <template #tip>
                        <slot name="tip">
                            <div class="el-upload__tip">请上传 .zip 标准格式文件</div>
                        </slot>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup lang="ts" name="ImportZip">
import { ref } from 'vue'
import { ElMessage, UploadRequestOptions } from 'element-plus'

export interface ZipParameterProps {
    title: string // 标题
    patternId?: string // 模式ID
    importApi?: (params: any) => Promise<any> // 批量导入的Api
}
// dialog状态
const dialogVisible = ref(false)
// 父组件传过来的参数
const parameter = ref<ZipParameterProps>({
    title: ''
})
const emit = defineEmits<{
    (e: 'result', data: boolean): void
}>()
// 接收父组件参数
const acceptParams = (params: ZipParameterProps) => {
    parameter.value = { ...parameter.value, ...params }
    dialogVisible.value = true
}

// 文件上传
const uploadZip = async (param: UploadRequestOptions) => {
    let zipFormData = new FormData()
    zipFormData.append('file', param.file)
    if (parameter.value.patternId) {
        zipFormData.append('patternId', parameter.value.patternId)
    }
    await parameter.value.importApi!(zipFormData).then(res => handleImportResponse(res))
}

const handleImportResponse = (res: any) => {
    if (res.code === 'A0000') {
        ElMessage.success('导入成功')
    } else {
        ElMessage.error(res.message)
    }
    dialogVisible.value = false
    emit('result', res.data)
}

defineExpose({
    acceptParams
})
</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
