import areaData from '@/untils/area';

function format(data) {
    const result = [];
    const children = {};
    const dic = {
        '0': {
            label: 'root',
            value: '0',
            children: result
        }
    };

    data.forEach(item => {
        if (item.layer > 3) {
            return;
        }
        const node = {
            label: item.areaName,
            value: item.areaId,
            quickQuery: item.quickQuery,
            simpleSpelling: item.simpleSpelling,
            parentId: item.parentId
        };
        if (dic.hasOwnProperty(item.parentId)) {
            if (!dic[item.parentId].children) {
                dic[item.parentId].children = [];
            }
            dic[item.parentId].children.push(node);
        } else {
            dic[item.parentId] = {
                children: [node]
            };
        }
        if (children.hasOwnProperty(item.parentId)) {
            children[item.parentId].push(node);
        } else {
            children[item.parentId] = [node];
        }
        if (dic.hasOwnProperty(item.areaId)) {
            dic[item.areaId].label = item.areaName;
            dic[item.areaId].value = item.areaId;
        } else {
            dic[item.areaId] = node;
        }
    });
    return {
        data: result,
        children,
        dic
    };
}

let loaded = false

const data = format(areaData)
const area = {
    state: {
        ...data
    },
    actions: {
        InitArea({
            commit
        }) {
            if (!loaded) {
                loaded = true
                import('@/untils/area.js').then((resp) => {
                    commit('SET_AREA', format(resp.default));
                })
            }
        },
    },
    mutations: {
        SET_AREA: (state, data) => {
            state.data = data.data
            state.dic = data.dic
        },
    },
    getters: {
        getAreaParents: (state) => (id) => {
            const res = [];
            let item = state.dic[id];
            while (item && item.value !== '0') {
                id = item.parentId;
                res.unshift(item);
                item = state.dic[id];
            }
            return res
        }
    }
};

export default area;