<template>
  <div class="mc-dropdown" 
    :class="[
    type ? 'mc-dropdown_' + type : 'mc-dropdown_default',
    {'is-disabled': disabled}
    ]"
    :name="name"
    @click="showOption"
  >
    <i :class="'mc-icon-' + icon" v-if="icon"></i>
    <span><slot></slot></span>
    <transition v-if="!disabled" name="slideDown">
      <ul class="mc-dropdown_content" v-show="show">
        <li 
          @click="setValue(option)"
          @click.stop="showOption"
          v-for="option in options"
          :class="{
            'is-selected': option.selected,
            'is-disabled': option.disabled,
            'is-line': option.line
          }">{{option.label}}</li>
      </ul>
    </transition>
  </div>
</template>

<script>
export default {
  props: {
    options:{
      type: Array
    },
    value:  {
      type: String,
      default: ''
    },
    label:   {
      type: String,
      default: ''
    },
    selected:  {
      type: Boolean,
      default: false
    },
    disabled:{
      type: Boolean,
      default: false
    },
    line:{
      type: Boolean,
      default: false
    },
    onClick: {
      type: Function,
      default() {},
    },
    icon: {
      type: String,
      default: ''
    },
    name: String,
    type: String,
    disabled: Boolean
  },
  data () {
    return {
      vals: [],
      labs: [],
      show: false,
    }
  },
  mounted (e) {
    document.addEventListener('click', (e) => {
      if (!this.$el.contains(e.target)) this.show = false;
    });
    this.setDisplayValue(this.options);
  },
  methods: {
    showOption(e) {
      if (this.disabled) {return};
      this.show = !this.show;
    },
    setValue (option) {
      if (this.disabled) {return};
      if (option.disabled) {
        this.show = false;
        return
      };
        // 取消选中
      this.options.forEach(op => {
        op.selected = false
      })
      // 选中
      option.selected = true
      // 赋值
      this.labs = option.label
      this.vals = option.value
      this.$emit('change', this.vals, this.labs);
    },
    setDisplayValue (options) {
      const selected = options.filter(option => {
          return option.selected
      });
      // console.log("set1:"+JSON.stringify(selected));
      for (var i = selected.length - 1; i >= 0; i--) {
          this.vals.push(selected[i].label);
        }
    },
  }
}
</script>