<script setup lang="ts">
import { watch, onMounted, type PropType } from 'vue'
import area from '@/utils/area'
import { MAP_INJECTION_KEY } from '@/config/symbol'

const cascaderProps = {
    checkStrictly: true,
    value: 'label'
}
const parentApi = inject(MAP_INJECTION_KEY)

const emit = defineEmits(['handleSearch'])

const form = reactive<{ area: string[] }>({
    area: [],
})
const isDisabled = computed(() => !form.area?.length)
const isInited = computed(() => parentApi?.isInited.value)
const location = computed(() => !isInited.value ? parentApi?.address.value.address_components : '')

onMounted(() => {
    if (isInited.value) return
    setCascaderValue(location.value)
})

const handleSearch = async () => {
    emit('handleSearch', form)
}
function setCascaderValue(location: any) {
    const { province, city, district } = location
    form.area = [province, city, district]
}
defineExpose({
    setCascaderValue
})
</script>

<template>
    <div class="area__search">
        <el-form :model="form" :inline="true">
            <el-form-item label="地区选择">
                <el-cascader v-model="form.area" :options="area" :props="cascaderProps" clearable>
                </el-cascader>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="isDisabled" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style lang="scss" scoped></style>
