<template>
  <fdc-popup v-model="visible" position="bottom" class="fdc-select__wrapper">
    <div class="popup-header__wrapper">
      <span class="popup-header__cancel" @click="visible = false;$emit('cancel')">{{ cancelText }}</span>
      <span class="popup-header__title">{{title}}</span>
      <span class="popup-header__confirm" @click="confirm">{{ confirmText }}</span>
    </div>
    <slot></slot>
    <fdc-picker :slots="actualSlotData" :value-key="'label'" @change="onChange" :visible-item-count="visibleItemCount" class="mint-datetime-picker" ref="picker"></fdc-picker>
  </fdc-popup>
</template>

<style lang="scss">
@import "../../../src/style/var.css"; //选择弹出样式

.fdc {
  &-select{
    &__wrapper{
      width: 100%
    }
  }
}
</style>

<script type="text/babel">
import picker from 'fdc-ui/packages/picker/index.js';
import popup from 'fdc-ui/packages/popup/index.js';
if (process.env.NODE_ENV === 'component') {
  require('fdc-ui/packages/picker/style.css');
  require('fdc-ui/packages/popup/style.css');
}
export default {
  name: 'fdc-select',

  props: {
    title: {
      type: String,
      default: ''
    },
    slots: {
      type: Array,
      default: []
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    confirmText: {
      type: String,
      default: '确定'
    },
    visibleItemCount: {
      type: Number,
      default: 5
    },
    value: {
      type: Array,
      default: []
    }
  },

  data() {
    return {
      visible: false,
      tempSelectData: []
    };
  },
  computed: {
    actualSlotData() {
      for (let i = 0, count = 0; i < this.slots.length; i++) {
        let slotItem = this.slots[ i ];
        if (slotItem.divider) {
          count++;
        } else {
          let slotIndex = slotItem.values.map(x=>x.value).indexOf(this.value[i - count]);
          slotItem.defaultIndex = slotIndex === -1 ? 0 : slotIndex;
        }
      }
      return this.slots;
    }
  },
  components: {
    'fdc-picker': picker,
    'fdc-popup': popup
  },

  methods: {
    open() {
      this.visible = true;
    },

    close() {
      this.visible = false;
    },

    confirm() {
      this.visible = false;
      this.$emit('input', this.tempSelectData);
    },
    onChange(ref, data) {
      this.tempSelectData = JSON.parse(JSON.stringify(data)).map(x=>x.value);
      this.$emit('change', ref, this.tempSelectData);
    }
  },

  mounted() {
  }
};
</script>
