import {polyphonic} from "pinyin-pro";

const sortIndex = [
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z', '#'
]
const getNestedValue = (obj, path) => {
    const keys = path.split('.');
    let current = obj;

    for (let key of keys) {
        if (current && typeof current === 'object' && key in current) {
            current = current[key];
        } else {
            return undefined;
        }
    }
    return current;
}
const sort = (originalData = [], byString = 'label') => {
    try {

        const list = originalData.filter(o => !!getNestedValue(o, byString)).map(o => {
            let indexLetter = polyphonic(getNestedValue(o, byString).substring(0, 1), {
                toneType: 'none',
                pattern: 'first'
            }).join('').substring(0, 1).replace(/\s+/g, '').toLocaleUpperCase()
            return {
                ...o,
                indexLetter: sortIndex.includes(indexLetter) ? indexLetter : '#'
            }
        })
        list.sort((a, b) => {
            const aValue = a.indexLetter === '#' ? 'ZZ' : a.indexLetter;
            const bValue = a.indexLetter === '#' ? 'ZZ' : b.indexLetter;
            return aValue.localeCompare(bValue);
        });

        const listMap = new Map([]);
        sortIndex.forEach(o => {
            listMap.set(o, list.filter(k => k.indexLetter === o))
        })
        return {
            sortList: list,
            sortListMap: listMap
        }
    } catch (e) {
        console.log(e, 'sortStringToAZ')
    }
}

export const sortStringToAZ = {
    sortIndex,
    sort
}