import moment from 'moment'
import 'moment/locale/zh-cn'
import commonApi from '@/api/common'


export async function uploadFile(file, callback, progressfn) {

    if (!file) {
        return
    }

    let folder = 'feedback';
    let path = folder + '/' + new Date().toLocaleDateString().split('/').join('-');
    commonApi.getPolicy(path).then(res => {
        console.log(res);
        console.log(file);
        let fileName = uuid(32) + file.name.substring(file.name.lastIndexOf("."), file.name.length);
        console.log("fileName: ", fileName);
        const fd = new FormData();
        const {accessid, host, policy, signature, dir, cdnUrl} = res;
        fd.append('OSSAccessKeyId', accessid);
        fd.append('policy', policy);
        fd.append('signature', signature);
        fd.append('key', dir + '/' + fileName);
        fd.append('success_action_status', 200);
        fd.append('file', file, fileName);
        const xhr = new XMLHttpRequest();
        xhr.open('post', host, true);
        //控制进度条的
        xhr.upload.addEventListener('progress', (evt) => {
            let progress = Math.round((evt.loaded) * 100 / evt.total);
            progressfn && progressfn(progress);

        }, false);
        xhr.addEventListener('load', (e) => {
            if (e.target.status !== 200) {
                return
            }
            if (e.target.status === 200) {
                callback && callback(cdnUrl + '/' + dir + '/' + fileName);
            }
        }, false);
        xhr.send(fd)
    })

}

export async function uploadFiles(files, callback) {

    if (!files || !files.length) {
        return
    }

    let folder = 'feedback';
    let path = folder + '/' + new Date().toLocaleDateString().split('/').join('-');

    commonApi.getPolicy(path).then(res => {
        const {accessid, host, policy, signature, dir, cdnUrl} = res;

        for(let i = 0; i< files.length; i++) {
            let file = files[i];
            let fileName = uuid(32) + file.name.substring(file.name.lastIndexOf("."), file.name.length);
            console.log("fileName: ", fileName);
            const fd = new FormData();
            fd.append('OSSAccessKeyId', accessid);
            fd.append('policy', policy);
            fd.append('signature', signature);
            fd.append('key', dir + '/' + fileName);
            fd.append('success_action_status', 200);
            fd.append('file', file, fileName);
            const xhr = new XMLHttpRequest();
            xhr.open('post', host, true);
            xhr.addEventListener('load', (e) => {
                if (e.target.status === 200) {
                    callback && callback(cdnUrl + '/' + dir + '/' + fileName);
                }
            }, false);
            xhr.send(fd)
        }
    })


}

export function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}


/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
    const event = document.createEvent('HTMLEvents')
    event.initEvent('resize', true, true)
    event.eventType = 'message'
    window.dispatchEvent(event)
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
    if (id === '') {
        return
    }
    setTimeout(() => {
        document.body.removeChild(document.getElementById(id))
    }, timeout)
}


export function timeAgo(time) {
    var currentTime = new Date().getTime()
    var between = currentTime - time
    var days = Math.floor(between / (24 * 3600 * 1000))
    if (days === 0) {
        var leave1 = between % (24 * 3600 * 1000)
        var hours = Math.floor(leave1 / (3600 * 1000))
        if (hours === 0) {
            var leave2 = leave1 % (3600 * 1000)
            var minutes = Math.floor(leave2 / (60 * 1000))
            if (minutes === 0) {
                var leave3 = leave2 % (60 * 1000)
                var seconds = Math.round(leave3 / 1000)
                return seconds + ' 秒前'
            }
            return minutes + ' 分钟前'
        }
        return hours + ' 小时前'
    }
    if (days < 0) return '刚刚'
    if (days < 5) {
        return days + ' 天前'
    } else {
        return moment(time).format('YYYY-MM-DD HH:mm')
    }
}

export function isObject(value) {
    return value && typeof value === 'object' && value.constructor === Object
}

export function download(res, name) {
    if (!res) {
        return
    }
    let blob = new Blob([res.data], {type: res.headers['content-type']});
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = name; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
}


export function getLastDay(day) {
    let today = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) //今天23:59:59
    let lastDay = new Date(new Date(new Date(today.getFullYear(), today.getMonth(), today.getDate() - day).toLocaleDateString()).getTime()) //day天前的00:00:00
    return [lastDay, today]
}


function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

export function formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//获取cookie、
export function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return (arr[2]);
    else
        return null;
}

//设置cookie,增加到vue实例方便全局调用
export function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};

//删除cookie
export function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
};
