<template>
    <el-dialog v-model="value" title="上传体检报告" :close-on-click-modal="false" width="840px" v-if="value">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100">
            <el-form-item label="绑定师傅:" prop="userId">
                <user-select
                    btn-text="选择师傅"
                    type="primary"
                    v-model="form.userId"
                    :userVo="form.userVo"
                    v-model:userMobile="form.mobile"
                    :api="apiStaffUnUploadPdfList"
                    binding="staff"
                />
            </el-form-item>
            <el-form-item label="体检报告:" prop="files">
                <uploadDialog v-model:files="fileUploadList" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="toggle(false)">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { useToggle } from '@vueuse/core'
import { omit } from 'lodash-es'
import type { FormInstance, UploadFile } from 'element-plus'
import UserSelect from '@/components/user-select/index.vue'
import uploadDialog from './uploadDialog.vue'
import { apiStaffPhysical, apiStaffUnUploadPdfList, apiUploadFile } from '@/api/master_worker/index'
import feedback from '@/utils/feedback'
import { validateFiles } from '@/utils/validate'

const formRef = ref<FormInstance>()
const fileUploadList = ref({
    pdf: [],
    report: []
})
const form = reactive({
    userId: null,
    userVo: {},
    mobile: null,
    files: {
        pdf: [],
        report: []
    }
})
const rules = reactive({
    userId: [{ required: true, message: '请选择师傅', trigger: [] }],
    files: [{ validator: (...args) => validateFiles(args, unref(fileUploadList)), trigger: [] }]
})
const [value, toggle] = useToggle()

const openDialog = () => {
    toggle(true)
}
/**师傅提交体检报告 */
const handleConfirm = () => {
    try {
        formRef.value?.validate(async valid => {
            if (!valid) return
            await handleUpload()
            const files = omit(form.files, ['avatar', 'idCard'])
            const data = {
                staffId: form.userId,
                files
            }
            await apiStaffPhysical(data)
            feedback.msgSuccess('提交成功')
            toggle(false)
        })
    } catch (error) {}
}
/**上传所有文件 */
const handleUpload = () => {
    return new Promise(async (resolve, reject) => {
        if (!unref(fileUploadList) || !Object.keys(unref(fileUploadList)).length) {
            resolve([])
            return
        }

        const fileTypes = Object.keys(unref(fileUploadList))
        try {
            for (const type of fileTypes) {
                await loopUploadFile(unref(fileUploadList)[type], type)
            }
            resolve(form.files)
        } catch (error) {
            reject(error)
        }
    })
}
/**循环上传图片 */
async function loopUploadFile(files: UploadFile[], type: string) {
    if (files.length > 0) {
        for (let i = 0; i < files.length; i++) {
            try {
                const { path } = await uploadFile(files[i])
                form.files[type][i] = path
            } catch (error) {}
        }
    } else {
        form.files[type] = []
    }
}
/**上传图片接口 */
function uploadFile(file: UploadFile) {
    return new Promise(async (resolve, reject) => {
        try {
            let formData = new FormData()
            formData.append('file', file.raw!)
            const data = await apiUploadFile(formData)
            resolve(data)
        } catch (error) {
            reject(error)
        }
    })
}

defineExpose({
    openDialog
})
</script>
<style scoped></style>
