import { cascaderHn } from '/@/api/model/dict'

const storageKey = 'app_dict_data_area_cascaderHn';

export const getDictData = () => {
    // 先从本地加载数据
    let dictData = getLocalDict();
    if (!dictData) {
        // 如果本地没有数据，则从接口获取
        cascaderHn().then(res => uni.setStorageSync(storageKey, JSON.stringify(res[0].children).replaceAll('label', 'text')));
    }
    return dictData;
}

/**
 *  获取本地数据
 */
export const getLocalDict = () => {
    const data = uni.getStorageSync(storageKey);
    if (data) {
        return data ? JSON.parse(data) : null;
    }
    return null;
}

/**
 *  刷新数据
 */
export const refreshDictData = () => {
    // 删除本地数据
    uni.removeStorageSync(storageKey);
    // 重新获取数据
    getDictData();
}

export const areaOptions = getDictData();

export const getText = (scope: string, spliced: string) => {
        if (!scope || !areaOptions || areaOptions.length === 0) {
            return ''
        }

        const values = scope.split(',')
        const labels = []

        // 递归查找label
        const findLabel = (nodes, value) => {
            for (const node of nodes) {
                if (node.value === value) {
                    return node.text
                }
                if (node.children && node.children.length > 0) {
                    const found = findLabel(node.children, value)
                    if (found) {
                        return found
                    }
                }
            }
            return null // 如果没找到，返回原始value
        }

        for (const value of values) {
            const text = findLabel(areaOptions, value.trim())
            labels.push(text)
        }

        if (spliced) {
            return labels ? labels.join(spliced) : ''
        } else {
            return labels ? labels.join('') : ''
        }
    }