<template>
  <div>
    <popup-picker
      v-model="currentValue"
      :fixed-columns="hideDistrict ? 2 : 0"
      :columns="3"
      :data="list"
      :title="title"
      :show-name="showName"
      :show-second-name="showSecondName"
      :inline-desc="inlineDesc"
      :placeholder="placeholder"
      :value-text-align="valueTextAlign"
      @on-hide="emitHide"
      @on-show="$emit('on-show')"
    />
  </div>
</template>

<script>
import { cvux as AddressChinaData, tools } from 'city-data/lib/mobile'
import PopupPicker from '../popup-picker'

const value2name = tools.value2name
const name2value = tools.name2value

export default {
  components: {
    PopupPicker
  },
  props: {
    title: {
      type: String,
      required: true
    },
    value: {
      type: Array,
      default () {
        return []
      }
    },
    rawValue: Boolean,
    list: {
      type: Array,
      required: false,
      default () {
        return AddressChinaData
      }
    },
    inlineDesc: String,
    placeholder: String,
    hideDistrict: Boolean,
    valueTextAlign: String,
    showSecondName: Boolean,
    showName: Boolean
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  computed: {
    nameValue () {
      return value2name(this.currentValue, this.list)
    }
  },
  watch: {
    currentValue (val, oldVal) {
      if (val !== oldVal) {
        this.$emit('input', val)
        let addressName = this.nameValue.split(' ')
        let changeDate = {
          province: addressName[0],
          provinceCode: val[0],
          city: addressName[1],
          cityCode: val[1],
          district: addressName[2] ? addressName[2] : null,
          districtCode: val[2] ? val[2] : null
        }
        this.$emit('on-change', changeDate)
      }
    },
    value (val) {
      this.currentValue = val
    }
  },
  created () {
    if (this.currentValue.length && this.rawValue) {
      const parsedVal = name2value(this.currentValue, this.list)
      if (/__/.test(parsedVal)) {
        console.error('Vux: Wrong address value', this.currentValue)
        this.currentValue = []
      } else {
        this.currentValue = parsedVal.split(' ')
      }
    }
  },
  methods: {
    emitHide (val) {
      this.$emit('on-hide', val)
    },
    getAddressName () {
      return value2name(this.value, this.list)
    }
  }
}
</script>
