<template>
  <div>
    <van-field
      :name="field.label"
      :required="field.required"
      :disabled="field.disabled"
      :value="areaVal"
      :label="field.label"
      right-icon="arrow-down"
      placeholder="请选择地址"
      :rules="rules(field)"
      readonly
      clickable
      @click="field.disabled ? () => {}:areaClick(field)"
    />
    <van-popup
      v-model="showArea"
      position="bottom"
    >
      <van-area
        :area-list="areaList"
        :value="areaDefault"
        @confirm="onConfirmAreaVal"
        @cancel="showArea = false"
      />
    </van-popup>
  </div>
</template>
<script>
export default {
  name: 'AreaSelect',
  props: {
    field: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 校验规则
    rules: {
      type: Function,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      showArea: false,
      areaList: [],
      areaDefault: '',
      areaInfo: {},
      areaValCode: []
    }
  },
  created () {
    const area = {
      province_list: {},
      city_list: {},
      county_list: {}
    }
    this.$store.getters.areas.forEach(province => {
      area.province_list[province.value] = province.label
      province.children.forEach(city => {
        area.city_list[city.value] = city.label
        const arr = (city.children || [])
        arr.forEach(county => {
          area.county_list[county.value] = county.label
        })
      })
    })
    this.areaList = area
    if (this.field.value.length > 0) {
      this.areaValCode = this.field.value
      this.areaVal = `${this.areaList.province_list[this.field.value[0]]}${this.areaList.city_list[this.field.value[1]]}${this.field.value[2] ? this.areaList.county_list[this.field.value[2]] : ''}`
      this.field.value = this.areaVal
    } else {
      this.areaVal = ''
      this.field.value = ''
    }
  },
  methods: {
    areaClick (field) {
      this.areaInfo = field
      this.areaDefault = this.areaValCode && this.areaValCode.length >= 2 ? this.areaValCode[2] : this.areaValCode.length >= 1 ? this.areaValCode[1] : null
      this.showArea = true
    },
    onConfirmAreaVal (values) {
      const newArr = []
      const newCode = []
      values.forEach((item) => {
        if (typeof (item) !== 'undefined') {
          newArr.push(item.name)
          newCode.push(item.code)
        }
      })
      this.areaValCode = newCode
      this.areaDefault = this.areaValCode.length > 2 ? this.areaValCode[2] : this.areaValCode.length > 1 ? this.areaValCode[1] : null
      this.areaVal = newArr.join('')
      this.areaInfo.value = this.areaVal
      this.showArea = false
    }
  }
}
</script>
