import {isEmptyUtils, isNotEmptyUtils, subString} from "@/utils/index";
import fetch from './fetch.js';

/**
 * OSS工具类
 */
// let OSS = require('ali-oss');
// 文件扩展名(图片以外的文件如果需要下载,需要在此处添加文件扩展名)
let contentTypeMap = new Map();
contentTypeMap.set("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel");

// PICA_DEV_APP.service('ossUtil', function ($rootScope, $q) {

//获取OSS客户端
let bucketName = localStorage.getItem("bucketName");
let endpoint = localStorage.getItem("endpoint");

// //上传状态
// let status = false;
//
// /**
//  * 文件上传状态
//  * */
// export const isUpload = () => {
//     return status;
// };

/**
 * 获取OSS客户端对象
 *
 * @return {Object} client OSS客户端对象
 * */
const doOSSAction = () => {
    //sts服务器
    // let stsUrl = localStorage.getItem("stsUrl") + "/" + localStorage.getItem("token");
    // let stsUrl = 'https://dev-api.yunqueyi.com/middle/oss/token/' + localStorage.getItem("token");
	let stsUrl = 'https://dev-api.yunqueyi.com/middle/oss/token/B1A7745D85D74EB4966125A4E0979ACE'

    return new Promise(function (resolve, reject) {
        fetch(stsUrl, {}, 'GET').then(function (result) {
            let client = null;
            if (isNotEmptyUtils(result) && result.StatusCode == "200") {
                //获取client对象
                client = new OSS.Wrapper({
                    accessKeyId: result.AccessKeyId,
                    accessKeySecret: result.AccessKeySecret,
                    stsToken: result.SecurityToken,
                    endpoint: endpoint,
                    bucket: bucketName
                });
                resolve(client);
                console.log('STS临时授权成功');
            } else {
                reject(result);
                console.error('STS临时授权失败:', result);
            }
        }).catch(function (error) {
            reject();
            console.error('STS临时授权失败:', error);
        });
    });
};

/**
 * 获取OSS上的文件路径
 *
 * @param {String} [filePath] 文件路径
 * @return {String} address 网络路径(默认有效时间半个小时)
 * */
export const downloadOSSFile = (filePath) => {
    let deferred = $q.defer();
    if (isEmptyUtils(filePath)) {
        return null;
    }
    let suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
    // return client.signatureUrl(filePath);
    //默认下载图片
    let content_type = "image/png";
    if (isNotEmptyUtils(suffix) && contentTypeMap.has(suffix)) {
        content_type = contentTypeMap.get(suffix);
    }

    doOSSAction().then(function (client) {
            let address = client.signatureUrl(filePath, {
                expires: 1800,
                response: {
                    'content-type': content_type,
                    'content-disposition': 'attachment'
                }
            });
            deferred.resolve(address);
        }
    );
    return deferred.promise;
};

/**
 * 文件重命名
 * @param {File} [file] 上传文件对象
 * @param {String} [fileName] 指定文件名
 * @param {String} [folder] 指定文件夹
 * @return {String} fileName
 * modified by Anndy Yang
 */
export const getFilePathForOSS = (file, fileName, folder) => {
    if (isEmptyUtils(file)) {
        return null;
    }

    //文件类型
    let ext = file.type;
    //后缀名
    let suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
    //若为空则从name中获取---对wps格式的文件获取不到file.type
    if (isEmptyUtils(ext)) {
        ext = suffix;
    }
    //获取当前日期对象
    let date = new Date();
    if (isEmptyUtils(fileName)) {
        //重命名后的文件名
        fileName = timeStamp(date) + "-" + subString(guid(), 8) + "." + suffix;
    }

    //文件全路径(文件路径 + 文件名) 扩展名​/年/月/日/
    let filePath = ext + "/" + date.format('yyyy/MM/dd') + "/" + (isEmptyUtils(folder) ? "" : (folder + "/")) + fileName;
    console.log(filePath);
    return filePath;
};

/**
 * oss上传
 *
 * @param {Vue} [self] vue实例
 * @param {File} [file] 上传文件对象
 * @param {String} [filePath] 文件全路径(文件路径 + 文件名)
 * @param {String} [previewId] 显示图片的元素Id
 * @param {String} [progressId] 显示上传进度的进度条id
 * @param {Object} [imageAction] 图片操作
 * @return {Promise} [dbFilePath] 存到数据库的文件路径
 * */
