<!-- 省市区级联选择器 -->
<template>
  <a-cascader
    :value="value"
    :options="accessoryData"
    :show-search="showSearch"
    :placeholder="placeholder"
    dropdown-class-name="ele-pop-wrap-higher"
    @change="onChange"
    @update:value="updateValue"
  />
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import type { ValueType } from 'ant-design-vue/es/vc-cascader/Cascader';
  import { listCategory } from '@/api/goods/category';
  import { toTreeData } from 'ele-admin-pro/es';
  import { Category } from '@/api/goods/category/model';

  const props = withDefaults(
    defineProps<{
      value?: string[];
      placeholder?: string;
      options?: Category[];
      valueField?: 'label';
      showSearch?: boolean;
    }>(),
    {
      showSearch: true
    }
  );

  const emit = defineEmits<{
    (e: 'update:value', value?: string[]): void;
    (e: 'load-data-done', value: Category[]): void;
  }>();

  // 级联选择器数据
  const accessoryData = ref<Category[]>([]);

  /* 更新 value */
  const updateValue = (value: ValueType) => {
    emit('update:value', value as string[]);
  };

  const onChange = (e) => {
    console.log(e);
  };

  watch(
    () => props.options,
    (options) => {
      listCategory().then((data) => {
        accessoryData.value = toTreeData({
          data: data.map((d) => {
            return { ...d, value: d.title, label: d.title };
          }),
          idField: 'categoryId',
          parentIdField: 'parentId'
        });
      });
      // accessoryData.value = filterData(options ?? []);
      if (!options) {
        listCategory().then((data) => {
          accessoryData.value = toTreeData({
            data: data.map((d) => {
              return { ...d, value: d.title, label: d.title };
            }),
            idField: 'categoryId',
            parentIdField: 'parentId'
          });
          emit('load-data-done', accessoryData.value);
        });
      }
    },
    {
      immediate: true
    }
  );
</script>
