<template>
  <el-cascader
    :options="data"
    :props="cascaderProps"
    v-model="ids"
    clearable
    @change="handleChange"
  />
</template>
<script setup>
import { ref, watch } from "vue";
import { cascaderAreaList } from "@/api/system/area";

const props = defineProps({
  modelValue: [String, Array],
});

const emit = defineEmits(["update:modelValue", "change"]);

const data = ref([]);
const ids = ref(props.modelValue || []);

// 监听父组件传入的值变化
watch(
  () => props.modelValue,
  (newVal) => {
    ids.value = newVal || [];
  },
  { immediate: true }
);

// 监听内部值变化并通知父组件
watch(
  ids,
  (newVal) => {
    emit("update:modelValue", newVal);
  },
  { deep: true }
);

const cascaderProps = {
  multiple: false,
  checkStrictly: true,
  label: "areaName",
  value: "areaId",
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level, value } = node;
    if (level === 0) {
      // resolve(await getAreaList(100000));
      resolve(await getAreaList());
    } else {
      resolve(await getAreaList(value));
    }
  },
};
async function getAreaList(parentId) {
  return cascaderAreaList(parentId);
}
function handleChange(value) {
  emit("update:modelValue", ids.value || []);
  emit("change", ids.value || []);
}
</script>
<style lang="scss" scoped></style>
