import uploader from '@/plugins/uploader/index.js'
import { RUN, ERROR } from "@/common/log.js"

const getNetworkType = function() {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success (res) {
				resolve(res.networkType)
			},
			fail (res) {
				resolve('获取失败')
			} 
		})
	})
}

export default {
    /**
     * 执行任务队列
     */
    async uploadImageTask(that) {
        if (that.uploadStatus === 2) return

        that.$u.vuex('uploadStatus', 2)
        const uploadTask = JSON.parse(JSON.stringify(that.uploadTask)).reverse()
        const networkType = await getNetworkType()
        const options = {
            files: uploadTask.slice(0,5), // 必填 临时文件路径 格式: [{path: "图片地址"}]
            load: false, //（默认 true 说明：本接口是否提示加载动画）
            onEachUpdate: res => {
                console.log("上传成功返回：",res);

                const log = {
                    ...res,
                    mobile: that.vuex_user.mobile,
                    networkType: networkType
                }
                delete log.files
                RUN('upload_photo_success', log)
            },
            onProgressUpdate: res => {
                //console.log("上传进度返回：",res);
            }
        }

        uploader.qnFileUpload(options).then(res => {
            const newSuccess = that.uploadSuccess + res.length
            that.$u.vuex('uploadSuccess', newSuccess)
            this.refreshTask(that, res)
        }).catch(err => {
            console.log("err", err)
            that.$u.vuex('uploadStatus', 3)
            err.mobile = that.vuex_user.mobile
            if(!err.key) err.files = uploadTask
            if(!err.orderNumber) err.orderNumber = uploadTask[0].orderNumber
            if(!err.networkType) err.networkType = networkType
            ERROR('upload_photo_error', err)
            
            if (err.errMsg && (err.errMsg.indexOf('fail file not found') !== -1 || err.errMsg.indexOf('file doesn') !== -1)) { // 在任务中删除不存在的图片
                const newTask = uploadTask.filter(v => v.key !== err.key)
                that.$u.vuex('uploadTask', newTask)
                this.resetProgress(that)
            }
        })
    },
    refreshTask(that, result) {
        const uploadTask = JSON.parse(JSON.stringify(that.uploadTask)).reverse()
        let newTask = [] 
        uploadTask.forEach(v => {
            if (!result.includes(`/${v.key}`)) { // 删除已上传的图片
                newTask.push(v)
            }
        })
        
        that.$u.vuex('uploadStatus', 1)
        that.$u.vuex('uploadTask', newTask)
        this.resetProgress(that)
    },
    // 重置任务状态
    resetProgress(that) {
        if (that.uploadTask.length === 0) { // 上传完本地所有照片
            that.$u.vuex('uploadSuccess', 0)
            that.$u.vuex('uploadTotal', 0)
            that.$u.vuex('uploadStatus', 1)
        }
    }
}
