<template>
  <van-field
    ref="input"
    v-model="inputValue"
    :label="label"
    :name="name"
    :size="size"
    :placeholder="placeholder"
    :border="border"
    :disabled="disabled"
    :required="required"
    :clearable="clearable"
    :clickable="clickable"
    :is-link="isLink"
    :error="error"
    :error-message="errorMessage"

    :arrow-direction="arrowDirection"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :error-message-align="errorMessageAlign"
    :autosize="autosize"
    :left-icon="leftIcon"
    :right-icon="rightIcon"
    :icon-prefix="iconPrefix"
    :rules="editable?rules:null"
    readonly
    @click-input="onClick"
  >
    <template #label>
      {{ label }}<van-icon v-if="desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="$action.descDialog({ title:label, message:desc })" />
    </template>
    <template v-if="editable" #right-icon>
      <van-icon
        v-if="showClear"
        name="clear"
        class="van-field__clear"
        @click.native.stop="onRightIconClick"
      />
      <van-icon
        v-else
        :name="showPopup?'arrow-up':'arrow-down'"
        @click.native.stop="onClick"
      />
      <van-popup
        v-model="showPopup"
        get-container="body"
        position="bottom"
        @opened="onOpened"
      >
        <van-picker
          ref="picker"
          :title="title"
          show-toolbar
          :default-index="defaultIndex"
          :columns="columns"
          :value-key="labelKey"
          @confirm="onConfirm"
          @cancel="showPopup = false"
        />
      </van-popup>
    </template>
  </van-field>
</template>

<script>
import { isDef, isObject } from 'vant/lib/utils'
import FieldMixin from '@/mixins/field'

export default {
  name: 'ibps-select',
  mixins: [FieldMixin],
  props: {
    title: {
      type: String
    },
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    otherOptionKey: {
      type: String,
      default: 'include_other_option'
    },
    otherOptionValue: {
      type: String,
      default: ''
    },
    desc: String
  },
  data() {
    return {
      showPopup: false,
      otherOption: '',
      otherOptionPlaceholder: '其他选项',
      defaultIndex: 0
    }
  },
  computed: {
    showClear() {
      return this.clearable && this.$utils.isNotEmpty(this.value) && isDef(this.value) && this.editable
    },
    cacheOptions() {
      const arr = this.options
      if (!arr || arr.length === 0) { return {} }
      const cacheOptions = {}
      for (let i = 0; i < arr.length; i++) {
        const option = arr[i]
        if (option instanceof String) {
          cacheOptions[option] = {
            [this.labelKey]: option
          }
        } else {
          cacheOptions[option[this.valueKey] ] = option
        }
      }
      return cacheOptions
    },
    hasOtherOption() {
      return this.isIncludeOtherOption(this.value)
    },
    columns() {
      return this.options
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        this.setInputValue()
        this.validate()
      },
      immediate: true
    },
    otherOption() {
      this.changeOtherOption(this.otherOption)
    }
  },
  methods: {
    setInputValue() {
      let inputValue = ''
      if (this.$utils.isEmpty(this.value)) {
        inputValue = ''
      } else {
        if (this.cacheOptions[this.value]) {
          inputValue = this.cacheOptions[this.value][this.labelKey]
        } else {
          inputValue = (isObject(this.value) ? '' : this.value)
        }
      }
      this.inputValue = inputValue
    },
    initSelected() {
      if (this.value) {
        return this.options.findIndex((option) => {
          return option[this.valueKey] === this.value
        })
      } else {
        return 0
      }
    },
    onClick() {
      if (!this.editable) { return }
      this.defaultIndex = this.initSelected()
      this.showPopup = true
    },
    onOpened() {

    },
    onRightIconClick() {
      this.showClear ? this.onClear() : this.onClick()
    },
    onClear() {
      this.otherOption = ''
      this.$emit('input', '')
      this.$emit('change', '')
    },
    onConfirm(data, index) {
      this.showPopup = false
      this.$emit('input', data[this.valueKey])
      this.$emit('change', data[this.valueKey], data, index)
    },
    setOtherOptionValue() {
      if (this.hasOtherOption) {
        this.otherOption = this.otherOptionValue
      }
    },
    isIncludeOtherOption(value) {
      if (this.cacheOptions[value]) {
        return !!this.cacheOptions[value][this.otherOptionKey]
      }
      return false
    },
    changeOtherOption(value) {
      this.$emit('change-other-option', value)
    }
  }
}
</script>
