import toast from '@/utils/tool/toast/index';
export default {

    methods:{

        openSubmitLoading(value){
            this.submitStatus = true;
            clearTimeout(this.submitTimeUse);
            this.submitTimeUse = setTimeout(()=>{
                toast.loading(value || '提交中');
            },300);
        },

        closeSubmitLoading(value,type='fail'){
            this.submitStatus = false;
            clearTimeout(this.submitTimeUse);
            toast.hideLoading();
            value && toast[type](value);
        },

        // 上传所有图片
        uploadImageAll(imageKeys){
            let uploadImages = [];
            for (let key in imageKeys) {
                if (imageKeys.hasOwnProperty(key)) {
                    if (typeof imageKeys[key] ==='string') { // @ts-ignore
                        imageKeys[key] = [imageKeys[key]];
                    }
                    uploadImages.push(...imageKeys[key].map((item)=> this.uploadImage(item,key)));
                }
            }

            return new Promise(function (resolve,reject){

                Promise.all(uploadImages).then((data)=>{
                    let imageKeyObject = {};
                    data.map((item)=>{
                        if (imageKeyObject[item.key] === undefined) {
                            imageKeyObject[item.key] = [item.value];
                        } else {
                            imageKeyObject[item.key].push(item.value);
                        }
                    });

                    for (let key in imageKeyObject) {
                        if (imageKeyObject.hasOwnProperty(key)) {
                            // @ts-ignore
                            imageKeyObject[key] = imageKeyObject[key].join(',');
                        }
                    }

                    resolve(imageKeyObject);

                }).catch(reject);
            });
        },

        uploadImage(url,key){

            return new Promise((resolve,reject)=>{

                if (this.imageCache[url]) return resolve({
                    value:this.imageCache[url],
                    key
                });

                this.$request({
                    url:'common/upload',
                    filePath:url,
                    name:'file',
                    token:true
                }).then((data)=>{
                    if (data.isSuccess) {
                        // 获取路径
                        let path = data.data.url;
                        // 植入缓存
                        this.imageCache[url] = path;
                        resolve({
                            value:path,
                            key
                        });
                    } else {
                        reject();
                    }
                }).catch(reject);

            });

        },
    },

    created(){
        this.imageCache = {};
    }

}