<template>
  <div
    :class="{
      'drip-switch__outer': true,
      'is-single': single
    }"
    @click.stop="disabled ? '' : changeStatus()">
    <div :class="{'is-check': isCheck}">
      <span :class="{
        'drip-switch__bkg': true,
        'is-disabled': disabled
      }">
        <span :class="b([
          single && item.value ? type : '',
          'tip'
          ])"
          v-for="(item, index) in currentData"
          :key="index" v-text="item.name">
        </span>
        <span
          v-if="!single"
          :class="b([
            'button',
            isCheck ? 'is-active' : '',
            !single ? type : '',
          ])"
          v-text="currentContent">
        </span>
        <span
          v-else
          :class="{
            'drip-switch--button': true,
            'is-active': isCheck
          }">
        </span>
      </span>
    </div>
  </div>
</template>

<script>
import create from '../utils/create';

export default create({
  name: 'switch',

  props: {
    // true与false的值
    data: {
      type: Array,
      default: function () {
        return [{
          name: '',
          value: true
        }, {
          name: '',
          value: false
        }]
      }
    },
    // 绑定的值
    value: {
      type: [String, Number, Boolean, Object],
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否只显示一个值
    single: {
      type: Boolean,
      default: false
    },
    // 样式
    type: {
      type: String,
      default: 'primary'
    }
  },
  data () {
    return {
      // 是否选中状态
      isCheck: !this.value,
      // true与false的值
      currentData: this.data,
      // 选中的value
      currentValue: this.value,
      // 显示选中的值
      currentContent: ''
    }
  },
  mounted () {
    this.data.forEach(item => {
      if (item.value === this.value) {
        this.currentContent = item.name
      }
    })
  },
  methods: {
    // 改变状态
    changeStatus () {
      this.isCheck = !this.isCheck
      if (this.isCheck) {
        this.currentValue = this.currentData[1].value
        this.currentContent = this.currentData[1].name
      } else {
        this.currentValue = this.currentData[0].value
        this.currentContent = this.currentData[0].name
      }
      this.$emit('changed', {currentValue: this.currentValue, currentName: this.currentContent})
    }
  }
});
</script>
