<template>
  <div class="qf-collapse">
    <slot></slot>
  </div>
</template>

<script>
  export default {
    name: 'QfCollapse',
    componentName: 'QfCollapse',
    props: {
      /**
       * 是否是手风琴式
       */
      accordion: Boolean,
      /**
       * value的类型可以是数组、字符串、数字，默认为空数组
       */
      value: {
        type: [Array, String, Number],
        default () {
          return [];
        }
      }
    },
    /**
     * 定义一个记录展开的item的activeNames
     */
    data () {
      return {
        activeNames: [].concat(this.value)
      };
    },
    /**
     * 定义一个服务，对外提供该组件的this指向
     * @returns {{collapse: props}}
     */
    provide () {
      return {
        collapse: this,
        sVue: this.sVue
      };
    },
    /**
     * 监听value的变化
     */
    watch: {
      value (value) {
        this.activeNames = [].concat(value);
      }
    },

    methods: {
      setActiveNames (activeNames) {
        activeNames = [].concat(activeNames);
        this.activeNames = activeNames;
      },
      handleItemClick (item) {
        if (this.accordion) {
          this.setActiveNames(
            (this.activeNames[0] || this.activeNames[0] === 0) &&
            this.activeNames[0] === item.name
              ? '' : item.name
          );
        } else {
          let activeNames = this.activeNames.slice(0);
          let index = activeNames.indexOf(item.name);

          if (index > -1) {
            activeNames.splice(index, 1);
          } else {
            activeNames.push(item.name);
          }
          this.setActiveNames(activeNames);
        }
      }
    }
  };
</script>
