export { default as langUtil } from './langUtils';
import { getUserInfoApi } from '@/api';
export * from './requestUtil';

const USERID_KEY = 'userId';
export function getUserId() {
    return window.sessionStorage.getItem(USERID_KEY) || '';
}

export function setUserId(val) {
    window.sessionStorage.setItem(USERID_KEY, val);
}
export function clearUserId() {
    window.sessionStorage.removeItem(USERID_KEY);
}

const USERINFO_KEY = 'USERINFO';
export async function setUserInfoByRequest() {
    const userInfo = await getUserInfoApi(getUserId());
    window.sessionStorage.setItem(USERINFO_KEY, JSON.stringify(userInfo));
}

export function getUserInfo() {
    const localUserInfo = window.sessionStorage.getItem(USERINFO_KEY);
    return JSON.parse(localUserInfo);
}

export function clearUserInfo() {
    window.sessionStorage.clear();
}

/**
 * 转变菜单列表为tree结构
 * @param {Array} menuList 菜单列表
 * @param {Boolean} filterMenu 是否过滤掉菜单，只保留目录
 */
export function convertListToTree(menuList, filterMenu = false, toMenuData = false) {
    let tempMenu = [...menuList];
    if (filterMenu) {
        tempMenu = tempMenu.filter((m) => m.menuType !== 'MENU');
    }
    for (const menu of menuList) {
        if (toMenuData) {
            menu.name = menu.menuName;
            menu.path = menu.menuUrl;
        }
        if (menu.parentMenuId === 0) continue;
        const parent = menuList.find((m) => m.menuId === menu.parentMenuId);
        parent.children ? parent.children.push(menu) : (parent.children = [menu]);
    }
    return tempMenu.filter((m) => m.parentMenuId === 0);
}

export function EMPTY_FUN() {}

export const isFunction = (val) => typeof val === 'function';
export function arrayToTree(options) {
    options = JSON.parse(JSON.stringify(options));
    this.data = options.data || [];
    this.parentKey = options.parentKey || 'parent_code';
    this.childrenKey = options.childrenKey || 'children';
    this.key = options.key || 'code';
    this.maping = options.maping || undefined;
    this.rootValue = options.rootValue || '0';
    this.treeData = [];
    this.indexStorage = {};
    this.getDataBykey = function (key) {
        return this.indexStorage[key];
    };
    this.setMapping = function () {
        for (let i = 0; i < this.data.length; i++) {
            var item = this.data[i];
            for (const x in this.maping) {
                item[this.maping[x]] = item[x];
            }
        }
    };
    if (this.maping) {
        this.setMapping();
    }
    this.setIndexStorage = function () {
        for (let i = 0; i < this.data.length; i++) {
            this.indexStorage[this.data[i][this.key]] = this.data[i]; // 以id作为索引存储元素，可以无需遍历直接定位元素
        }
    };
    this.setIndexStorage();
    // 利用数组浅拷贝
    this.toTree = function () {
        const THISDATA = JSON.parse(JSON.stringify(this.data));
        for (let i = 0; i < this.data.length; i++) {
            let currentElement = this.data[i];
            let tempCurrentElementParent = this.indexStorage[currentElement[this.parentKey]]; // 临时变量里面的当前元素的父元素
            if (tempCurrentElementParent) {
                // 如果存在父元素
                if (!tempCurrentElementParent[this.childrenKey]) {
                    // 如果父元素没有chindren键
                    tempCurrentElementParent[this.childrenKey] = []; // 设上父元素的children键
                }
                tempCurrentElementParent[this.childrenKey].push(currentElement); // 给父元素加上当前元素作为子元素
            } else {
                // 不存在父元素，意味着当前元素是一级元素
                if (this.rootValue != undefined && currentElement[this.key] === this.rootValue) {
                    this.treeData.push(currentElement);
                } else {
                    this.treeData.push(currentElement);
                }
            }
        }
        return this.treeData;
    };
    this.toTree();
    return this;
}

// select组件 数据格式化
export const formatObj = (ArrObj, obj) => {
    const newData = [...ArrObj];
    const newDataOne = newData.map((i) => {
        const newObj = { ...i };
        Object.keys(obj).forEach((key) => {
            newObj[key] = i[obj[key]];
        });
        return newObj;
    });
    return newDataOne;
};

export const isObjEmpty = (data = {}) => {
    const arr = Object.keys(data);
    return arr.length === 0;
};
/**
 * 下载文件
 * @param {String} url 下载路径
 */
export function downloadFileByUrl(url) {
    const aEle = document.createElement('a');
    aEle.setAttribute('download', true);
    aEle.setAttribute('href', url);
    aEle.click();
}

/**
 * 下载文件
 * @param {data} data 文件流
 * @param {string} type 文件后缀
 */
export function downloadFile(data, type) {
    const url = window.URL.createObjectURL(data);
    // 生成一个a标签
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    // 生成时间戳
    const timestamp = new Date().getTime();
    link.download = `${timestamp}.${type}`;
    document.body.appendChild(link);
    link.click();
}
