<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="showDesc(label,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"
      >
        <ibps-picker-toolbar
          :title="title"
          :cancel-button-text="cancelButtonText"
          :confirm-button-text="confirmButtonText"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
        <div class="ibps-popup-wrapper">
          <van-radio-group v-if="$utils.isNotEmpty(options)" v-model="radio">
            <van-cell-group>
              <van-cell
                v-for="option in options"
                :key="option[valueKey]"
                :title="option[labelKey]"
                clickable
                @click="onRadioClick(option[valueKey],option['disabled'])"
              >
                <template #right-icon>
                  <van-radio
                    :name="option[valueKey]"
                    :disabled="option['disabled']"
                  >
                    <template #icon="props">
                      <div v-if="props.checked" class="icon-circle">
                        <div class="icon-circle_inside" />
                      </div>
                      <van-icon v-else name="circle" />
                    </template>
                  </van-radio>
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <van-empty v-else :description="emptyData" />
        </div>
      </van-popup>
    </template>
  </van-field>
</template>

<script>
import { isDef, isObject } from 'vant/lib/utils'
import FieldMixin from '@/mixins/field'
import IbpsPickerToolbar from '@/components/ibps-picker-toolbar'
import ActionUtils from '@/utils/action'

export default {
  name: 'ibps-radio',
  components: {
    IbpsPickerToolbar
  },
  mixins: [FieldMixin],
  props: {
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    emptyData: {
      type: String,
      default: '暂无数据'
    },
    otherOptionKey: {
      type: String,
      default: 'include_other_option'
    },
    otherOptionValue: {
      type: String,
      default: ''
    },
    title: String,
    cancelButtonText: String,
    confirmButtonText: String,
    desc: String
  },
  data() {
    return {
      radio: '',
      showPopup: false,
      otherOption: '',
      otherOptionPlaceholder: '其他选项'
    }
  },
  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)
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        this.setOtherOptionValue()
        this.setInputValue()
        this.validate()
      },
      immediate: true
    },
    // radio() {
    //   this.$emit('input', this.radio)
    //   this.$emit('change', this.radio)
    // },
    otherOption() {
      this.changeOtherOption(this.otherOption)
    }

  },
  methods: {
    showDesc(title, message) {
      ActionUtils.descDialog({ title, message })
    },
    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
    },
    onClick() {
      if (!this.editable) { return }
      this.radio = this.value
      this.showPopup = true
    },
    onOpened() {

    },
    onRadioClick(val, disabled) {
      if (disabled) return
      this.radio = val
      // this.showPopup = false
    },
    onRightIconClick() {
      this.showClear ? this.onClear() : this.onClick()
    },
    onClear() {
      this.otherOption = ''
      this.$emit('input', '')
      this.$emit('change', '')
    },
    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)
    },
    onCancel() {
      this.showPopup = false
      this.$emit('cancel', this)
    },
    onConfirm() {
      this.showPopup = false
      this.$emit('input', this.radio)
      this.$emit('change', this.radio)
    }
  }
}
</script>
<style lang="scss" scoped>
  .icon-circle{
    height: 20px;
    width: 20px;
    background: #3396FB;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    .icon-circle_inside{
      background: #fff;
      height: 8px;
      width: 8px;
      border-radius: 50%;
    }
  }
</style>
