<template>
  <div :class="classes">
    <slot></slot>
  </div>
</template>

<script>
import { oneOf } from "../../utils/assist.js";
import { findComponentsDownward } from "../../utils/assist.js";
import castError from "../../utils/castError.js";
import Emitter from '../../mixins/emitter.js'

const prefixCls = "lion-btn-group";

export default {
  name: "LionButtonGroup",
  mixins: [ Emitter ],
  data() {
    return {};
  },
  props: {
    effect: {
      validator(value) {
        return oneOf(value, ["opt", "opt-simple"]);
      },
      default: "opt"
    },
    direction: {
      validator(value) {
        return oneOf(value, ["crosswise", "vertical"]);
      },
      default: "crosswise"
    },
    // 默认有选中状态
    active:{
        type: [Number, String],
        default: ''
    },
    special: {
        type: Boolean,
        default: false
    }
  },
  computed: {
    classes() {
      return [
        `${prefixCls}`,
        {
          [`${prefixCls}-${this.effect}`]: !!this.effect && !this.special,
          [`${prefixCls}-special`]: this.special,
          [`${prefixCls}-${this.direction}`]: !!this.direction
        }
      ];
    }
  },
  methods: {
    // 按钮选中时候状态改变
    activeItemButton(opt) {
      if (!opt._e) return false;
      let comButtons = findComponentsDownward(this, "LionButton");
      let othButtons = comButtons.filter(item => item._uid !== opt._this._uid);
      othButtons.map((item) => {
          let _el = item.$el;
          _el.classList.remove('lion-btn-group-opt-active'); 
      })

      let _ele = opt._e.path[1];
      _ele.classList.add(`${prefixCls}-opt-active`);
    },
    // 默认选中状态
    activeHandle() {
        let comButtons = findComponentsDownward(this, "LionButton");
        this.active && comButtons[this.active].$el.classList.add('lion-btn-group-opt-active')
    },
    // 按钮向外暴露click事件，并获得button子组件的value值
    changeButton(el) {
        if(!el) return false;
        if(!el.value) {
            castError.error('[Warn]Value on a component is mandatory');
            return false;
        }
        this.$emit('change', el.value)
    }
  },
  mounted() {
    // 获得子元素触发的click事件
    this.$on("buttonClick", (opt) => {
      this.activeItemButton(opt);
    });
    this.$on("changeButtonHandle", el => {
        this.changeButton(el)
    })
    this.activeHandle();
  }
};
</script>

