import wxCommonApi from '@/api/wxCommonApi'
import aliOssApi from '@/api/aliOssApi'
import wx from 'weixin-js-sdk'
import client from './oss'
import Common from './common'
import Vue from 'vue'

const ossHandle = {

    /**
   * 存放微信上传返回的localId
   * */
    imagesObj: {
        localId: [] // 已选择的本地图片
    },

    /**
   * oss业务参数
   * @param {Number}  limit = 9
   * @param {Obeject}  ossCof = {  endpoint: 'oss-cn-shenzhen.aliyuncs.com', bucket: 'vschool-solution', region: 'oss-cn-shenzhen.aliyuncs.com'}
   * @param {String}  filePath = '10086/TestUpload'
   * @param {Number}  sourceType = 2 eg: 0 -- 来源为相册 1 -- 来源为相机 2 二者都有
   * @param {Array} filesList
   * */
    businessParams: {
        limit: 9,
        ossCof: {
            endpoint: 'oss-cn-shenzhen.aliyuncs.com',
            bucket: 'vschool-solution',
            region: 'oss-cn-shenzhen.aliyuncs.com'
        },
        filePath: '10086/TestUpload',
        sourceType: 2
    },

    /**
   * ossClient 对象
   * */
    ossClient: null,

    /**
   *  获取微信jssdk
   *  @param {Function} callBack = [上传成功的回调]
   * */
    getWxConfig (callBack) {
        let self = this
        wxCommonApi.getWxJsdkPermission().then(res => {
            const data = res.data
            if (data.Status) {
                self.getWxConfigSucc(data.Data, callBack)
            } else {
                Vue.$vux.toast.show({
                    text: data.ResponseError.LongMessage,
                    type: 'cancel'
                })
            }
        })
            .catch(res => {})
    },

    /**
   *  获取微信jssdk, 不带token
   *  @param {Function} callBack = [上传成功的回调]
   *  @param {Object} params = [是否需要token获取ali-oss配置]
   *
   * */
    getNotTokenOfWxConfig (callBack, params = null) {
        let self = this
        wxCommonApi.getNotTokenOfWxJsdkPermission().then(res => {
            const data = res.data
            if (data.Status) {
                self.getWxConfigSucc(data.Data, callBack, params)
            } else {
                Vue.$vux.toast.show({
                    text: data.ResponseError.LongMessage,
                    type: 'cancel'
                })
            }
        })
            .catch(res => {})
    },

    /**
   * 获取微信jssdk成功
   * @param {Obeject} res 获取微信配置返回的数据
   * @param {Function} callBack = [上传成功的回调]
   * @param {Object} params = [是否需要token获取ali-oss配置]
   * */
    getWxConfigSucc (res, callBack, params) {
        var self = this
        wx.config({
            debug: false,
            appId: res.appId,
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            signature: res.signature,
            jsApiList: ['checkJsApi', 'chooseImage', 'getLocalImgData']
        })
        wx.ready(() => {
            self.getSTSToken('upload', callBack, params)
        })
    },

    /**
   * 获取STS及token
   * @param {String} paramType： upload 上传图片  delete  删除图片
   * @param {Function} callBack = [上传成功的回调]
   * @param {Object} params = [是否需要token获取ali-oss配置]
   **/
    getSTSToken (paramType, callBack, params, objectKey = '') {
        let self = this
        aliOssApi
            .getToken(params)
            .then(res => {
                let data = res.data
                if (data.Status) {
                    let ossParams = {
                        accessKeyId: data.Data.AccessKeyId,
                        accessKeySecret: data.Data.AccessKeySecret,
                        stsToken: data.Data.SecurityToken,
                        endpoint: self.businessParams.ossCof.endpoint,
                        bucket: self.businessParams.ossCof.bucket,
                        region: self.businessParams.ossCof.region
                    }
                    self.ossClient = client(ossParams)
                    // 实例化ossClient之后 如果是上传图片则选择图片
                    if (paramType === 'upload') {
                        self.handleChooseImage(callBack)
                    } else if (paramType === 'delete') {
                        self.deleteImage(callBack, objectKey)
                    }
                } else {
                    Vue.$vux.toast.show({
                        text: data.ResponseError.LongMessage,
                        type: 'cancel'
                    })
                }
            })
            .catch(err => {
                console.log(err)
            })
    },

    /**
   *  选择图片
   *  @param {Function} callBack = [上传成功的回调]
   * */
    handleChooseImage (callBack) {
        let self = this
        let sourceType = []
        switch (self.businessParams.sourceType) {
        case 0:
            sourceType = ['album']
            break
        case 1:
            sourceType = ['camera']
            break
        default:
            sourceType = ['album', 'camera']
            break
        }
        wx.chooseImage({
            count: self.businessParams.limit, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
            success (res) {
                self.imagesObj.localId = res.localIds
                Vue.$vux.loading.show({
                    text: '上传中'
                })
                self.uploadImage(callBack)
            }
        })
    },

    /**
   * 上传 图片
   * @param {Function} callBack = [上传成功的回调]
   *
   * */
    uploadImage (callBack) {
        let self = this
        if (self.imagesObj.localId.length === 0) {
            Vue.$vux.toast.show({
                text: '请选择图片',
                type: 'warn'
            })
            return
        }
        let i = 0,
            len = self.imagesObj.localId.length

        function upload () {
            wx.getLocalImgData({
                localId: self.imagesObj.localId[i],
                success (res) {
                    let localData = res.localData // localData是图片的base64数据，可以用img标签显示
                    if (localData.indexOf('data:image') != 0) {
                        // 判断是否有这样的头部
                        localData = 'data:image/jpeg;base64,' + localData
                    }
                    localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg')
                    // 第一个替换的是换行符，第二个替换的是图片类型，因为在IOS机上测试时看到它的图片类型时jgp，
                    // 不知道是什么格式的图片，为了兼容其他设备就把它转为jpeg
                    let fileObj = self.dataURLtoFile(localData, '图片')
                    let backslash = fileObj.type.lastIndexOf('/')
                    let suffix = `.${fileObj.type.substr(backslash + 1)}`
                    let size = fileObj.size
                    let fileName = `wx_file_${self.randomNum(10)}`
                    let date = Common.formatDate(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())
                        .replace(/\-/g, '')
                    let uid = new Date().getTime()
                    let storeAs = `${self.businessParams.filePath}/${date}/${fileName}_${uid}${suffix}`
                    self.ossClient
                        .multipartUpload(storeAs, fileObj)
                        .then(result => {
                            if (result.res && result.res.status === 200) {
                                let obj = {
                                    objectKey: result.name,
                                    filename: fileName,
                                    filesize: size,
                                    filesuffix: suffix,
                                    fileUrl: `/${result.name}`
                                }
                                callBack(obj)
                            } else {
                                Vue.$vux.toast.show({
                                    text: '上传失败',
                                    type: 'warn'
                                })
                            }
                        })
                        .catch(() => {})
                    i++
                    if (i < len) {
                        upload()
                    } else {
                        Vue.$vux.loading.hide()
                    }
                },
                fail (res) {
                    Vue.$vux.toast.show({
                        text: JSON.stringify(res),
                        type: 'cancel'
                    })
                }
            })
        }
        upload()
    },
    /**
   * base64转file对象
   * @param {String} dataurl = [base64URL]
   * @param {String} filename = [图片名称]
   * */
    dataURLtoFile (dataurl, filename) {
        try {
            // eslint-disable-next-line one-var
            let arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], filename, {
                type: mime
            })
        } catch (e) {
            // TODO handle the exception
        }
    },

    /**
   *  删除图片
   *  @param {Function} callback = [删除成功回调]
   *  @param {String} objectKey = [图片的object-key]
   *  @param {Object} params = [是否需要token获取ali-oss配置]
   *  如果有ObjectKey 则请求删除 或者直接删除
   * */
    handleDelete (callback, objectKey, params = null) {
        let self = this
        objectKey ? self.getSTSToken('delete', callback, params, objectKey) : self.deleteImage(callback)
    },

    /**
   *  删除图片
   *  @param {Function} callBack = [删除成功 的回调]
   *  @param {String} objectKey = [图片文件的objectKey]
   *
   * */
    deleteImage (callBack, objectKey) {
        let self = this
        if (objectKey) {
            self.ossClient
                .delete(objectKey)
                .then(result => {
                    console.log(result)
                    if (result.res.status === 204) {
                        Vue.$vux.toast.show({
                            text: '删除成功',
                            type: 'success'
                        })
                        callBack()
                    }
                })
                .catch(err => {
                    console.log(err)
                })
        } else {
            callBack()
        }
    },

    /**
   * 获取指定位数的随机数
   * @param {Number} n = [随机数的位数]
   * */
    randomNum (n) {
        var rnd = ''
        for (var i = 0; i < n; i++) {
            rnd += Math.floor(Math.random() * 10)
        }
        return rnd
    }

}

export default ossHandle
