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

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

export default {
  name: 'PsMSelect',
  props: {
    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) {
        MDropList.createDrop({
          options: this.options,
          format: this.format,
          value: this.value
        }, this);
      } else {
        MDropList.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>
