import { ref, unref } from 'vue'
import { formatFileSize, navigateTo, toast, uploadFile } from '@/utils/util'
import { previewFile } from '@/utils/file'
import { IMAGE_LIMIT_SIZE } from '@/config/index'

export function useUploadValidate() {
    const fileList = ref<any>({
        moduleWhole: [], //模块整体
        fault: [], //故障图片
        beforeRepair: [], //维修前图片
        inRepairing: [], //维修中、后图片
        scrapImg: [], //报废图片
        inspectionFinish: [], //巡检完工拍照确认
        repairImage: [], //维修单图片
        picture: [], // 客户上报图片
        scrapMarkPicture: [] //报废标图片
    })

    const uploadFileList = ref({
        moduleWhole: [], //模块整体
        fault: [], //故障图片
        beforeRepair: [], //维修前图片
        inRepairing: [], //维修中、后图片
        scrapImg: [], //报废图片
        inspectionFinish: [], //巡检完工拍照确认
        repairImage: [], //维修单图片
        scrapMarkPicture: [] //报废标图片
    })
    const btnDisabled = ref(false)

    /**上传图片前校验 */
    const beforeRead = event => {
        console.log(event)

        const { file, name } = event
        return new Promise(resolve => {
            const uploadLen = unref(fileList)[name].length + file.length
            if (uploadLen > 9) {
                toast('最多上传9张图片')
                return resolve(false)
            }

            for (let i = 0; i < file.length; i++) {
                if (!isImage(file[i].url)) {
                    toast('请上传jpg，png，jpeg格式的图片')
                    return resolve(false)
                }
                if (file[i].size > IMAGE_LIMIT_SIZE) {
                    toast(`请上传小于${formatFileSize(IMAGE_LIMIT_SIZE)}的图片`)
                    return resolve(false)
                }
            }
            resolve(true)
        })
    }
    /**上传图片后 */
    const afterRead = async event => {
        const flag = await beforeRead(event)
        if (!flag) return
        const { file, name } = event
        fileList.value[name].push(...file)
    }
    /**删除图片 */
    const handleDelPic = (index: number) => {
        fileList.value['report'].splice(index, 1)
    }
    /**删除图片 */
    const deletePic = event => {
        const { index, name } = event
        fileList.value[name].splice(index, 1)
    }
    /**上传pdf前格式校验 */
    const beforeReadPdf = event => {
        return new Promise(resolve => {
            const { file } = event
            if (!isImage(file.name, ['pdf'])) {
                toast('请上传pdf格式文件')
                return resolve(false)
            }
            resolve(true)
        })
    }
    /**上传pdf */
    const afterReadPdf = async event => {
        const flag = await beforeReadPdf(event)
        if (!flag) return
        // toast('上传中')
        try {
            const { url, name } = event.file
            fileList.value['pdf'] = []
            fileList.value['pdf'].push({ url, name })

            // const { path } = await uploadFile(url, 'file')
            // fileList1.value = []
            // fileList1.value.push({ url })
            // toast('上传成功')
        } catch (error) {
            // toast('上传失败，请重新上传')
        }
    }
    /**预览体检图片 */
    const handlePreviewImage = (index: number) => {
        const urls = unref(fileList)['report'].map(item => item.url)
        uni.previewImage({
            urls,
            current: index
        })
    }
    /**删除pdf */
    const handleClosePdf = () => {
        fileList.value['pdf'] = []
    }
    /**选择头像 */
    const chooseAvatar = (e: any) => {
        if (e.detail.avatarUrl) {
            fileList.value['avatar'] = []
            fileList.value['avatar'].push({ url: e.detail.avatarUrl })
        }
    }
    /** 获取图片后缀 */
    function getFileType(name: string) {
        const suffix = name.match(/\.([^.]+)$/)[1]
        return suffix
    }
    /**是否符合图片格式 */
    function isImage(url: string, suffixArr = ['jpg', 'png', 'jpeg']) {
        const suffix = getFileType(url)
        return suffixArr.includes(suffix)
    }

    function handleUploadFile(callback, filesList?: any) {
        Promise.all([...uploadFilePromise(filesList)]).then(async result => {
            if (result.length > 0 && result.includes('上传失败'))
                return toast('图片上传失败，请联系客服')
            uni.hideLoading()
            uni.showLoading({
                title: '提交中...'
            })
            btnDisabled.value = true
            callback(uploadFileList)
        })
    }

    /**上传图片 */
    function uploadFilePromise(_fileMap?: any) {
        const promiseFun = []
        const _files = _fileMap ? _fileMap : unref(fileList)
        Object.keys(_files).forEach(key => {
            const files = _files[key]
            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i]
                    if (file.url.includes('tmp') || file.url.includes('wxfile')) {
                        uni.showLoading({
                            title: '上传中'
                        })
                        promiseFun.push(
                            new Promise(async (resolve, reject) => {
                                try {
                                    const fileType = key === 'pdf' ? 'file' : 'image'
                                    const { path } = await uploadFile(file.url, fileType)
                                    files[i] = path
                                    resolve('上传成功')
                                } catch (error) {
                                    reject('上传失败')
                                }
                            })
                        )
                    } else {
                        files[i] = file.url
                    }
                }
                uploadFileList.value[key] = files
            } else {
                uploadFileList.value[key] = []
            }
        })
        return promiseFun
    }

    return {
        fileList,
        beforeRead,
        afterRead,
        beforeReadPdf,
        afterReadPdf,
        handleDelPic,
        deletePic,
        handlePreviewImage,
        chooseAvatar,
        handleClosePdf,
        handleUploadFile,
        btnDisabled
    }
}
