<template>
  <div>
    <!--co-buttons-fan样式-->
    <div v-if="cls === 'co-buttons-fan'">
      <div :class="cls">
        <a v-for="(row, index) in rows"  class="co-buttons-fan-button" :class="[{'active': row.id === currentActive}, row.cls]"
           @click="clickFn(row, index, $event)"><div v-text="row.label"></div></a>
      </div>
    </div>
    <!--co-buttons-tab样式-->
    <div v-else-if="cls === 'co-buttons-tab'">
      <div :class="cls">
        <a v-for="(row, index) in rows"  class="co-buttons-tab-button" :class="[{'active': row.id === currentActive}, row.cls]"
           @click="clickFn(row, index, $event)"><div v-text="row.label"></div></a>
      </div>
    </div>
    <!--co-buttons-row样式-->
    <div v-else-if="cls === 'co-buttons-row'">
      <div :class="cls">
        <a v-for="(row, index) in rows"  class="co-buttons-row-button" :class="[{'active': row.id === currentActive}, row.cls]"
           @click="clickFn(row, index, $event)"><div v-text="row.label"></div></a>
      </div>
    </div>
    <div
            @touchstart="startDrag"
            @mousedown="startDrag"
            @touchmove="onDrag"
            @mousemove="onDrag"
            @mouseleave="endDrag"
            @touchend="endDrag"
            class="co-tab-container">

      <div
              ref="wrap"
              class="co-tab-container-wrap">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<style lang="css">
  @component-namespace co {
    @component tab-container {
      overflow: hidden;
      position: relative;

      @descendent wrap {
        display: flex;
      }

      .swipe-transition {
        transition: transform 150ms ease-in-out;
      }
    }
    @component buttons-fan{
      -webkit-align-self: center;
      align-self: center;
      display: -webkit-flex;
      display: flex;
      -webkit-box-lines: single;
      -moz-box-lines: single;
      -webkit-flex-wrap: nowrap;
      flex-wrap: nowrap;
      border-radius: 1.3rem;
      border: 0.1rem solid #e60000;
      background: none;
      background-color: #fff;


      @descendent button{
        width: 100%;
        height: 1.4rem;
        line-height: 1.5rem;
        -webkit-box-flex: 1;
        -ms-flex: 1;
        border: 0;
        border-bottom: 0.1rem solid transparent;
        border-radius: 0;
        padding: 0rem;
        font-size: 0.65rem;
        color: #e60000;
        text-align: center;

      &.active{
         color: #fff;
         background-color: #e60000;
         border-radius: 1rem;
         border: 0;
       }

      &:after{
         height: 0;
       }
      }
    }

    @component buttons-tab{
      z-index: 1;
      background: white;
      position: relative;
      -webkit-align-self: center;
      -ms-flex-item-align: center;
      align-self: center;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-lines: single;
      -ms-flex-wrap: nowrap;
      flex-wrap: nowrap;
      padding: 0.3rem;
      background-color: #fff;

      @descendent button{
        height: 2rem;
        line-height: 1.5rem;
        padding: 0;
        font-size: 0.65rem;
        text-align: center;
        width: 100%;
        -webkit-box-flex: 1;
        border-bottom: 0.1rem solid transparent;
        border-radius: 0;
        text-decoration: none;
        text-align: center;
        display: block;
        box-sizing: border-box;
        -webkit-appearance: none;
        white-space: nowrap;
        position: relative;
        text-overflow: ellipsis;
        font-family: inherit;
        cursor: pointer;
        margin: 0 9%;

      &.active {
           color: #5FA0FF;
           border-color: #5FA0FF !important;
         }
      }

      div {
        margin: 0.25rem 0rem;
        height: 1.5rem;
      }

    }
    @component buttons-row{
      -webkit-align-self: center;
      align-self: center;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
      -webkit-box-lines: single;
      -moz-box-lines: single;
      -webkit-flex-wrap: nowrap;
      flex-wrap: nowrap;
      padding: 0.3rem;
      background-color: #fff;

      @descendent button{
        border-radius: 0 0 0 0;
        margin-left: -0.05rem;
        width: 100%;
        -webkit-box-flex: 1;
        -ms-flex: 1;
        border-color: #0894ec;
        color: #0894ec;
        text-align: center;
        height: 1.35rem;
        text-decoration: none;
        text-align: center;
        display: block;
        line-height: 1.25rem;
        box-sizing: border-box;
        -webkit-appearance: none;
        background: none;
        padding: 0 0.5rem;
        margin: 0;
        height: 1.35rem;
        white-space: nowrap;
        position: relative;
        text-overflow: ellipsis;
        font-size: 0.7rem;
        font-family: inherit;
        cursor: pointer;
        border: 0.05rem solid #0894ec;
        margin-left: -0.05rem;


      &.active {
         background-color: #0894ec;
         color: white;
         z-index: 90;
       }
      &:last-child {
         border-radius: 0 0.25rem 0.25rem 0;
      }
      &:first-child {
         border-radius: 0.25rem 0 0 0.25rem;
         margin-left: 0;
         border-left-width: 0.05rem;
         border-left-style: solid;
      }
    }

    }
  }
