<template>
  <el-cascader
    style="width: 100%"
    :options="pcaTextArr"
    v-model="selectOptions"
    @change="onChange"
    :props="{ checkStrictly: checkStrictly }"
  />
</template>

<script>
import {pcaTextArr} from "element-china-area-data";

export default {
  name: "AreaTextSelect",
  props: {
    // 省
    province: {
      type: String,
      default: null,
    },
    // 市
    city: {
      type: String,
      default: null,
    },
    // 区
    county: {
      type: String,
      default: null,
    },
    // 是否可选任意一级
    checkStrictly: {
      type: Boolean,
      default: false
    },
    // 级别，从0开始
    level: {
      type: Number,
      default: 2,
    }
  },
  data() {
    return {
      pcaTextArr: []
    }
  },
  computed: {
    selectOptions: {
      set(val) {
        this.$emit('update:province', val.length > 0 ? val[0] : null);
        this.$emit('update:city', val.length > 1 ? val[1] : null);
        this.$emit('update:county', val.length > 2 ? val[2] : null);
      },
      get() {
        let list = [];
        if (this.province != null) {
          list.push(this.province);
        }
        if (this.city != null) {
          list.push(this.city);
        }
        if (this.county != null) {
          list.push(this.county);
        }
        return list;
      }
    },
  },
  created() {
    this.filterAreaByLevel(pcaTextArr, this.level);
  },
  methods: {
    filterAreaByDepth(areaList, targetDepth, currentDepth = 0, maxDepth = targetDepth + 1) {
      return areaList.reduce((filteredAreas, area) => {
        const depth = currentDepth + 1;

        if (depth <= maxDepth) {
          filteredAreas.push(area); // 匹配当前深度或下一层深度，保留此区域

          if (depth < maxDepth && Array.isArray(area.children) && area.children.length > 0) {
            // 当前节点不是最深节点，且有子节点，递归过滤子节点
            area.children = this.filterAreaByDepth(area.children, targetDepth, depth, maxDepth);
          } else {
            // 当前节点是最深节点或无子节点，清除其 children 属性
            delete area.children;
          }
        }

        return filteredAreas;
      }, []);
    },
    // 将地区列表按照层级过滤出来，子列表:children
    // area地区列表，level层级
    filterAreaByLevel(area, level) {
      this.pcaTextArr = this.filterAreaByDepth(area, level);
    },
    onChange(val) {
      this.$emit('change', val);
    }
  }
}
</script>

<style scoped>

</style>
