import {onMounted, reactive, toRefs} from "vue";
import api from "@/axios";


interface SelectAndTreeNodeType {
    administrativeDivisionTree: TreeNodeVo<string>[];
}

export const callbackResult: { [key in keyof SelectAndTreeNodeType]: (params?: Record<string, any>) => Promise<SelectAndTreeNodeType[key]> } = {
    administrativeDivisionTree: async (params = {level: 4}) => (await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionTree', params)).data,
}

export default (type?: keyof SelectAndTreeNodeType | (keyof SelectAndTreeNodeType)[], params?: { [key in keyof SelectAndTreeNodeType]?: Record<string, any> }) => {
    const allData = reactive<SelectAndTreeNodeType>({
        administrativeDivisionTree: [],
    })

    const refreshData = (type: keyof SelectAndTreeNodeType | (keyof SelectAndTreeNodeType)[]) => {
        if (typeof type === "string") {
            //@ts-ignore
            callbackResult[type](params?.[type]).then(data => allData[type] = data)
        } else {
            //@ts-ignore
            type.forEach(t => callbackResult[t](params?.[t]).then(data => allData[t] = data))
        }
    }

    onMounted(() => type && refreshData(type))

    return {
        refreshData,
        ...toRefs(allData),
        callbackResult
    }

}
