/*
 * @Author: qiuwt
 * @Email: qiuwt@hxmec.com
 * @Date: 2020-10-14 17:05:34
 * @Last Modified by: qiuwt
 * @Last Modified time: 2020-10-16 16:59:01
 * @Description:助手函数
 */


// 判断对象是否为空
export const isEmptyObj = obj => !obj || Object.keys(obj).length === 0;
/**
 * 获得链接后缀
 */
export const getUrlSuffix = url => {
    let type = '';
    if (url.indexOf('.') > -1) {
        type = url.split('.');
        type = type[type.length - 1];
    }
    return type;
};

/**
 * 下载图片
 */
export const download = (url, name) => {
    const a = document.createElement('a'); // 创建一个a节点插入的document
    const event = new MouseEvent('click'); // 模拟鼠标click点击事件
    a.download = name; // 设置a节点的download属性值
    a.target = 'download';
    a.href = url; // 将图片的src赋值给a节点的href
    a.dispatchEvent(event);
};


/**
 * 将url转换为对象形式
 * @param {String} url 链接地址
 */
export const urlObject = url => {
    const urlArr = url && url.split('/');
    const urlLen = urlArr.length - 1;
    const urlObj = {
        host: urlArr[2],
        hostname: urlArr[2].split(':')[0],
        origin: `${urlArr[0]}//${urlArr[2]}`,
        pathname: '',
        port: urlArr[2].split(':')[1],
        protocol: urlArr[0].split(':')[0],
        search: `?${urlArr[urlLen].split('?')[1]}`
    };

    urlArr.forEach((item, index) => {
        if (index > 2 && index < urlLen) {
            urlObj.pathname += `/${item}`;
        } else if (index === urlLen) {
            urlObj.pathname += `/${item.split('?')[0]}`;
        }
    });
    return urlObj;
};