<template>
  <section :class="disabled ? 'vux-checklist-disabled' : ''">
    <div
      v-show="title"
      class="weui_cells_title"
    >
      {{ title }}
    </div>
    <slot name="after-title" />
    <div class="weui_cells weui_cells_checkbox">
      <label
        v-for="(one, index) in currentOptions"
        :key="one"
        class="weui_cell weui_check_label"
        :class="{'vux-checklist-label-left': labelPosition === 'left'}"
        :for="`checkbox_${uuid}_${index}`"
      >
        <div class="weui_cell_hd">
          <input
            :id="disabled ? '' : `checkbox_${uuid}_${index}`"
            v-model="currentValue"
            type="checkbox"
            class="weui_check"
            :name="`vux-checkbox-${uuid}`"
            :value="getKey(one)"
            :disabled="isDisabled(getKey(one))"
          >
          <i class="weui_icon_checked" />
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <p>{{ getValue(one) }}</p>
          <inline-desc v-if="getInlineDesc(one)">{{ getInlineDesc(one) }}</inline-desc>
        </div>
      </label>
    </div>
    <tip v-show="!validy && dirty">
      <icon
        type="warn"
        class="icon_small"
      />{{ error }}
    </tip>
  </section>
</template>
<script>
import Base from '../../libs/base'
import Tip from '../tip'
import Icon from '../icon'
import InlineDesc from '../inline-desc'
import { getValue, getLabels, getKey, getInlineDesc } from './object-filter'
import shuffle from 'array-shuffle'

export default {
  components: {
    Tip,
    Icon,
    InlineDesc
  },
  filters: {
    getValue,
    getKey
  },
  mixins: [Base],
  props: {
    title: String,
    required: {
      type: Boolean,
      default: false
    },
    options: {
      type: Array,
      required: true
    },
    value: {
      type: Array,
      default: () => []
    },
    max: Number,
    min: Number,
    fillMode: Boolean,
    randomOrder: Boolean,
    checkDisabled: {
      type: Boolean,
      default: true
    },
    labelPosition: {
      type: String,
      default: 'right'
    },
    disabled: Boolean
  },
  data() {
    return {
      currentValue: [],
      currentOptions: this.options
    }
  },
  computed: {
    _total() {
      return this.fillMode ? (this.options.length + 1) : this.options.length
    },
    _min() {
      if (!this.required) {
        return 0
      }
      if (this.min) {
        if (this.min < 0) {
          return 1
        }
        if (this.min >= this._total) {
          return this._total
        }
        return this.min
      } else {
        return 1
      }
    },
    _max() {
      if (!this.required) {
        return this._total
      }
      if (this.max) {
        if (this.max > this._total) {
          return this._total
        }
        return this.max
      } else {
        return this._total
      }
    },
    validy() {
      return this.currentValue.length >= this._min && this.currentValue.length <= this._max
    },
    error() {
      let err = []
      if (this.currentValue.length < this._min) {
        err.push(`最少要选择${this._min}个哦`)
      }
      if (this.currentValue.length > this._max) {
        err.push(`最多只能选择${this._max}个哦`)
      }
      return err
    }
  },
  watch: {
    value(newVal) {
      if (JSON.stringify(newVal) !== JSON.stringify(this.currentValue)) {
        this.currentValue = newVal
      }
    },
    options(val) {
      this.currentOptions = val
    },
    currentValue(newVal) {
      const val = pure(newVal)
      this.$emit('on-change', val)
      this.$emit('input', val, getLabels(this.options, val))
      let err = {}
      if (this._min) {
        if (this.required) {
          if (this.currentValue.length < this._min) {
            err = {
              min: this._min
            }
          }
        } else {
          if (this.currentValue.length && this.currentValue.length < this._min) {
            err = {
              min: this._min
            }
          }
        }
      }
      if (!this.validy && this.dirty && Object.keys(err).length) {
        this.$emit('on-error', err)
      } else {
        this.$emit('on-clear-error')
      }
    }
  },
  created() {
    // this.handleChangeEvent = true
    // if (this.randomOrder) {
    //   this.options = shuffle(this.options)
    // }
    this.handleChangeEvent = true
    if (this.value) {
      this.currentValue = this.value
    }
    if (this.randomOrder) {
      this.currentOptions = shuffle(this.options)
    } else {
      this.currentOptions = this.options
    }
  },
  methods: {
    getValue,
    getKey,
    getInlineDesc,
    getFullValue() {
      const labels = getLabels(this.options, this.value)
      return this.currentValue.map((one, index) => {
        return {
          value: one,
          label: labels[index]
        }
      })
    },
    isDisabled(key) {
      if (!this.checkDisabled) {
        return false
      }
      if (this._max > 1) {
        return this.currentValue.indexOf(key) === -1 && this.currentValue.length === this._max
      }
      return false
    }
  }
}

function pure(obj) {
  return JSON.parse(JSON.stringify(obj))
}
</script>
