<!-- 城市 -->
<template>
  <span>
    <cs-field
      ref="csField"
      v-model="currentValue"
      :label="label"
      :rules="rules"
      :rules-key="rulesKey"
      :disabled="disabled"
      :colon="colon"
      :required="required"
      :readonly="readonly"
      :error-message-align="errorMessageAlign"
      :label-class="labelClass"
      :label-width="labelWidth"
      :label-align="labelAlign"
      :input-align="inputAlign"
      right-icon="arrow"
      @click="showArea = true"
    >
      <div :class="disabled ? 'disabled' : ''">
        <span v-if="currentValue">{{ currentValue }}</span>
        <span class="placeholder" v-else>{{ currentPlaceholder }}</span>
      </div>
    </cs-field>
    <van-popup v-model="showArea" position="bottom">
      <van-area :area-list="areaList" @confirm="areaConfirm" @cancel="showArea = false" />
    </van-popup>
  </span>
</template>
<script>
import CsField from '../Base'
import mixin from '../mixin'
import Data from '../../../../lib/data/city.json'
import { i18n } from '../../../..//lib/locale/lang/index'

export default {
  name: 'CsFieldCity',
  components: { CsField },
  mixins: [mixin],
  props: {
    // 当前输入的值
    value: {
      default: null
    }
  },
  data() {
    return {
      i18nLang: new Vue({ i18n }),
      currentValue: '',

      showArea: false,
      areaList: null
    }
  },
  //监听属性 类似于data概念
  computed: {
    currentPlaceholder() {
      if (this.placeholder) {
        return this.placeholder
      } else {
        return this.i18nLang.$t('common.placeholderCity')
      }
    }
  },
  //监控data中的数据变化
  watch: {
    value: {
      handler(val, oldVal) {
        if (val != oldVal) {
          this.setData()
        }
      },
      immediate: true, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  //方法集合
  methods: {
    change() {
      this.$forceUpdate()
    },

    /** 选中地址 */
    areaConfirm(areaValues) {
      let names = []
      areaValues.forEach(value => {
        if (value.name && value.name != '-') {
          names.push(value.name)
        }
      })
      this.areaValue = names.join('-')
      this.showArea = false
      this.$emit('input', this.areaValue)
    },

    /** 绑定数据 */
    setData() {
      this.currentValue = this.value
    },

    init() {
      if (!this.areaList) {
        this.areaList = Data
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init()
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped></style>
