<template>
  <region-picker v-model="model" :disabled="disabled" :multiple="multiple" :data="data" :max-level="maxLevel" :placement="placement" :collapse-tags="collapseTags" @change="handleChange"></region-picker>
</template>
<script>
  export default {
    name: 'Region',
    props: {
      // 组件值
      value: [String, Array],
      // 选择框禁用状态
      disabled: {
        type: Boolean,
        default: false
      },
      // 多选
      multiple: {
        type: Boolean,
        default: false
      },
      // 数据源
      dataSource: [Promise, Function, Object, String],
      // 地区级数
      maxLevel: [String, Number],
      // 弹出方向
      placement: String,
      // 收缩标签
      collapseTags: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        // 绑定值
        model: this.multiple ? [] : undefined,
        // 数据
        data: undefined,
      };
    },
    watch: {
      value(val) {
        if (this.multiple && !val) {
          this.model = [];
        } else {
          this.model = val;
        }
      },
    },
    created() {
      this.queryData();
    },
    mounted() {
      this.model = !this.multiple ? this.value : this.value || [];
    },
    methods: {
      // 数据
      async queryData() {
        const isObject = this.dataSource instanceof Object;
        const isJSON = this.dataSource instanceof String;
        if (isObject || isJSON) {
          this.data = this.dataSource;
        } else {
          this.data = await this.dataSource();
        }
      },
      // 选择
      handleChange(value) {
        this.model = this.value;
        this.$emit('input', value);
        this.$emit('change', value);
      },
    }
  };
</script>