<!-- AreaCascader.vue -->
<template>
  <a-cascader v-model:value="modelValue" :options="options" :load-data="loadData" :placeholder="placeholder"
    :style="style" :disabled="disabled" :show-search="showSearch" :allow-clear="allowClear"
    :change-on-select="changeOnSelect" :field-names="fieldNames" @change="handleChange" ref="cascaderRef" />
</template>

<script setup>
import { ref, watch, nextTick, defineModel, onMounted,defineExpose } from 'vue';
import apis from '@/apis';
import { useDicsStore } from '@/store';

const dicsStore = useDicsStore();
const modelValue = defineModel();
const props = defineProps({
  placeholder: { type: String, default: '请选择省市区' },
  style: { type: Object, default: () => ({ width: '100%' }) },
  disabled: { type: Boolean, default: false },
  showSearch: { type: Boolean, default: true },
  allowClear: { type: Boolean, default: true },
  changeOnSelect: { type: Boolean, default: false },
  fieldNames: {
    type: Object,
    default: () => ({
      label: 'label',
      value: 'code',
      // children: 'children' // 注意：如果后端字段是 children，可以放开
    })
  }
});

const emit = defineEmits(['change']);
const options = ref([]);

// 🔁 监听 store 的省份数据
watch(
  () => dicsStore.provinceOptions,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      options.value = newVal;
    }
  },
  { immediate: true }
);


// 🔍 递归查找节点
function findNodeInOptions(options, code) {
  for (const opt of options) {
    if (opt.code === code) return opt;
    if (opt.children) {
      const found = findNodeInOptions(opt.children, code);
      if (found) return found;
    }
  }
  return null;
}
async function initData(codes){
      // 从第二级开始，逐级模拟加载
    for (let i = 1; i < codes.length; i++) {
      const parentCode = codes[i - 1];
      // const currentCode = val[i];
      // 查找当前选中的父节点
      let targetNode;
      if (i === 1) {
        // 第一级（省）在 options 中
        targetNode = options.value.find(opt => opt.code === parentCode);
      } else {
        // 更深层级，需要递归查找
        targetNode = findNodeInOptions(options.value, parentCode);
      }

      if (targetNode && !targetNode.children) {
        // 触发 loadData 加载子级
        await loadData([targetNode]);
      }

      // 等待加载完成
      await nextTick();
    }
}
// 🌐 异步加载子节点
const loadData = async (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;

  try {
    const parentId = targetOption.id || targetOption.code; // 兼容 id 或 code
    const response = await apis.common.getAreaList({
      current: 1,
      pageSize: 100,
      parentId
    });

    targetOption.loading = false;

    if (Array.isArray(response.data)) {
      const children = response.data.map(item => ({
        ...item,
        isLeaf: !item.hasChild,
        label: item.label || item.name, // 兼容字段
        value: item.code
      }));

      targetOption.children = children;
    } else {
      targetOption.children = [];
    }

    // 触发视图更新
    options.value = [...options.value];
  } catch (error) {
    console.error('加载子节点失败:', error);
    targetOption.children = [];
    targetOption.loading = false;
  }
};

// 📣 处理选择变化
const handleChange = (value, selectedOptions) => {
  console.log(value)
  emit('change', value, selectedOptions?.map(opt => opt.label) || []);
};
defineExpose({initData})
</script>