<template>
    <div class="app-region" @click="show = true">
        <slot :label="inputValue">
            <input class="app-region__input" v-model="inputValue" :placeholder="placeholder" readonly />
        </slot>
        <Popup v-model:show="show" position="bottom" teleport="body" round>
            <Cascader :title="title" v-model="selectedValue" :options="options" @close="show = false" @change="onChange"
                @finish="onFinish" />
        </Popup>
    </div>
</template>

<script lang="ts" setup>
import { shallowRef, computed } from 'vue'
import { Popup, Cascader, CascaderOption } from 'vant'
import axios from 'axios'

const props = defineProps({
    modelValue: {
        type: [String, Number],
        default: 0
    },
    label: {
        type: String,
    },
    title: {
        type: String,
        default: '请选择地区'
    },
    placeholder: {
        type: String,
        default: '请选择'
    },
})

const emit = defineEmits(['update:modelValue', 'change', 'finish'])
const show = shallowRef(false) // 是否弹出选择器
const inputValue = shallowRef(props.label)
const options = shallowRef<CascaderOption[]>([])

// 选中的值
const selectedValue = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

// 选中项变化时触发
const onChange = ({ value }: { value: string | number }) => {
    emit('change', value)
}

// 全部选项选择完毕后触发
const onFinish = ({ selectedOptions }: { selectedOptions: CascaderOption[] }) => {
    const selection = selectedOptions.map((e) => e.value)
    show.value = false
    inputValue.value = selectedOptions.map((option) => option.text).join(' ')

    emit('update:modelValue', [...selection].pop())
    emit('finish', selection)
}

// 扁平列表树形化
const arrayToTree = (list: Model.Region[]) => {
    const getChildren = (parent?: string) => {
        const result: CascaderOption[] = []
        list.forEach((e) => {
            if (e.parentcode === parent) {
                const children = getChildren(e.divisioncode)
                result.push({
                    text: e.divisionname,
                    value: e.autoid,
                    children: children.length ? children : undefined,
                })
            }
        })
        return result
    }
    return getChildren('0086')
}

axios('./config/address.json').then((res) => {
    options.value = arrayToTree(res.data)
})
</script>

<style lang="less">
@import './index.less';
</style>