<template>
  <l-label @click="click" :arrow="!readonly" :required="required" :title="title">
    {{ display || displayPlaceholder }}
    <l-modal
      v-if="modal"
      @ok="confirm"
      @cancel="cancel"
      @checkboxChange="checkboxChange"
      :checkbox="innerChecked"
      :value="modalOpen"
      :range="range"
      :readonly="readonly"
      type="checkbox"
    />
  </l-label>
</template>

<script>
export default {
  name: 'l-checkbox-picker',

  props: {
    value: {},
    range: { default: () => [] },
    title: {},
    required: {},
    placeholder: {},
    readonly: {}
  },

  data() {
    return {
      modal: false,
      modalOpen: false,
      innerChecked: this.value || []
    }
  },

  methods: {
    click() {
      if (this.readonly || this.modal || this.modalOpen) {
        return
      }

      this.innerChecked = this.value
      this.modal = true
      setTimeout(() => {
        this.modalOpen = true
        uni.$emit('modal', true)
        this.$emit('open')
      }, 300)
    },

    checkboxChange(newVal) {
      this.innerChecked = newVal
    },

    confirm() {
      this.modalOpen = false
      setTimeout(() => {
        this.modal = false
        this.$emit('input', this.innerChecked)
        this.$emit('change', this.innerChecked)
        uni.$emit('modal', false)
        this.$emit('close')
      }, 300)
    },

    cancel() {
      this.modalOpen = false
      setTimeout(() => {
        this.modal = false
        uni.$emit('modal', false)
        this.$emit('close')
      }, 300)
    }
  },

  computed: {
    display() {
      if (this.value.length <= 0) {
        return null
      }

      if (!this.objMode) {
        return this.value.join('，')
      }

      return this.value
        .reduce((a, b) => {
          const selected = this.range.find(t => t.value === b)
          return selected ? a.concat(selected.text) : a
        }, [])
        .join('，')
    },

    displayPlaceholder() {
      if (this.readonly) {
        return ''
      }

      if (this.placeholder) {
        return this.placeholder
      }

      return this.title ? `请选择${this.title}` : '请选择…'
    },

    objMode() {
      return typeof this.range[0] === 'object'
    }
  }
}
</script>
