<script lang="ts" setup>
import { defineProps, defineEmits, ref, onMounted, watch } from 'vue'
import { CascaderOption } from 'vant'
import { getGridAddress } from '@/api/system'

// 接收父组件传递的 props
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits(['update:modelValue','finish'])

const localShow = ref(props.modelValue) // 本地控制的显示状态
const cascaderValue = ref<string>() // 用于存储级联选择的值
const options = ref<CascaderOption[]>([]) // 用于存储级联选择的选项

// 监听 props 的变化，更新本地状态
watch(
  () => props.modelValue,
  (newVal) => {
    localShow.value = newVal
  }
)

// 当弹窗关闭时触发事件，更新父组件的 areaShow
const onClose = () => {
  emit('update:modelValue', false)
}


// 当级联选择完成时
const onFinish = (value: any) => {
  emit('update:modelValue', false)
  emit('finish',value)
}

// 异步加载选项数据
const fieldNames = {
  text: 'areaName',
  value: 'areaCode',
  children: 'childrenRes',
}
// 递归删除最后一级的childrenRes为[]的节点
const deleteEmptyChildren = (data: CascaderOption[]) => {
  data.forEach((item) => {
    if (item.childrenRes && item.childrenRes.length === 0) {
      delete item.childrenRes
    }
    if (item.childrenRes) {
      deleteEmptyChildren(item.childrenRes)
    }
  })
  return data
}
onMounted(async () => {
  const { data } = await getGridAddress({ parentCode: '330205', selectMethod: '2' })
  options.value = data ? deleteEmptyChildren(data) : []
})
</script>

<template>
  <van-popup v-model:show="localShow" round position="bottom">
    <van-cascader
      v-model="cascaderValue"
      title="请选择所在地区"
      :options="options"
      :field-names="fieldNames"
      @close="onClose"
      @finish="onFinish"
    />
  </van-popup>
</template>

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