<template>
  <div class="lanaya-select" :style="widthStyle" @click="clickMe">
    <span class="lanaya-select__placeholder" v-show="showPlaceholder">{{placeholder}}</span>
    <span class="lanaya-select__inner" v-show="!showPlaceholder">{{selectedItemLabel}}</span>
    <span class="lanaya-select__caret" :class="isDropClass"></span>
  </div>
</template>

<script>
import { DropList } from './drop';

export default {
  name: 'LSelect',
  props: {
    filter: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    width: {
      type: String,
      default: '100%'
    },
    value: null,
    format: {
      type: Object,
      default: function () {
        return {
          label: 'label',
          value: 'id'
        };
      }
    },
    options: {
      type: Array,
      default: function () {
        return [];
      }
    }
  },
  data () {
    return {
      selectedItem: null,
      isDrop: false
    };
  },
  computed: {
    showPlaceholder () {
      return !this.selectedItem;
    },
    widthStyle () {
      return {
        width: this.width
      };
    },
    selectedItemLabel () {
      return this.selectedItem && this.selectedItem[this.format.label];
    },
    isDropClass () {
      return this.isDrop ? 'is-drop' : '';
    }
  },
  watch: {
    value (newValue) {
      this.selectedItem = this.options.find(op => {
        return op[this.format.value] === newValue;
      });
    }
  },
  methods: {
    clickMe () {
      this.isDrop = !this.isDrop;
      if (this.isDrop) {
        DropList.createDrop({
          options: this.options,
          format: this.format,
          value: this.value,
          filter: this.filter
        }, this);
      } else {
        DropList.destroyDrop();
      }
    }
  },
  mounted () {
    this.selectedItem = this.options.find(op => {
      return op[this.format.value] === this.value;
    });
  },
  beforeCreate () {
    this.$on('selectedOption', (op) => {
      let currentValue = this.selectedItem && this.selectedItem[this.format.value];
      if (currentValue !== op[this.format.value]) {
        this.selectedItem = op;
        this.$emit('input', op[this.format.value]);
        this.$emit('change', op[this.format.value], op);
      }
    });
  }
};
</script>
