<template>
  <t-cascader
    v-model="selected"
    :options="options"
    :clearable="clearable"
    :placeholder="placeholder"
    check-strictly
    @change="onChange"
  >
  </t-cascader>
</template>

<script setup name="SelectArea">
import { ref, watch } from 'vue';
import { buildData } from './area';

let selected = ref('');
const emit = defineEmits(['change']);
const props = defineProps({
  level: { type: Number, default: 3 },
  clearable: { type: Boolean, default: true },
  disabled: { type: Boolean, default: false },
  placeholder: { type: String, default: '请选择' },
});

let options = ref([]);
let areaCodeMap = {};

const getAreaStrArr = (arr, parentNode) => {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    item.parentLabels = parentNode
      ? [...parentNode.parentLabels, parentNode.label]
      : [];
    if (item.children) {
      getAreaStrArr(item.children, item);
    }
  }
  return arr;
};

let _options = [];
const getChooseLabels = (val, arr = _options) => {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (item.value == val) {
      return [...item.parentLabels, item.label];
    }
    if (item.children) {
      let result = getChooseLabels(val, item.children);
      if (result) {
        return result;
      }
    }
  }
};
const initData = () => {
  const data = buildData(props.level);
  options.value = data.areaData;
  _options = getAreaStrArr(options.value);
  console.log('_options', _options);
  areaCodeMap = data.areaCodeMap;
};
initData();

const getVal = (list) => {
  if (!list.length) return ['', '', ''].slice(0, props.level);
  return list.map((item) => areaCodeMap[item]);
};

const onChange = (val) => {
  emit('change', getChooseLabels(val));
};
</script>
