import {Message} from 'element-ui';
import {$axios} from '@/axios'
import SparkMD5 from "spark-md5";
import {storage} from "@/utils/storage";
import AliOSS from "ali-oss";

// import AWS from 'aws-sdk' // 该库较大，谨慎使用

/**
 * 获取当前相对路径
 */
export function curRelativePath() {
    const cur_url = window.location.href;
    let start_index = cur_url.indexOf('/', 8);
    let result_url = cur_url.substring(start_index, cur_url.length);
    if (result_url.charAt(1) === '#') {
        result_url = result_url.substring(2, result_url.length);
    }
    return result_url;
}

/**
 * 是否是外链
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path)
}


/**
 * 去掉http部分
 */
export function linkName(link) {
    return link.replace(/http(s)?:\/\//, '');
}

/**
 * 完整链接
 */
export function wholeLink(link) {
    return link.startsWith("http") ? link : "http://" + link;
}

/**
 * 格式化查询条件，用于列表查询条件
 */
export function formatListQuery(listQuery) {
    const newQuery = {};
    Object.keys(listQuery).forEach(key => {
        if (listQuery[key]) {
            if (listQuery[key] instanceof Array) {
                if (listQuery[key].length !== 0) {
                    newQuery[key] = listQuery[key].join(',')
                }
            } else {
                newQuery[key] = listQuery[key]
            }
        }
    });
    return newQuery;
}

/**
 * 把路由的查询条件映射到listQuery
 */
export function parseListQuery(query, listQuery) {
    if (query) {
        Object.keys(query).forEach(key => {
            // eslint-disable-next-line no-console
            if (listQuery[key]) {
                if (listQuery[key].constructor === Array) {
                    listQuery[key] = query[key].split(',').map(v => parseInt(v));
                } else if (listQuery[key].constructor === Number) {
                    listQuery[key] = parseInt(query[key]);
                } else {
                    listQuery[key] = query[key];
                }
            } else {
                listQuery[key] = query[key];
            }
        });
    }
}

/**
 * 图片大小是否在2Mb内
 */
export function checkPicSize(file) {
    const overSize = file.size / 1024 / 1024 > 2;
    if (overSize) {
        Message.error('图片大小不能超过2Mb')
    }
    return overSize;
}

/**
 * 附件大小是否在5Mb内
 */
export function checkAttachmentSize(file) {
    const overSize = file.size / 1024 / 1024 > 5;
    if (overSize) {
        Message.error('附件大小不能超过2Mb')
    }
    return overSize;
}

/**
 * 下载文件
 * @param downloadFileUrl 下载文件地址
 * @param fileName 下载显示文件名
 */
export function downloadFile(downloadFileUrl, fileName) {
    return new Promise((resolve, reject) => {
        $axios.get(downloadFileUrl, {
            timeout: -1,
            responseType: 'blob', //重要
        }, true).then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            resolve();
        }).catch(error => reject(error));
    })
}

export function downloadImage(downloadFileUrl, fileName) {
    let image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute("crossOrigin", "anonymous");
    image.onload = function () {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = fileName || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
    };
    image.src = downloadFileUrl;
}


/**
 * 计算文件的md5
 * @param file
 * @returns {Promise<unknown>}
 */
const fileMD5 = (file) => {
    return new Promise((resolve) => {
        let fileReader = new FileReader();
        let spark = new SparkMD5(); // 创建md5（基于SparkMD5）
        if (file.size > 1024 * 1024 * 10) {
            let data = file.slice(0, 1024 * 1024 * 10); //将文件进行分块 file.slice(start,length)
            fileReader.readAsBinaryString(data); //将文件读取为二进制码
        } else {
            fileReader.readAsBinaryString(file);
        }

        fileReader.onload = (e) => {
            spark.appendBinary(e.target.result);
            let md5 = spark.end();
            resolve(md5);
        };
    })
}

/**
 *  POST multipart/form-data 格式上传文件
 * @param url 上传地址
 * @param file 上传文件
 * @returns {Promise<AxiosResponse<any>>} 请求响应
 */
