<template>
  <component
    ref="address"
    :is="componentId"
    :http-client="httpClient"
    :api-url-map="apiUrlMap"
    :response-props="responseProps"
    :response-path="responsePath"
    :placeholder="placeholder"
    :address-i-ds="value"
    :disabled="disabled"
    :level="level"
    :clearable="clearable"
    @change="change">
  </component>
</template>

<script>
import HnAddressCascader from './address-cascader';
import HnAddressSelect from './address-select';

export default {
  name: 'HnAddress',
  components: {
    HnAddressCascader,
    HnAddressSelect
  },
  props: {
    value: {
      type: Array,
      default: () => ([])
    },
    httpClient: Function,
    apiUrlMap: {
      type: Object,
      default: () => {
        const prefix = 'https://openapi.qipeipu.com/bs/region/find';
        return {
          province: prefix + '/allProvince',
          city: prefix + '/findCityByProvinceID',
          county: prefix + '/findCountyByCityID',
          town: prefix + '/findTownByCountyID'
        };
      }
    },
    responseProps: {
      type: Object,
      default: () => ({
        provinceID: 'provinceID',
        provinceName: 'provinceName',
        cityID: 'cityID',
        cityName: 'cityName',
        countyID: 'countyID',
        countyName: 'countyName',
        townID: 'townID',
        townName: 'townName'
      })
    },
    responsePath: {
      type: String,
      default: 'data.model'
    },
    level: {
      type: Number,
      default: 4
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: [String, Array],
    clearable: {
      type: Boolean,
      default: false
    },
    isCascade: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    componentId() {
      return this.isCascade ? 'HnAddressCascader' : 'HnAddressSelect';
    }
  },
  methods: {
    change(v) {
      this.$emit('change', v);
      if (!v.provinceID) {
        this.$emit('input', []);
        return;
      }
      this.$emit('input', [v.provinceID, v.cityID, v.countyID, v.townID].slice(0, this.level));
    },

    setDefaultValue(addressIDs) {
      return this.$refs.address.setDefaultValue(addressIDs);
    }
  }
};
</script>
