import { shallowRef, computed, getCurrentInstance } from 'vue'
import axios from 'axios'

interface Region {
    autoid: number;
    divisioncode: string;
    divisionlevel: string;
    divisionname: string;
    modifierid: number;
    modifytime: string;
    parentcode: string;
    pathname: string;
    postcode: string;
    separablename: string;
    shortcode: string;
}

export function useRegion(defaultValue: (number | undefined)[]) {
    const instance = getCurrentInstance()

    const region: { province: Region[]; city: Region[]; district: Region[]; } = {
        province: [],
        city: [],
        district: []
    }

    const provinceList = shallowRef<Region[]>([])
    const provinceId = shallowRef(defaultValue[0])
    const cityId = shallowRef(defaultValue[1])
    const districtId = shallowRef(defaultValue[2])

    const cityList = computed(() => {
        const province = provinceList.value.find((e) => e.autoid === provinceId.value)
        if (province) {
            return region.city.filter((e) => e.parentcode === province.divisioncode)
        }
        return []
    })

    const districtList = computed(() => {
        const city = cityList.value.find((e) => e.autoid === cityId.value)
        if (city) {
            return region.district.filter((e) => e.parentcode === city.divisioncode)
        }
        return []
    })

    const regionChage = () => {
        const value = [provinceId.value, cityId.value, districtId.value]
        instance?.emit('update:province', value[0])
        instance?.emit('update:city', value[1])
        instance?.emit('update:district', value[2])
        instance?.emit('change', value)
    }

    const provinceChange = () => {
        cityId.value = undefined
        districtId.value = undefined
        regionChage()
    }

    const cityChange = () => {
        districtId.value = undefined
        regionChage()
    }

    const districtChange = () => {
        regionChage()
    }

    axios('./config/address.json').then((res) => {
        res.data.forEach((e: Region) => {
            if (e.divisionlevel === 'province') {
                region.province.push(e)
            }
            if (e.divisionlevel === 'city') {
                region.city.push(e)
            }
            if (e.divisionlevel === 'district') {
                region.district.push(e)
            }
        })
        provinceList.value = region.province
    })

    return {
        provinceList,
        cityList,
        districtList,
        provinceId,
        cityId,
        districtId,
        provinceChange,
        cityChange,
        districtChange,
    }
}