import fileApi from '@/api/fileApi';
import { compress } from "./imgCompress"
import { isSupportHtml5Plus } from '@/utils/platform'

class Uploader {
    constructor({
        isCompress=false,
        type="image",
        minCompressSize=1 // 当isCompress：true，并且超出指定大小时进行压缩
    }) {
        this.isCompress = isCompress
        this.type = type
        this.minCompressSize = minCompressSize
    }

    upload(file, data) {
        if(this.type === "image") {
            if(isSupportHtml5Plus) {
                this.plusUpload(file)
            } else {
                this.webUpload(file, data)
            }
        }
    }

    webUpload(file, data) {
        if(file.file){
            this.postFile(file, data)
        }else {
            file.forEach((v, i)=>{
                if(i==0){
                    this.postFile(v, data)
                } else {
                    setTimeout(()=>{
                        this.postFile(v, data)
                    }, 200)
                }
            })
        }
    }

    plusUpload(path) {
        return new Promise((resolve, reject) => {
            window.plus.io.resolveLocalFileSystemURL(path, entry => {
                entry.file(file => {
                    const reader = new window.plus.io.FileReader()
                    // 读取base64
                    reader.readAsDataURL(file)
                    reader.onloadend = function(e) {
                        file.close()
                        entry.remove()
                        
                        task.start();
                    }
                })
            })
    
            var task = window.plus.uploader.createUpload(fileApi.upload_stream_path, {
                        method: "POST"
                    },
                    function(t, status) {
                        if (status == 200) {
                            var res = JSON.parse(t.responseText)
                            resolve(res, status)
    
                        } else {
                            console.error(`文件上传失败(${status}): ${t.responseText}`)
                            reject(t, status)
                        }
                    }
                );
            task.addFile(path, { key: "file" })
        })
    }

    async postFile(item, data=[]) {
        var formData = new FormData();
        data.forEach((o)=>{
            Object.keys(o).forEach((k) => {
                formData.append(k, o[k]);
            })
        })
        if(this.isCompress){
            let file = await compress(item)
            formData.append("file", file);
        } else {
            formData.append("file", item.file)
        }
        
        return fileApi.uploadStream(formData)
    }

    capture() {
        var cmr = window.plus.camera.getCamera();
        var res = cmr.supportedImageResolutions[0];
        var fmt = cmr.supportedImageFormats[0];
        cmr.captureImage( function( path ){
                window.plus.io.resolveLocalFileSystemURL(path, function(entry) {
                    var imgSrc = entry.toLocalURL() + "?version=" + new Date().getTime(); //拿到图片路径                        
                    var dst = "_downloads/" + vm.getUid() + "."+path.split(".").reverse()[0]; //设置压缩后图片的路径 
                    compress({
                        file: imgSrc,
                        dst: dst
                    }).then(function(target) {
                        this.upload(target);
                    });
                    
                }, function(e) {
                    console.log("读取拍照文件错误：" + e.message);
                });
            },
            function( error ) {
               console.error(error)
            },
            {resolution:res,format:fmt}
        );
        return false
    }
    
}