<template>
    <picker mode="multiSelector" :value="value" :range="region" @columnchange="onColumnChange" @change="onChange">
        <slot />
    </picker>
</template>

<script setup>
import { onShow } from '@dcloudio/uni-app';
import { ref, getCurrentInstance, defineProps, defineEmits } from 'vue';
const { $Http } = getCurrentInstance().proxy;

// 只保留事件
const emit = defineEmits(['select'])

const props = defineProps({
    modelValue: { type: Array, default: () => [] }
});

let region = ref([[], [], []]),
    value = ref([0, 0, 0]),
    rawData = {};

onShow(() => {
    if (region.value[0].length) return;

    region.value = uni.getStorageSync('region') || [[], [], []];

    $Http.basic({ "classname": "system.tools", "method": "query_arealist", "content": {} })
        .then(res => {
            if (res.code == 1) {
                rawData = res.data;

                const selected = props.modelValue.length ? props.modelValue : [];
                const { regionArr, indexes } = initRegion(rawData, selected);

                region.value = regionArr;
                value.value = indexes;

                uni.setStorageSync('region', region.value);
            }
        });
});

function initRegion(rawData, selected = []) {
    const provinces = Object.keys(rawData);
    const province = selected[0] || provinces[0];

    const cities = Object.keys(rawData[province] || { [province]: [province] });
    const city = selected[1] || cities[0] || province;

    const districts = rawData[province]?.[city] || [city];
    const district = selected[2] || districts[0] || province;

    const indexes = [
        provinces.indexOf(province),
        cities.indexOf(city),
        districts.indexOf(district)
    ];

    return { regionArr: [provinces, cities, districts], indexes };
}

function onColumnChange(e) {
    const { column, value: colIndex } = e.detail;
    let [pi, ci, di] = value.value;

    if (column === 0) {
        pi = colIndex;
        const province = region.value[0][pi];
        const cities = Object.keys(rawData[province] || { [province]: [province] });
        const city = cities[0] || province;
        const districts = rawData[province]?.[city] || [city];

        region.value = [region.value[0], cities, districts];
        value.value = [pi, 0, 0];
    } else if (column === 1) {
        ci = colIndex;
        const province = region.value[0][pi];
        const city = region.value[1][ci];
        const districts = rawData[province]?.[city] || [city];

        region.value = [region.value[0], region.value[1], districts];
        value.value = [pi, ci, 0];
    } else if (column === 2) {
        di = colIndex;
        value.value = [pi, ci, di];
    }
}

function onChange(e) {
    value.value = e.detail.value;
    const [pi, ci, di] = value.value;
    const selected = [
        region.value[0][pi],
        region.value[1][ci],
        region.value[2][di]
    ];
    emit('select', selected);
}
</script>
