import {pinyin} from "pinyin-pro";

class Tools {
    private static instance: Tools;
    static getInstance() {
        if (!this.instance) {
            this.instance = new Tools();
        }
        return this.instance;
    }

    /**
     * 把list结构转成 map 首字母结构
     * @param {Object} list
     */
    listToMap(list: any[]) {
        let map = new Map();
        let reg = /[A-Z]/;
        let other = '-';
        list.forEach((item, index) => {
            if (item && item.name) {
                //拼音的首字母
                let pyf = pinyin(item.name).substring(0, 1).toUpperCase()
                //不是26个字母，用-代替
                if (!reg.test(pyf)) {
                    pyf = other
                }
                let tempList = map.get(pyf) ? map.get(pyf) : [];
                tempList.push({
                    id: item.id,
                    name: item.name,
                    avatar: item.avatar,
                    type: item.type,
                })
                map.set(pyf, tempList);
            }
        })
        let res = new Map();
        //从新排序
        for (let i = 0; i < 26; i++) {
            let n = String.fromCharCode(65 + i)
            let obj = map.get(n);
            if (obj) {
                res.set(n, obj)
            }
        }
        if (map.get(other)) {
            res.set(other, map.get(other))
        }
        return res;
    }
}

export default Tools.getInstance()
