<template>
  <a-cascader
    v-model:value="value"
    :options="data"
    :field-names="{ label: 'text', value: useCode ? 'value' : 'text' }"
    :style="{ width: '100%' }"
    placeholder="请选择省市"
    @change="handleChange"
  />
</template>

<script setup lang="ts">
import NotConfigue from '@/api/NotConfigue';
import { onMounted, ref, computed, watch } from 'vue';

const data = ref<Array<any>>([]);
const localValue = ref<Array<string | number>>([]);

const props = defineProps({
  modelValue: {
    type: Array as () => Array<string | number>,
    default: () => []
  },
  useCode: {
    type: Boolean,
    default: false,
  },
})

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

// 计算属性用于双向绑定
const value = computed({
  get() {
    return props.modelValue || localValue.value;
  },
  set(newValue) {
    localValue.value = newValue;
    emit('update:modelValue', newValue);
  }
})

// 监听外部modelValue变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && JSON.stringify(newValue) !== JSON.stringify(localValue.value)) {
      localValue.value = [...newValue];
    }
  },
  { deep: true }
)

onMounted(() => {
  NotConfigue.get('https://mn.wenlvti.net/app_static/xiangan/city-data.json', '', undefined).then((res) => {
    data.value = res.data as any[];
    // 如果有初始值，设置到本地状态
    if (props.modelValue && props.modelValue.length > 0) {
      localValue.value = [...props.modelValue];
    }
  })
});

function handleChange(values: Array<string | number>) {
  emit('update:modelValue', values);
}
</script>