<script setup lang="ts">
import type { CascaderProps } from 'element-plus'
import { getAreaList } from '@/api/area'

interface Props {
  // 选中数据
  modelValue: string | string[]
  // 地区类型
  type?: 'province' | 'city' | 'area'
  props?: CascaderProps
  // 自定义数据源
  request?: () => Promise<any>
}

const props = withDefaults(defineProps<Props>(), {
  type: 'area',
  clearable: true,
  request: getAreaList
})
const emits = defineEmits(['change', 'update:modelValue'])

const modelValue = computed({
  get: () => (typeof props.modelValue === 'string' ? props.modelValue.split(',') : props.modelValue),
  set: value => emits('update:modelValue', Array.isArray(value) ? value.join(',') : value)
})

/* 配置 */
const cascaderProps = {
  value: 'id',
  ...props.props
}

const options = ref<any>([])
props.request().then((res: any) => {
  options.value = res
})
/* 级联数据 */
const cascaderData = computed(() => {
  // 选择区
  if (props.type === 'area') {
    return options.value
  } else if (props.type === 'city') {
    // 选择市返回两级
    return options.value.map((x: any) => {
      return {
        id: x.id,
        label: x.label,
        children: x.children.map((y: any) => {
          return {
            id: y.id,
            label: y.label
          }
        })
      }
    })
  } else {
    // 全部返回
    return options.value.map((x: any) => {
      return {
        id: x.id,
        label: x.label
      }
    })
  }
})
</script>

<template>
  <el-cascader
    v-model="modelValue"
    :options="cascaderData"
    :props="cascaderProps"
    clearable
    collapse-tags
    style="width: 100%"
  />
</template>

<style scoped lang="scss">
:deep(.el-cascader__dropdown) {
  min-width: 200px;
}
</style>
