<template>
  <t-cascader
    v-model="selected"
    :options="options"
    :clearable="clearable"
    :disabled="disabled"
    :valueType="valueType"
    :placeholder="placeholder"
    filterable
    @change="onChange"
  >
  </t-cascader>
</template>

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

let selected = ref();

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: { type: [Object, Array, String] },
  level: { type: Number, default: 3 },
  clearable: { type: Boolean, default: true },
  disabled: { type: Boolean, default: false },
  placeholder: { type: String, default: '请选择' },
  valueType: { type: String, default: 'single' }, // full/single
});

let options = [];
let areaCodeMap = {};

const initData = () => {
  const data = buildData(props.level);
  options = data.areaData;
  areaCodeMap = data.areaCodeMap;
};
initData();

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

const onChange = (val) => {
  let value = null;
  if (props.valueType === 'single') {
    value = areaCodeMap[val];
  } else {
    value = getVal(val);
  }
  emit('update:modelValue', value);
  emit('change', value);
};

// tips: valueType等于single时，不保证复现结果，因为存在不同城市区域名称相同情况
const parseCode = (val) => {
  let value = val;
  if (props.valueType !== 'single') {
    const validVals = Object.values(areaCodeMap);
    if (val.some((item) => !validVals.includes(item))) {
      return val.map((item) => '');
    }
    value = val.join('_');
  }
  if (value === '') {
    return [];
  }
  const validName = Object.keys(areaCodeMap).find(
    (item) => item.includes(value) || item.replace('_', '').includes(value)
  );
  // if (!validName) return val;
  if (!validName) return '';
  const validCode = areaCodeMap[validName].split('_');
  return props.valueType === 'single'
    ? validCode[props.level - 1]
    : validCode.slice(0, props.level);
};

watch(
  () => props.modelValue,
  (val, oldval) => {
    if (val === oldval) return;
    const code = parseCode(val);
    selected.value = code;
  },
  {
    immediate: true,
  }
);
</script>
