<template>
  <distpicker :province="model.province" :city="model.city" :area="model.area" :disabled="disabled" @province="handleProvince" @city="handleCity" @area="handleArea"></distpicker>
</template>
<script>
import RegionData from '@/components/DistPicker/districts.json';

export default {
  name: 'Dist',
  props: {
    // 组件值
    value: Object,
    // 选择框禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      // 组件需要的绑定值
      model: {
        province: '',
        city: '',
        area: '',
      },
      // 实际需求的完整值
      form: {
        province: {},
        city: {},
        area: {},
      }
    };
  },
  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 || RegionData[province.code];
      this.model.city = city.value || RegionData[city.code];
      this.model.area = area.value || RegionData[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>