<template>
  <div class="ai-collapse-item"
    :class="{'is-active': isActive, 'is-disabled': disabled }">
    <div
      role="tab"
      :aria-expanded="isActive"
      :aria-controls="`ai-collapse-content-${id}`"
      :aria-describedby ="`ai-collapse-content-${id}`"
    >
      <div
        class="ai-collapse-item__header"
        @click="handleHeaderClick"
        role="button"
        :id="`ai-collapse-head-${id}`"
        :tabindex="disabled ? undefined : 0"
        @keyup.space.enter.stop="handleEnterClick"
        :class="{
          'focusing': focusing,
          'is-active': isActive
        }"
        @focus="handleFocus"
        @blur="focusing = false"
      >
        <slot name="title">{{title}}</slot>
        <i
          class="ai-collapse-item__arrow ai-icon-arrow-right"
          :class="{'is-active': isActive}">
        </i>
      </div>
    </div>
    <ai-collapse-transition>
      <div
        class="ai-collapse-item__wrap"
        v-show="isActive"
        role="tabpanel"
        :aria-hidden="!isActive"
        :aria-labelledby="`ai-collapse-head-${id}`"
        :id="`ai-collapse-content-${id}`"
      >
        <div class="ai-collapse-item__content">
          <slot></slot>
        </div>
      </div>
    </ai-collapse-transition>
  </div>
</template>
<script>
  import ElCollapseTransition from 'ai-vue/src/transitions/collapse-transition';
  import Emitter from 'ai-vue/src/mixins/emitter';
  import { generateId } from 'ai-vue/src/utils/util';

  export default {
    name: 'AiCollapseItem',

    componentName: 'AiCollapseItem',

    mixins: [Emitter],

    components: { ElCollapseTransition },

    data() {
      return {
        contentWrapStyle: {
          height: 'auto',
          display: 'block'
        },
        contentHeight: 0,
        focusing: false,
        isClick: false,
        id: generateId()
      };
    },

    inject: ['collapse'],

    props: {
      title: String,
      name: {
        type: [String, Number],
        default() {
          return this._uid;
        }
      },
      disabled: Boolean
    },

    computed: {
      isActive() {
        return this.collapse.activeNames.indexOf(this.name) > -1;
      }
    },

    methods: {
      handleFocus() {
        setTimeout(() => {
          if (!this.isClick) {
            this.focusing = true;
          } else {
            this.isClick = false;
          }
        }, 50);
      },
      handleHeaderClick() {
        if (this.disabled) return;
        this.dispatch('AiCollapse', 'item-click', this);
        this.focusing = false;
        this.isClick = true;
      },
      handleEnterClick() {
        this.dispatch('AiCollapse', 'item-click', this);
      }
    }
  };
</script>