</style>

<script>
import { once } from 'CoUI/src/utils/dom';
import arrayFindIndex from 'array-find-index';

/**
 * co-tab-container
 * @desc 面板，搭配 tab-container-item 使用
 * @module components/tab-container
 *
 * @param {number|string} [value] - 当前激活的 tabId
 *
 * @example
 * <co-tab-container v-model="selected">
 *   <co-tab-container-item id="1"> 内容A </co-tab-container-item>
 *   <co-tab-container-item id="2"> 内容B </co-tab-container-item>
 *   <co-tab-container-item id="3"> 内容C </co-tab-container-item>
 * </co-tab-container>
 */
export default {
  name: 'co-tab-container',

  props: {
    value: {},
    swipeable: Boolean,
    cls: String,
    parentRows: Array
  },

  data() {
    return {
      start: { x: 0, y: 0 },
      swiping: false,
      activeItems: [],
      pageWidth: 0,
      currentActive: this.value,
      rows: this.parentRows
    };
  },

  watch: {
    value(val) {
      this.currentActive = val;
    },

    currentActive(val, oldValue) {
      this.$emit('input', val);
      if (!this.swipeable) return;
      const lastIndex = arrayFindIndex(this.$children,
        item => item.id === oldValue);
      this.swipeLeaveTransition(lastIndex);
    }
  },

  mounted() {
    if (!this.swipeable) return;

    this.wrap = this.$refs.wrap;
    this.pageWidth = this.wrap.clientWidth;
    this.limitWidth = this.pageWidth / 4;
  },

  methods: {
    /*
    * 点击tab触发tab切换事件，包括tab-container-item的切换
    * @param {Object} row  对应tab所绑定的对象
    * @param {Number} index 当前点击的索引值
    * @param {Object } $event 事件对象
    * */
    clickFn: function(row, index, $event) {
      let self = this;
      self.reset(index);
      row.active = 'active';
      self.currentActive = row.id;
    },
    /*
    * Tab切换及重置，向父级发送事件。
    * @param {Number} index 当前点击的索引值
    * */
    reset: function(index) {
      let self = this;
      let _data = self.rows;
      self.currentActive = index;
      // 重置tab样式，设置点击的样式。
      for (var i in _data) {
        _data[i].active = '';
      }
      self.rows[index].active = 'active';
      // 向父级发送点击改变事件。
      self.$emit('tabChange', index);

    },
    swipeLeaveTransition(lastIndex = 0) {
      if (typeof this.index !== 'number') {
        this.index = arrayFindIndex(this.$children,
          item => item.id === this.currentActive);
        this.swipeMove(-lastIndex * this.pageWidth);
      }

      setTimeout(() => {
        this.wrap.classList.add('swipe-transition');
        this.swipeMove(-this.index * this.pageWidth);

        once(this.wrap, 'webkitTransitionEnd', _ => {
          this.wrap.classList.remove('swipe-transition');
          this.wrap.style.webkitTransform = '';
          this.swiping = false;
          this.index = null;
        });
      }, 0);
    },

    swipeMove(offset) {
      this.wrap.style.webkitTransform = `translate3d(${offset}px, 0, 0)`;
      this.swiping = true;
    },

    startDrag(evt) {
      if (!this.swipeable) return;
      evt = evt.changedTouches ? evt.changedTouches[0] : evt;
      this.dragging = true;
      this.start.x = evt.pageX;
      this.start.y = evt.pageY;
    },

    onDrag(evt) {
      if (!this.dragging) return;
      let swiping;
      const e = evt.changedTouches ? evt.changedTouches[0] : evt;
      const offsetTop = e.pageY - this.start.y;
      const offsetLeft = e.pageX - this.start.x;
      const y = Math.abs(offsetTop);
      const x = Math.abs(offsetLeft);

      swiping = !(x < 5 || (x >= 5 && y >= x * 1.73));
      if (!swiping) return;
      evt.preventDefault();

      const len = this.$children.length - 1;
      const index = arrayFindIndex(this.$children,
        item => item.id === this.currentActive);
      const currentPageOffset = index * this.pageWidth;
      const offset = offsetLeft - currentPageOffset;
      const absOffset = Math.abs(offset);

      if (absOffset > len * this.pageWidth ||
          (offset > 0 && offset < this.pageWidth)) {
        this.swiping = false;
        return;
      }

      this.offsetLeft = offsetLeft;
      this.index = index;
      this.swipeMove(offset);
    },

    endDrag() {
      if (!this.swiping) return;

      const direction = this.offsetLeft > 0 ? -1 : 1;
      const isChange = Math.abs(this.offsetLeft) > this.limitWidth;

      if (isChange) {
        this.index += direction;
        const child = this.$children[this.index];
        if (child) {
          this.currentActive = child.id;
          return;
        }
      }

      this.swipeLeaveTransition();
    }
  }
};
</script>
