
import { getPolicy, uploadFile } from '@/api/ossUpload'
import * as baseUrls from "@/utils/request.js";
export default {

	exportData(msg, status = true) {
		if (!msg) {
			this.$message.warning("导出地址获取错误，请联系开发人员处理")
			return
		}
		if (status) {
			var baseUrl = baseUrls.baseURL + "common/download?fileName="
		} else {
			var baseUrl = baseUrls.BASE_IMG_URL + '/'
		}
		let url =
			baseUrl + msg;
		let link = document.createElement("a");
		let fileName = "导入模板" + ".xlsx";
		document.body.appendChild(link);
		link.href = url;
		link.download = fileName;
		link.click();
		link.remove();
	},
    /**
     * 
     * @param {// 上传图片标识 0头像 1身份证 2题库 3指南指引图片 4广告图片 5身份证或学信网图片 6文件excel,word,zip等} int 
     * @returns 
     */
    submitUpload: function (int) {
        return new Promise((resolve, reject) => {
            var uploadInput = document.createElement("input")
            uploadInput.type = 'file'
            // 可选：设置文件上传的接受的文件类型    '.png, .jpg' ， image/*
            uploadInput.accept = ".png, .jpg";
            uploadInput.style.display = 'none'
            uploadInput.onchange = () => {
                console.log(uploadInput.files[0], 'uploadInput')
                var datas = {
                    imageStatus: int
                }
                getPolicy(datas).then(res => {
                    var ossToken = res.data.resultContent
                    // const filename = file.name;
                    // const fileExtension = filename.split('.').pop().toLowerCase()
                    let formData = new FormData()
                    // formData.append('key', ossToken.dir + "." + fileExtension); //存储在oss的文件路径
                    formData.append('key', ossToken.dir); //存储在oss的文件路径
                    formData.append('OSSAccessKeyId', ossToken.accessid); //accessKeyId
                    formData.append('policy', ossToken.policy); //policy
                    formData.append('Signature', ossToken.signature); //签名
                    // formData.append('callback', ossToken.callback); //回调
                    formData.append('success_action_status', 200); //成功后返回的操作码
                    //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
                    formData.append("file", uploadInput.files[0]);
                    uploadFile(ossToken.host, formData).then(resp => {
                        resolve(ossToken.dir)
                        // resolve(ossToken.host + '/' + ossToken.dir)
                        document.removeChild(uploadInput)
                    }).catch(error => {
                        reject(error)
                    })
                }).catch(err => {
                    document.removeChild(uploadInput)
                    reject(err)
                })
            } 
            // 执行onchange
            uploadInput.click()
        })
    },

    /**
     * 图片下载
     * @param {* 文件路径} _url 
     * @param {* 文件保存名称 = 默认为当前时间戳new Date().getTime()} fileName 
     * @param {* 文件保存类型 = 默认为.jpg格式} type 
     */
    downloadImg(_url, fileName = new Date().getTime(), fileType = '.jpg') {
        if (!_url) {
            this.$message.error("文件不存在！");
            return
        }
        let url = this.splitImgHost(_url) // 获取文件完整链接路径信息
        let xhr = new XMLHttpRequest()
        xhr.open("get", url, true)
        xhr.responseType = "blob";
        xhr.onload = function() {
            if (xhr.status == 200) {
                var blob = new Blob([xhr.response]) //二进制文件流
                let href = window.URL.createObjectURL(blob) //创建下载的链接
                let link = document.createElement("a")
                link.href = href;
                link.download = fileName + fileType
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(href) //释放掉blob对象
            }
        }
        xhr.send();
    },



    splitImgHost(url) {
		if (!url) {
			return ''
		}
		if (url.indexOf("http") != -1 || url.indexOf("https") != -1 || url.indexOf("base64") != -1) {
			return url;
		}
		return baseUrls.BASE_IMG_URL + '/' + url
	},

    /**
     * 
     * @param {show: 10位转13位回显使用 save: 13位转10位提交} type 
     * @param {*} timestamp 
     * @returns 
     */
    timestampTo1013(type, timestamp) {
        console.log(timestamp, '---timestamp')
        if(!timestamp) {
            return null
        }
        return type === 'show' ? parseInt(timestamp * 1000) : parseInt(timestamp / 1000)
    },
    /**
     * 
     * @param {*} timestamp 
     * @param {YYYY-MM-dd hh:mm:ss 根据日期显示需求传入年月日时分秒} format 
     * @returns 
     */
    timestampFormat(timestamp, format = 'YYYY-MM-dd') {
        if (!timestamp) {
            return null;
        }
        var date = new Date(timestamp * 1000) // 10位时间戳转化用于符合组件13位显示
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10  ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-';
        var d = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + " ";
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
		var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        var time = null;
        // split(/[- :]/)使用了正则表达式来作为分隔符，匹配 "-（空格）:" 
        format.split(/[- :]/).forEach(i => {
            if (i === 'YYYY') time = Y
            if (i === 'MM') time += M
            if (i === 'dd') time += d
            if (i === 'hh') time += h
            if (i === 'mm') time += m
            if (i === 'ss') time += s
        })
        return time
    },
    // 获取get路径请求参数
    getQueryVariable(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) { return pair[1]; }
		}
		return (false);
	},
    // 获取图片完整路径
    getUrl() {
		return baseUrls.BASE_IMG_URL + '/'
	},
}