<template>
  <div
    class="weui_cell"
    :class="{'weui_select_after':title, 'weui_cell_select':!readonly}"
  >
    <div
      v-if="title"
      class="weui_cell_hd"
      :class="{'weui_cell_primary':readonly}"
    >
      <label
        for=""
        class="weui_label"
        :style="{width: $parent.labelWidth +'rem', textAlign: $parent.labelAlign, marginRight: $parent.labelMarginRight}"
      >{{ title }}</label>
    </div>
    <div
      v-if="!readonly"
      class="weui_cell_bd weui_cell_primary"
    >
      <select
        v-model="currentValue"
        class="weui_select"
        :class="classes"
        :name="name"
        :style="{direction: direction}"
      >
        <option
          v-if="placeholder"
          value=""
          :selected="placeholder && !currentValue"
        >
          {{ placeholder }}
        </option>
        <option
          v-for="one in processOptions"
          :key="one.value"
          :value="one.key"
        >
          {{ one.value }}
        </option>
      </select>
    </div>
    <div
      v-else
      class="weui_cell_ft"
    >
      {{ currentValue | findByKey(processOptions) }}
    </div>
  </div>
</template>

<script>
import find from 'array-find'

const findByKey = function (key, options) {
  const _rs = find(options, function (item) {
    return item.key === key
  })
  return _rs ? _rs.value : key
}

export default {
  filters: {
    findByKey
  },
  props: {
    title: String,
    direction: String,
    options: {
      type: Array,
      required: true
    },
    name: String,
    placeholder: String,
    readonly: Boolean,
    value: {
      type: [String, Number, Boolean],
      default: ''
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  computed: {
    processOptions () {
      if (this.options.length && {}.hasOwnProperty.call(this.options[0], 'key')) {
        return this.options
      } else {
        return this.options.map(function (item) {
          return {
            key: item,
            value: item
          }
        })
      }
    },
    classes () {
      return {
        'vux-selector-no-padding': !this.title,
        'cvux-selector-placeholder': this.currentValue === ''
      }
    }
  },
  watch: {
    value (newValue) {
      this.currentValue = newValue
    },
    currentValue (newValue) {
      this.$emit('input', newValue)
      this.$emit('on-change', newValue)
    }
  }
}
</script>
