<template>
  <li
    :class="{
      'mm-select-dropdown-menu-item--selected': selected,
      'mm-select-dropdown-menu-item--disabled': disabled,
      'mm-select-dropdown-menu-item--hover': hover,
    }"
    class="mm-select-dropdown-menu-item"
    @mouseenter="hoverItem"
    @click.stop="clickHandler">
    <ui-checkbox
      v-if="multiple"
      :checked="selected"
      :readonly="readonly"
      :disabled="disabled"
      class="mm-select-dropdown-menu-item-checkbox"
      @click.native.stop
      @change="selectHandler">
    </ui-checkbox>
    <slot>
      <span
        :title="label || value"
        class="mm-select-dropdown-menu-item-content">
        {{ label || value }}
      </span>
    </slot>
  </li>
</template>
<script>
import isObject from "lodash/isObject"
import get from "lodash/get"
import Checkbox from "../checkbox"
export default {
  components: {
    "ui-checkbox": Checkbox,
  },
  props: {
    label: {
      type: [String, Number],
    },
    value: null,
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  inject: {
    select: {
      from: "mm-select",
      default: null,
    },
  },
  computed: {
    readonly() {
      if (this.selected && !this.select.mayAdd) {
        return false
      }
      return !this.select.mayAdd
    },

    isObject() {
      return isObject(this.value)
    },

    multiple() {
      return this.select && this.select.multiple
    },

    selected() {
      if (!this.multiple) {
        return this.isEqual(this.value, this.select.valueList[0])
      } else {
        return this.contains(this.select.valueList)
      }
    },
    hover() {
      const valueKey = this.select.valueKey
      return this.isEqual(this.value, get(this.select.hoverOption, valueKey))
    },
  },
  methods: {
    clickHandler(e) {
      this.selectOption(e)
    },
    selectHandler(event, value) {
      this.selectOption(event, value)
    },
    selectOption(e) {
      if (!this.disabled) {
        if (this.select) {
          this.select.handleSelect(this.value, e)
        }
      }
    },

    isEqual(a, b) {
      if (!this.isObject) {
        return a === b
      } else {
        const valueKey = this.select.valueKey
        return get(a, valueKey) === get(b, valueKey)
      }
    },
    contains(arr = [], target = this.value) {
      if (!this.isObject) {
        return arr.indexOf(target) > -1
      } else {
        const valueKey = this.select.valueKey
        return arr.some(item => {
          return get(item, valueKey) === get(target, valueKey)
        })
      }
    },
    hoverItem() {
      if (!this.disabled) {
        const valueKey = this.select.valueKey
        const valueList = this.select.flattenOptions.map(item => item[valueKey])
        this.select.hoverIndex = valueList.indexOf(this.value)
      }
    },
  },
}
</script>
