<template>
  <ul :class='classes'>
    <slot></slot>
  </ul>
</template>

<script>
const prefixCls = 'co-collapse';
/**
 * co-collapse
 * @module components/collapse
 * @desc 折叠面板
 * @param { Array | String } [value] - 当前激活面板的 name，可使用 v-model 双向绑定
 * @param { Boolean } [accordion=false] - 是否开启手风琴模式（每次至多展开一个面板）
 * @param { Function } [on-change] - 事件，切换面板
 * @example
 * <co-collapse v-model='showPanelName' accordion>
 *   <co-panel name='1'></co-panel>
 *   <co-panel name='2'></co-panel>
 *   <co-panel name='3'></co-panel>
 * </co-collapse>
 */
export default {
  name: 'co-collapse',
  props: {
    accordion: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Array, String]
    }
  },
  data() {
    return {
      currentValue: this.value
    };
  },
  computed: {
    classes() {
      return `${prefixCls}`;
    }
  },
  mounted() {
    this.setActive();
  },
  methods: {
    setActive() {
      const activeKey = this.getActiveKey();

      this.$children.forEach((child, index) => {
        const name = child.name || index.toString();
        let isActive = false;

        if (self.accordion) {
          isActive = activeKey === name;
        } else {
          isActive = activeKey.indexOf(name) > -1;
        }

        child.isActive = isActive;
        child.index = index;
      });
    },
    getActiveKey() {
      let activeKey = this.currentValue || [];
      const accordion = this.accordion;

      if (!Array.isArray(activeKey)) {
        activeKey = [activeKey];
      }

      if (accordion && activeKey.length > 1) {
        activeKey = [activeKey[0]];
      }

      for (let i = 0; i < activeKey.length; i++) {
        activeKey[i] = activeKey[i].toString();
      }

      return activeKey;
    },
    toggle(data) {
      const name = data.name.toString();
      let newActiveKey = [];

      if (this.accordion) {
        if (!data.isActive) {
          newActiveKey.push(name);
        }
      } else {
        let activeKey = this.getActiveKey();
        const nameIndex = activeKey.indexOf(name);

        if (data.isActive) {
          if (nameIndex > -1) {
            activeKey.splice(nameIndex, 1);
          }
        } else {
          if (nameIndex < 0) {
            activeKey.push(name);
          }
        }

        newActiveKey = activeKey;
      }

      this.currentValue = newActiveKey;
      this.$emit('input', newActiveKey);
      this.$emit('on-change', newActiveKey);
    }
  },
  watch: {
    value(val) {
      this.currentValue = val;
    },
    currentValue() {
      this.setActive();
    }
  }
};
</script>
<style>
  @component-namespace co {
    @component collapse {
      background-color: #fff;
      border-radius: 0.15rem;
      border: 0.05rem solid #dddee1;
    }
  }
</style>
