import { request } from "@/services/request";
import { ref } from "vue";
import { Addresss } from './interface';

export function getAddress() {
    const cityList = ref<Addresss[]>([]); // 市
    const districtList = ref<Addresss[]>([]);// 区
    const provinceList = ref<Addresss[]>([]); // 省

    const city: Addresss[] = []; // 市
    const district: Addresss[] = []; // 区
    // 获取地址数据
    request({ method: 'get', url: './config/address.json' }).then(res => {
        res.data.forEach((el: Addresss) => {
            const { divisionlevel } = el;
            if (divisionlevel === 'city') { // 市
                city.push(el)
            } else if (divisionlevel === 'district') { // 区
                district.push(el)
            } else if (divisionlevel === 'province') { // 省
                provinceList.value.push(el)
            }
        });
    }).catch((err) => {
        throw new Error('读取地址失败！');
    })
    /**
     * 获取 市 数据
     * @param autoid 省id
     */
    function getCityList(autoid: number) {
        const province = provinceList.value.find(e => e.autoid === autoid)
        if (province) {
            cityList.value = city.filter(e => e.parentcode === province.divisioncode)
        }
    }
    /**
     * 获取 区  数据
     * @param autoid 市 id
     */
    function getDistrictList(autoid: number) {
        const temp = city.find(e => e.autoid === autoid)
        if (temp) {
            districtList.value = district.filter(e => e.parentcode === temp.divisioncode)
        }
    }
    function getName(arr: Addresss[], autoid: number): string {
        const temp = arr.find(e => e.autoid === autoid)
        return temp ? temp.divisionname : '--'
    }
    /**
     * 获取 省 名
     * @param autoid 
     */
    function getProvinceName(autoid: number) {
        return getName(provinceList.value, autoid)
    }
    /**
     * 获取 市 名
     * @param autoid 
     */
    function getCityName(autoid: number) {
        return getName(city, autoid)
    }
    /**
     * 获取 区 名
     * @param autoid 
     */
    function getDistrictName(autoid: number) {
        return getName(district, autoid)
    }

    return { cityList, districtList, provinceList, getCityList, getDistrictList, getProvinceName, getCityName, getDistrictName }
}