<template>
  <div class="weui_cells_radio">
    <label
      v-for="(one, index) in options"
      :key="one"
      class="weui_cell weui_cell_radio weui_check_label"
      :for="'radio_'+uuid+'_'+index"
    >
      <div class="weui_cell_bd weui_cell_primary">
        <p>
          {{ one | getValue }}
          <slot :one="one" />
        </p>
      </div>
      <div class="weui_cell_ft">
        <input
          :id="'radio_'+uuid+'_'+index"
          v-model="currentValue"
          type="radio"
          class="weui_check"
          :value="one | getKey"
        >
        <span class="weui_icon_checked" />
      </div>
    </label>
    <div
      v-show="fillMode"
      class="weui_cell"
    >
      <div class="weui_cell_hd">
        <label
          for=""
          class="weui_label"
        >{{ fillLabel }}</label>
      </div>
      <div class="weui_cell_bd weui_cell_primary">
        <input
          v-model="fillValue"
          class="weui_input needsclick"
          type="text"
          :placeholder="fillPlaceholder"
          @blur="isFocus=false"
          @focus="onFocus()"
        >
      </div>
      <div
        v-show="value==='' && !isFocus"
        class="weui_cell_ft"
      >
        <i class="weui_icon_warn" />
      </div>
    </div>
  </div>
</template>

<script>
import Base from '../../libs/base'
import { getValue, getKey } from '../checklist/object-filter'

export default {
  filters: {
    getValue,
    getKey
  },
  mixins: [Base],
  props: {
    options: {
      type: Array,
      required: true
    },
    value: [String, Number],
    fillMode: {
      type: Boolean,
      default: false
    },
    fillPlaceholder: {
      type: String,
      default: '其他'
    },
    fillLabel: {
      type: String,
      default: '其他'
    }
  },
  data () {
    return {
      fillValue: '',
      isFocus: false,
      currentValue: this.value
    }
  },
  watch: {
    currentValue (newVal) {
      var isOption = contains(this.options, newVal)
      if (newVal !== '' && isOption) {
        this.fillValue = ''
      }
      this.$emit('on-change', newVal)
      this.$emit('input', newVal)
    },
    value (newVal) {
      this.currentValue = newVal
    },
    fillValue (newVal) {
      if (this.fillMode && this.isFocus) {
        this.currentValue = newVal
      }
    }
  },
  created () {
    this.handleChangeEvent = true
  },
  methods: {
    onFocus () {
      this.currentValue = this.fillValue || ''
      this.isFocus = true
    }
  }
}

function contains (a, obj) {
  var i = a.length
  while (i--) {
    if (a[i] === obj) {
      return true
    }
  }
  return false
}
</script>
