import { getViewUrlDbPath } from '@/api/wps'
import router from '@/router';

/** 
  * 下载文件
  * @param {String} url 目标url
  * @param {fileName} url 指定文件下载名称
  * @return {void} 
  */
export function downloadFile(url, fileName) {
    var x = new XMLHttpRequest();
    x.open("GET", url, true);
    x.responseType = 'blob';
    x.onload = function (e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
    }
    x.send();
}

/** 
* 替换pdf文件的预览或下载地址
* @param {String} url 目标url
* @return {String}  替换后的url 
*/
export function getPdfUrl(url) {
    if (url.indexOf('http') != -1) {
        return url.replace('http://222.85.214.245:9559', 'https://222.85.214.245:9558/webapi')
    }
    return url
}

/** 
* 转换文件格式
* @param {Number} size 文件原始大小
* @return {String}  格式化后的文件大小 
*/
export function sizeTostr(size) {
    var data = "";
    if (size < 0.1 * 1024) { //如果小于0.1KB转化成B  
        data = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB  
        data = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB  
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB  
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    var sizestr = data + "";
    var len = sizestr.indexOf("\.");
    var dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {//当小数点后为00时 去掉小数部分  
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
}


/** 
* 获取url中的参数
* @param {String} name 目标key
* @return {String}  指定的key对应的value
*/
export function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

/** 
* 替换URL的参数值
* @param {String} url 目标url
* @param {String} arg 需要替换的参数名称 
* @param {String} arg_val 替换后的参数的值 
* @return {String}  参数替换后的url 
*/
export function changeURLArg(url, arg, arg_val) {
    var pattern = arg + '=([^&]*)';
    var replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        var retuenUrl = url;
        var temp = '/(\&' + arg + '=)([^&]*)/gi';
        if (eval(temp).test(retuenUrl)) {
            retuenUrl = retuenUrl.replace(eval(temp), '&' + replaceText);
        }
        var temps = '/([\?])(' + arg + '=)([^&]*)/gi';
        if (eval(temps).test(retuenUrl)) {
            retuenUrl = retuenUrl.replace(eval(temps), '?' + replaceText);
        }
        return retuenUrl;
    } else {
        // if (url.match('[\?]')) {
        if (url.indexOf('?') > 0) {
            return url + "&" + replaceText;
        } else {
            return url + "?" + replaceText;
        }
    }
}

/**
 * 统一打开文件的方法
 * @param {Object} file 文件本身信息
 * @param {Object} $el vue组件对象
 * @param {Object} localStorage 本地存储对象
 * @param {Boolean} flag 是否支持编辑，默认为只读
 * @return {void} 
 */
export function openFile(file, $el, localStorage, flag = false) {
    // debugger
    const { id, docId, fileType, docSType, name, showType, url, contentType } = file
    if (contentType == 'pdf' || showType == 'pdf' && url) {
        let query = {
            id,
            fileType: fileType || contentType || showType,
            docSType,
            pdfSrc: getPdfUrl(url),
            title: name
        }
        let resolve = $el.$router.resolve({
            path: '/pdfReader',
            query: query
        })
        window.open(resolve.href, '_blank')
    } else {
        //文件类型为word,excel,ppt的用wps的打开
        const params = {
            fileId: id || docId,
            flag
        }
        getViewUrlDbPath(params).then((res) => {
            if (res.data) {
                // 跳转 使用sessionStorage，避免关键信息在ip中暴露
                // 使用push会停留当前页面，故不采纳
                // params 传递参数，子组件无法渲染iframe组件，故不采纳
                localStorage.wpsUrl = res.data.wpsUrl
                localStorage.token = res.data.token
                let resolve = $el.$router.resolve({
                    path: '/wpsReader',
                    query: {
                        wpsUrl: res.data.wpsUrl,
                        token: res.data.token
                    }
                })
                window.open(resolve.href, '_blank')
            }
        })
    }
}

// 打开cajViwer下载页面
export function handleDownloadCajViewer() {
    let resolve = router.resolve({
        path: '/caj',
    })
    window.open(resolve.href, '_blank')
    // let a = document.createElement("a");
    // a.href = "http://192.168.1.5:5432/cajview/CAJViewer8.1.exe";
    // a.download = "CAJViewer8.1.exe.exe";
    // a.style.display = "none";
    // document.body.appendChild(a);
    // a.click();
    // a.remove();
}