export const upload = (url, file) => {
    return new Promise(resolve => {
        fileMD5(file).then(md5 => {
            $axios.upload(url, file, md5).then(data => {
                resolve(data);
            })
        })
    })
};

/**
 * POST json参数 转 formData
 * @param data json参数
 * @returns {FormData} formData对象
 */
export const toFromData = (data) => {
    let formData = new FormData();
    for (let key in data) {
        if (data.hasOwnProperty(key)) {
            formData.append(key, data[key])
        }
    }
    return formData;
}

/**
 * 上传文件至OSS
 * @param stsUrl 获取sts信息的地址
 * @param file 需要上传的文件
 * @returns {Promise} 文件地址
 */
export const OSSFileUpload = (stsUrl, file) => {
    if (!file || !stsUrl) {
        return Promise.reject();
    }
    return fileMD5(file).then(filename => {
        return new Promise(resolve => {
                let stsInfo = storage.getData("sts");

                // 过期时间大于三分钟时直接读取缓存的授权信息
                if (stsInfo && new Date(stsInfo.expiration).getTime() - 3 * 60 * 1000 > Date.now()) {
                    stsInfo.filename = filename;
                    resolve(stsInfo)
                } else {
                    $axios.get(stsUrl).then(stsInfo => {
                        storage.setData("sts", stsInfo);
                        stsInfo.filename = filename;
                        resolve(stsInfo);
                    }).catch((e) => {
                        console.log(e)
                    });
                }
            }
        );
    }).then((stsInfo) => {
        /**
         * stsInfo:{
         *   accessKeyId: "STS.NTvnQ4yQsU7SYUZTjB63nCUqb"
         *   accessKeySecret: "Hr5qSNKULeQvnaWz6vBWjbyzrfo9zEoqveWfupkNh1s2"
         *   bucketName: "flyhigh"
         *   endpoint: "oss-cn-hangzhou.aliyuncs.com"
         *   expiration: "2022-02-22T07:59:31Z"
         *   filename: "171851bcb38a6b752986ab6f06ca7628人工智能体系架构.jpg"
         *   pathName: "app"
         *   region: "cn-hangzhou"
         *   securityToken: "CAIS5QF1q6Ft5B2yfSjIr5fDJeuAlI5S4vW4W3PrsGoXOrxCrJDagDz2IHxKfHJgCeofs/40mGtV7Pkclqp6U4cdwoVphlE3vPpt6gqET9frma7ctM4p6vCMHWyUFGSIvqv7aPn4S9XwY+qkb0u++AZ43br9c0fJPTXnS+rr76RqddMKRAK1QCNbDdNNXGtYpdQdKGHaOITGUHeooBKJUxQ35lYs0z0ksvXhnJzH0HeE0g2mkN1yjp/qP52pY/NrOJpCSNqv1IR0DPGdjnYLu0gQrfos1/AfpG2Y4Mv2CkFJ86h0w219dSQEGoABryhbuBDUBtiuDc39Erxlqwpg/aVPKqG3yxB+Uqdt5gw8dalvVEG0TlbUmNedS4Hx1I5dKL7Ajn3+yVCh6Viuce2BPlY+bHVMpjJ6HsB9S9ydibvnmk2O/yOGxPtppGpzvTcol80Um65wxqI6AvJFRrmEOgvCgK5gvo0XziE+JmM="
         * }
         */
        return new Promise((resolve) => {
            let fullName = stsInfo.pathName + '/' + stsInfo.filename;
            new AliOSS({
                region: stsInfo.region,
                endpoint: stsInfo.endpoint,
                // secure:true,
                accessKeyId: stsInfo.accessKeyId,
                accessKeySecret: stsInfo.accessKeySecret,
                bucket: stsInfo.bucketName,
                stsToken: stsInfo.securityToken,
            }).put(fullName, file, {
                mime: file.type
            }).then((result) => {
                resolve(result.res.requestUrls[0])
            });
        });
    })
}

/**
 * @param file 需要上传的文件
 * @param stsUrl 获取sts信息的地址
 * @returns {Promise} 文件地址
 */
