<!-- 选择框 -->
<template>
  <cs-field
    ref="csField"
    v-model="currentLabel"
    :label="label"
    :rules="rules"
    :rules-key="rulesKey"
    :disabled="disabled"
    :readonly="true"
    :colon="colon"
    :required="required"
    :center="center"
    :error-message-align="errorMessageAlign"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    right-icon="arrow"
    @click="showPicker"
  >
    <div :class="disabled ? 'disabled' : ''">
      <span v-if="currentLabel">{{ currentLabel }}</span>
      <span class="placeholder" v-else>{{ currentPlaceholder }}</span>
    </div>

    <template #popup>
      <van-picker
        ref="picker"
        :title="pickerTitle"
        :columns="currentOptions"
        :columns-field-names="pickerColumnsFieldNames"
        :confirm-button-text="pickerConfirmButtonText"
        :cancel-button-text="pickerCancelButtonText"
        :toolbar-position="pickerToolbarPosition"
        :loading="pickerLoading"
        :show-toolbar="pickerShowToolbar"
        :allow-html="pickerAllowHtml"
        :default-index="currentDefaultIndex"
        :item-height="pickerItemHeight"
        :visible-item-count="pickerVisibleItemCount"
        :swipe-duration="pickerSwipeDuration"
        @change="change"
        @confirm="confirm"
        @cancel="cancel"
      >
        <!-- 自定义标题内容 -->
        <template #title> <slot name="picker-title"></slot> </template>
        <!-- 自定义确认按钮内容 -->
        <template #confirm> <slot name="picker-confirm"></slot> </template>
        <!-- 自定义取消按钮内容 -->
        <template #cancel> <slot name="picker-cancel"></slot> </template>
        <!-- 自定义选项内容 -->
        <template slot="option" slot-scope="scope">
          {{ scope.label }}
        </template>
        <!-- 自定义选项上方内容 -->
        <template #columns-top> <slot name="picker-columns-top"></slot> </template>
        <!-- 自定义选项下方内容 -->
        <template #columns-bottom> <slot name="picker-columns-bottom"></slot> </template>
      </van-picker>
    </template>
  </cs-field>
</template>
<script>
import CsField from '../Base'
import mixin from '../mixin'
import { i18n } from '../../../..//lib/locale/lang/index'

export default {
  name: 'CsFieldPicker',
  components: { CsField },
  mixins: [mixin],
  props: {
    // 顶部栏标题
    pickerTitle: {
      type: String,
      default: ''
    },
    // 选项
    options: {
      type: Array,
      default: null
    },
    // 自定义 columns 结构中的字段
    pickerColumnsFieldNames: {
      type: Object,
      default: {
        text: 'label',
        values: 'value',
        children: 'children'
      }
    },
    // 确认按钮文字
    pickerConfirmButtonText: {
      type: String,
      default: ''
    },
    // 取消按钮文字
    pickerCancelButtonText: {
      type: String,
      default: '清空'
    },
    // 顶部栏位置，可选值为 bottom
    pickerToolbarPosition: {
      type: String,
      default: 'top'
    },
    // 是否显示加载状态
    pickerLoading: {
      type: Boolean,
      default: false
    },
    // 是否显示顶部栏
    pickerShowToolbar: {
      type: Boolean,
      default: true
    },
    // 	是否允许选项内容中渲染 HTML
    pickerAllowHtml: {
      type: Boolean,
      default: false
    },
    // 单列选择时，默认选中项的索引
    pickerDefaultIndex: {
      default: 0
    },
    // 选项高度，支持 px vw vh rem 单位，默认 px
    pickerItemHeight: {
      default: 44
    },
    // 可见的选项个数
    pickerVisibleItemCount: {
      default: 5
    },
    // 快速滑动时惯性滚动的时长，单位 ms
    pickerSwipeDuration: {
      default: 1000
    }
  },
  data() {
    return {
      i18nLang: new Vue({ i18n }),
      currentOptions: [],
      currentLabel: '',
      currentValue: '',
      currentDefaultIndex: this.pickerDefaultIndex
    }
  },
  //监听属性 类似于data概念
  computed: {
    currentPlaceholder() {
      if (this.placeholder) {
        return this.placeholder
      } else {
        return this.i18nLang.$t('common.placeholderSelect')
      }
    }
  },
  //监控data中的数据变化
  watch: {
    value: {
      handler(val, oldVal) {
        if (this.currentValue != val && val !== oldVal) {
          this.setData()
        }
      },
      immediate: true, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    },
    currentValue: {
      handler(val, oldVal) {
        if (this.value !== val && val !== oldVal) {
          this.$emit('input', val)
        }
      },
      immediate: true, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    },
    options: {
      handler(val, oldVal) {
        this.setData()
      },
      immediate: true, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  //方法集合
  methods: {
    /** 弹出选择框 */
    showPicker() {
      this.$refs.csField.showPopup = true
    },

    /** 当值变化时触发的事件 */
    change(value) {
      this.$emit('change', value)
    },

    /** 保存时间 */
    confirm(item) {
      this.currentLabel = item.label
      this.currentValue = item.value
      this.$emit('input', this.currentValue)
      this.$refs.csField.showPopup = false
      this.$forceUpdate()
    },

    cancel() {
      this.currentLabel = ''
      this.currentValue = ''
      this.$emit('clear')
      this.$refs.csField.showPopup = false
    },

    setData() {
      if (!this.options) {
        return
      }
      let currentOptions = []
      let currentDefaultIndex = this.currentDefaultIndex
      let currentLabel = ''
      let currentValue = ''
      for (let i = 0; i < this.options.length; i++) {
        const option = this.options[i]

        let item = {}
        if (typeof option === 'object') {
          Object.keys(option).forEach(key => {
            item[key.toLowerCase()] = option[key]
          })
        } else {
          item = {
            value: option,
            label: option
          }
        }
        if (this.value == item.value) {
          currentLabel = item.label
          currentValue = item.value
          currentDefaultIndex = i
        }
        currentOptions.push(item)
      }
      this.currentOptions = currentOptions
      this.currentDefaultIndex = currentDefaultIndex
      this.currentLabel = currentLabel
      this.currentValue = currentValue
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.setData()
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped></style>