export const ossUpload = (self, file, filePath, previewId, progressId, imageAction) => {

    return new Promise(function (resolve, reject) {
        if (isEmptyUtils(file) || isEmptyUtils(filePath)) {
            console.error('OSS上传失败:非法参数');
            reject();
        }

        //修改状态为上传
        self.uploadStatus = true;

        doOSSAction().then(function (client) {
                //分片上传
                client.multipartUpload(filePath, file, {
                    progress: function* (p) {
                        //获取百分比进度
                        self.uploadProgress = getPercentage(p, 2);
                        if (p == 1) {
                            //修改状态为非上传
                            self.uploadStatus = false;
                        }
                        console.log('uploadProgress: ' + self.uploadProgress);
                    },
                    headers: {
                        'Access-Control-Allow-Origin': '*'
                    }
                }).then(function (r1) {
                    resolve('/' + filePath);
                    //修改状态为非上传
                    self.uploadStatus = false;
                    console.log('上传成功', r1);
                    // let address = getOSSFilePath(filePath, imageAction);
                    // //显示图片
                    // if (isNotEmptyUtils(previewId) && isNotEmptyUtils(address)) {
                    //     console.log('图片路径: ' + address);
                    //
                    //     let $img = $('<img>').attr("src", address);
                    //     let obj = $("#" + previewId);
                    //     obj.empty().append($img);
                    //     obj.css('max-width', '100%');
                    // }
                }).catch(function (err) {
                    reject(err);
                    //修改状态为非上传
                    self.uploadStatus = false;
                    console.error('OSS上传失败:', err);
                    // modalClick("提示", "上传失败！", "确定", function () {
                    //     $('#model-modify').modal('hide');
                    // }, "", null);
                });
            }
        );

    });
};

/**
 * OSS获取图片的参数模型
 *
 * @return {Object} [imageAction] 图片的参数模型
 * */
export const getImageAction = () => {
    return {
        'resize': {
            'width': null,
            'height': null
        },
        'rotate': {
            'angle': null //角度
        }
    };
};

//OSS获取图片的参数模型,转换为url路径参数
let imageActionParam = function (action) {
    //有参数为true
    let haveParamFlag = false;
    let param = [];
    if (isNotEmptyUtils(action)) {
        // 缩放
        if (isNotEmptyUtils(action.resize)) {
            let width = isNotEmptyUtils(action.resize.width) ? ("w_" + action.resize.width) : null;
            let height = isNotEmptyUtils(action.resize.height) ? ("h_" + action.resize.height) : null;
            if (isNotEmptyUtils(width) || isNotEmptyUtils(height)) {
                let resize = [];
                if (isNotEmptyUtils(width)) {
                    resize.push(width);
                }
                if (isNotEmptyUtils(height)) {
                    resize.push(height);
                }
                param.push(['resize', resize]);
                haveParamFlag = true;
            }
        }

        //旋转
        if (isNotEmptyUtils(action.rotate)) {
            if (isNotEmptyUtils(action.rotate.angle)) {
                param.push(['rotate', [action.rotate.angle]]);
                haveParamFlag = true;
            }
        }
    }

    //如果有参数
    if (haveParamFlag) {
        let ParamStr = "?x-oss-process=image";
        let paramMap = new Map(param);
        //Map的回调函数参数依次为value、key和map本身：
        paramMap.forEach(function (value, key, map) {
            ParamStr = ParamStr + '/' + key;
            for (let i = 0; i < value.length; i++) {
                ParamStr = ParamStr + ',' + value[i];
            }
        });
        return ParamStr;
    }
    return null;
};

/**
 * 获取OSS上的文件路径
 *
 * @param {String} [filePath] 文件路径
 * @param {String} [param] 参数字符串
 * @return {String} address 网络路径
 * */
export const getOSSFilePath = (filePath, param) => {
    if (isEmptyUtils(filePath)) {
        return null;
    }
    let paramStr = imageActionParam(param);
    // http://bucket.<endpoint>/object?x-oss-process=image/action,parame_value
    let str = "http://" + bucketName + "." + endpoint + "/" + filePath;
    return isNotEmptyUtils(paramStr) ? (str + paramStr) : str;
};
// });


/**
 * 获取全局唯一标识符（GUID，Globally Unique Identifier）
 * @return {String} guid
 */
const guid = () => {
    /**
     * @return {String}
     */
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};

/**
 * 获取时间戳
 * @param {Date} [date]日期对象,为空时,返回当前时间戳
 * @return {String} timeStamp时间戳 格式:yyyyMMddhhmmssS
 */
const timeStamp = (date) => {
    if (isEmptyUtils(date)) {
        return new Date().format('yyyyMMddhhmmssS');
    }

    return date.format('yyyyMMddhhmmssS');
}

/**
 * 保留precision位小数(四舍五入)后百分比显示
 * @param {Number} [input] 要四舍五入的对象
 * @param {Number} [precision] 要保留的小数位(默认2位)
 * @return {Number} 例如:98.22
 */
const getPercentage = (input, precision) => {
    if (isEmptyUtils(input)) {
        return 0;
    }
    return Number((input * 100).toFixed(isEmptyUtils(precision) ? 2 : precision));
};

/**
 * 从dataURL获取文件对象
 *
 * @param {String} [dataurl] 文件路径
 * @param {String} [filename] 参数字符串
 * @return {File} file 文件
 * */
const dataURLtoFile = (dataurl, filename) => {
    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});
};
