<template>
  <dist-picker-inner :districts="districts" :province="model.province" :city="model.city" :area="model.area" :disabled="disabled" @province="handleProvince" @city="handleCity" @area="handleArea"></dist-picker-inner>
</template>
<script>
import DistPickerInner from './dist-picker-inner';
import DISTRICT_DATA from './districts.js';
import REGION_DATA from './districts.json';

export default {
  components: { DistPickerInner },
  name: 'DistPicker',
  props: {
    // 组件值
    value: Object,
    // 选择框禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
    districtsData: {
      type: Object
    },
    regionData: {
      type: Object
    }
  },
  data () {
    return {
      // 组件需要的绑定值
      model: {
        province: '',
        city: '',
        area: '',
      },
      // 实际需求的完整值
      form: {
        province: {},
        city: {},
        area: {},
      }
    };
  },
  computed: {
    districts() {
      return this.districtsData || DISTRICT_DATA
    },
    regionDataObj() {
      return this.regionData || REGION_DATA
    }
  },
  watch: {
    value(val = {}) {
      const { province = {}, city = {}, area = {} } = val;
      this.form.province = province;
      this.form.city = city;
      this.form.area = area;
      this.model.province = province.value || this.regionDataObj[province.code];
      this.model.city = city.value || this.regionDataObj[city.code];
      this.model.area = area.value || this.regionDataObj[area.code];
    },
  },
  methods: {
    handleProvince(data) {
      const { value } = data;
      this.model.province = value;
      this.form.province = data;
      this.$emit('input', JSON.parse(JSON.stringify(this.form)));
      this.$emit('change', JSON.parse(JSON.stringify(this.form)));
    },
    handleCity(data) {
      const { value } = data;
      this.model.city = value;
      this.form.city = data;
      this.$emit('input', JSON.parse(JSON.stringify(this.form)));
      this.$emit('change', JSON.parse(JSON.stringify(this.form)));
    },
    handleArea(data) {
      const { value } = data;
      this.model.area = value;
      this.form.area = data;
      this.$emit('input', JSON.parse(JSON.stringify(this.form)));
      this.$emit('change', JSON.parse(JSON.stringify(this.form)));
    },
  }
};
</script>