export const AWSFileUpload = (file, stsUrl) => {
    if (!file || !stsUrl) {
        return new Promise((resolve, reject) => {
            reject()
        })
    }
    return fileMD5(file).then(filename => {
        return new Promise(resolve => {
                let stsInfo = storage.getData("sts");

                // 过期时间大于三分钟时直接读取缓存的授权信息
                if (stsInfo && new Date(stsInfo.expiration).getTime() - 3 * 60 * 1000 > Date.now()) {
                    resolve(stsInfo)
                } else {
                    $axios.get(stsUrl).then(data => {
                        storage.setData("sts", data);
                        resolve(data);
                    }).catch((e) => {
                        console.log(e)
                    });
                }
            }
        ).then((stsInfo) => {
            /**
             * stsInfo:{
             *   accessKeyId: "STS.NSrSpja5mJZeGxPRU2NtWj59x"
             *   accessKeySecret: "9f83946dbKpsC4Rgnntfe64FafXZ6iMjGvK832TtEdh7"
             *   bucketName: "vtrt-vrlive"
             *   endpoint: "http://oss-cn-beijing.aliyuncs.com"
             *   expiration: "2020-04-17T15:07:31Z"
             *   pathName: "t-t-0"
             *   region: "oss-cn-beijing"
             *   securityToken: ""CAISoQJ1q6Ft5B2yfSjIr5DHGMrejOpM/ZiORV7htlVnQvt7hfCSmjz2IHFLeHZoBesbtP0+nW5W7fsZlqxvDoMAHRQ96hvdHtIFnzm6aq/t5uZehN5t0e+zewW6Dxr8w7WMAYHQR8/cffGAck3NkjQJr5LxaTSlWS7TU/iOkoU1QdkLeQO6YDFaZrJRPRAwkNIGEnHTOP2xSEuI5FDdF011oAFxpHpi4KCkuK2m5wHZkUfxx51cxfP4KYP2aNJ3btUtEYWrwPZqM7Tb1C9O5l9Wsbsz1OsG20+e7ozNUgEPs0nZYrqIroM3FmIjOPhmQZwjhePniPh1ttbUk4nK0BtXNYlXKX+OG9z/mJefRbnwZ49nK+2mYG6m3t2RJj1rO7nr3LxwGoABlBJnCdLzVBX+eJQIxsoSTCdO5tby90xmeKYIZc7vbH3TmS9L70J15Lwkw3h+0SP79GEBJUBrfLWuiLfiY1QOFLyd7VCghkuSV6Jvp1MOck80CqLH/fEi6nBP0sk/xHdyIIcj5Mn7EAB0K4KYGZKYjHy5HSkM1kFp332hpYN97jE="
             * }
             */
            return new Promise((resolve) => {
                let param = {
                    region: stsInfo.region,
                    credentials: new aws.Credentials(stsInfo.accessKeyId, stsInfo.accessKeySecret, stsInfo.securityToken),
                };
                new AWS.S3(param).upload({
                    Bucket: stsInfo.bucketName,
                    Key: stsInfo.pathName + '/' + filename,
                    ContentType: file.type,
                    Body: file,
                    "Access-Control-Allow-Credentials": "*",
                    ACL: "public-read"
                }).on("httpUploadProgress", function () {

                }).send(async err => {
                    if (!err) {
                        resolve(fullName); // stsInfo.hostname +
                    } else {
                        console.log(err);
                    }
                });
            });
        });
    })
}

/**
 * 获取文件内容
 * @param url 文件地址
 * @returns {Promise} 文件内容
 */
export const getFileContent = (url) => {
    return new Promise((resolve, reject) => {
            if (url) {
                $axios.get(url).then(response => {
                    resolve(response.data);
                }).catch((error) => {
                    reject(error)
                    console.log(error);
                });
            } else {
                reject("url不能为空")
            }
        }
    );
}

/**
 * 获取文件Blob格式
 * @param url 文件地址
 * @returns {Promise} 文件Blob格式
 */
export const getFileBlob = (url) => {
    return new Promise(resolve => {
            $axios.get(url, {responseType: 'blob'}).then(response => {
                resolve(response.data);
            }).catch((error) => {
                console.log(error);
            });
        }
    );
}
