<!-- CopyRight (C) 2017-2022 Alibaba Group Holding Limited. -->
<!-- Created by Tw93 on 17/07/28. -->
<!-- Updated by Tw93 on 17/11/16.-->

<template>
  <div class="lc-tab-page" :style="{ height: (tabPageHeight)+'px', backgroundColor:wrapBgColor }">
    <!-- 可滚动(支持图文) -->
    <scroller v-if="type=='scroll'"
      class="tab-title-list"
      ref="tab-title-list"
      :show-scrollbar="false"
      scroll-direction="horizontal"
      :data-spm="spmC"
      :style="{ backgroundColor: tabStyles.bgColor, height: (tabStyles.height)+'px',paddingLeft:tabStyles.leftOffset+'px' }">

      <div class="title-item"
           v-for="(v,index) in tabTitles"
           :key="index"
           :ref="'lc-tab-title-'+index"
           @click="setPage(index,v.url)"
           :style="{ width: tabStyles.width +'px', height: tabStyles.height +'px', backgroundColor: currentPage == index ? tabStyles.activeBgColor : tabStyles.bgColor }"
           :accessible="true"
           :aria-label="`${v.title?v.title:'标签'+index}`">

        <image :src="currentPage == index ? v.activeIcon : v.icon"
               v-if="titleType === 'icon' && !titleUseSlot && (v.icon || v.activeIcon) "
               :style="{ width: tabStyles.iconWidth + 'px', height:tabStyles.iconHeight+'px'}"></image>
        
        <div v-if="!v.icon && !v.activeIcon && !titleUseSlot" class="text-wrap" :style="{ width: tabStyles.activeBottomWidth+'px',height: tabStyles.height+'px'}">
          <text v-if="!titleUseSlot"
          :style="{ fontSize: tabStyles.fontSize+'px', fontWeight: (currentPage == index && tabStyles.isActiveTitleBold)? 'bold' : 'normal', color: currentPage == index ? tabStyles.activeTitleColor : tabStyles.titleColor, paddingLeft:tabStyles.textPaddingLeft+'px', paddingRight:tabStyles.textPaddingRight+'px'}"
          class="tab-text">{{v.title}}</text>
          <text v-if="v.tip" class="tab-tip" :style="tabtipStyle">{{v.tip}}</text>
        </div>

        <text v-if="(v.icon || v.activeIcon) && !titleUseSlot"
        :style="{ fontSize: tabStyles.fontSize+'px', fontWeight: (currentPage == index && tabStyles.isActiveTitleBold)? 'bold' : 'normal', color: currentPage == index ? tabStyles.activeTitleColor : tabStyles.titleColor, paddingLeft:tabStyles.textPaddingLeft+'px', paddingRight:tabStyles.textPaddingRight+'px'}"
        class="tab-text">{{v.title}}</text>

        
        <div class="border-bottom"
             v-if="tabStyles.hasActiveBottom && !titleUseSlot"
             :style="{ width: tabStyles.activeBottomWidth+'px', left: (tabStyles.width-tabStyles.activeBottomWidth)/2+'px', height: tabStyles.activeBottomHeight+'px', backgroundColor: currentPage == index ? tabStyles.activeBottomColor : ( tabStyles.bottomColor ? tabStyles.bottomColor :'transparent') }">
          

             </div>
            
        <slot :name="`tab-title-${index}`" v-if="titleUseSlot"></slot>
      </div>
       
    </scroller>
 
    <!-- 不可滚动(纯文字)-普通 -->
    <div v-if="type=='normal'"
      class="tab-title-list"
      ref="tab-title-list"
      :data-spm="spmC"
      :style="{ backgroundColor: tabStylesNormal.bgColor, height: (tabStylesNormal.height)+'px'}">

      <div
        v-for="(v,index) in tabTitles"
        :class="['title-item-normal', index!==0 && 'title-item-normal-border']"
        :key="index"
        :ref="'lc-tab-title-'+index"
        @click="setPage(index,v.url)"
        :style="{ height: tabStylesNormal.height +'px', backgroundColor: currentPage == index ? tabStylesNormal.activeBgColor : tabStylesNormal.bgColor }"
        :accessible="true"
        :aria-label="`${v.title?v.title:'标签'+index}`">

        <text
          v-if="!titleUseSlot"
          :style="{ fontSize: tabStylesNormal.fontSize+'px', fontWeight: (currentPage == index && tabStylesNormal.isActiveTitleBold)? 'bold' : 'normal', color: currentPage == index ? tabStylesNormal.activeTitleColor : tabStylesNormal.titleColor, paddingLeft: tabStylesNormal.textPaddingLeft+'px', paddingRight: tabStylesNormal.textPaddingRight+'px'}"
          class="tab-text">{{v.title}}</text>
      </div>
    </div>

    <!-- 不可滚动(纯文字)-卡片 -->
    <div v-if="type=='card'"
      class="tab-title-list-card"
      ref="tab-title-list"
      :data-spm="spmC"
      :style="{ backgroundColor: tabStylesCard.bgColor, height: (tabStylesCard.height)+'px',paddingTop: tabStylesCard.topOffset+'px', paddingBottom: tabStylesCard.bottomOffset+'px', paddingLeft: tabStylesCard.leftOffset+'px', paddingRight: tabStylesCard.rightOffset+'px' }">
      <div class="title-item-card-wrap">
        <div
           v-for="(v,index) in tabTitles"        
          :class="['title-item-card', index!==0 && 'title-item-card-border']"
           :key="index"
           :ref="'lc-tab-title-'+index"
           @click="setPage(index,v.url)"
           :style="{  backgroundColor: currentPage == index ? tabStylesCard.activeBgColor : tabStylesCard.bgColor }"
           :accessible="true"
           :aria-label="`${v.title?v.title:'标签'+index}`">

          <text
            v-if="!titleUseSlot"
            :style="{ fontSize: tabStylesCard.fontSize+'px', fontWeight: (currentPage == index && tabStylesCard.isActiveTitleBold)? 'bold' : 'normal', color: currentPage == index ? tabStylesCard.activeTitleColor : tabStylesCard.titleColor, paddingLeft: tabStylesCard.textPaddingLeft+'px', paddingRight: tabStylesCard.textPaddingRight+'px'}"
            class="tab-text">{{v.title}}</text>
        </div>
      </div>
      
    </div>

    <div v-if="showBottomLine" class="bottom_line_height" :style="{backgroundColor:bottomLineColor }" ></div>

    <div class="tab-page-wrap"
         ref="tab-page-wrap"
         @panstart="_onTouchStart"
         @panmove="_onTouchMove"
         @panend="_onTouchEnd"
         :prevent-move-event="true"
         @horizontalpan="startHandler"
         :style="{ height: (tabPageHeight-tabStyles.height)+'px', width: '100%', }">
      <div ref="tab-container" class="tab-container">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<style scoped>
  .lc-tab-page {
    width: 750px;
    flex-direction: column;
  }

  .tab-title-list {
    flex-direction: row;
  }

  .title-item {
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-bottom-style: solid;
    position: relative;
  }
  .text-wrap{
    position:relative;
    justify-content: center;
    align-items: center;
  }
  .tab-tip{
    position: absolute;
    justify-content: center;
    align-items: center;
    text-align: center;
  }

  .title-item-normal {
    flex: 1;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    letter-spacing: 0.09px;
    line-height: 26px;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: rgba(0,0,0,0.2);
  }

  .title-item-normal-border {
    border-left-style: solid;
    border-left-width: 1px;
    border-left-color: rgba(0,0,0,0.2);
  }

  .tab-title-list-card {
    flex-direction: row;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: rgba(0,0,0,0.2);
  }

  .title-item-card-wrap {
    width: 690px;
    /* height: 58px; */
    flex-direction: row;
    align-items: center;
    justify-content: center;
    /* background-color: #FFFFFF; */

    border-top-style: solid;
    border-top-width: 1px;
    border-top-color: #C8C8C8;
    
    border-right-style: solid;
    border-right-width: 1px;
    border-right-color: #C8C8C8;

    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-bottom-color: #C8C8C8;

    border-left-style: solid;
    border-left-color: #C8C8C8;
    border-left-width: 1px;  

    border-top-left-radius: 8px; 
    border-top-right-radius: 8px;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }
  
  .title-item-card {
    flex: 1;
    height: 54px;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    letter-spacing: 0.08px;
    line-height: 26px;
  }
 .bottom_line_height {
   height: 1px;
  }
   .title-item-card-border {
    border-left-style: solid;
    border-left-width: 1px;
    border-left-color: #c8c8c8;
  }

  .border-bottom {
    position: absolute;
    bottom: 0;
  }

  .tab-page-wrap {
    overflow: hidden;
    position: relative;
  }

  .tab-container {
    flex: 1;
    flex-direction: row;
    position: absolute;
  }

  .tab-text {
    lines: 1;
    text-overflow: ellipsis;
  }
</style>

<script>
  const dom = weex.requireModule('dom');
  const animation = weex.requireModule('animation');
  const swipeBack = weex.requireModule('swipeBack');
  const expressionBinding = weex.requireModule('expressionBinding');

  import Utils from 'lighting-ui/packages/utils';

  const supportsEB = Utils.env.supportsEB();
  const supportsEBForIos = Utils.env.supportsEBForIos();
  const isIos = Utils.env.isIOS();

  export default {
    props: {
      type: {
        type: String,
        default: 'scroll'
      },
      tabTitles: {
        type: Array,
        default: () => ([])
      },
      tipStyle:{
        type: Object,
        default: () => ({ })
      },
      panDist: {
        type: Number,
        default: 200
      },
      spmC: {
        type: [String, Number],
        default: ''
      },
      titleUseSlot: {
        type: Boolean,
        default: false
      },
      showBottomLine: {
        type: Boolean,
        default: false
      },
      tabStyles: {
        type: Object,
        default: () => ({
          bgColor: '#FFFFFF',
          titleColor: '#7A7A7A',
          activeTitleColor: '#4A4A4A',
          activeBgColor: '#FFFFFF',
          isActiveTitleBold: true,
          iconWidth: 70,
          iconHeight: 70,
          width: 160,
          height: 120,
          fontSize: 24,
          hasActiveBottom: true,
          bottomColor: 'transparent',
          activeBottomColor: '#4A90E2',
          activeBottomWidth: 120,
          activeBottomHeight: 6,
          textPaddingLeft: 10,
          textPaddingRight: 10,
          leftOffset: 0
        })
      },
      tabStylesNormal: {
        type: Object,
        default: () => ({
          bgColor: '#FFFFFF',
          titleColor: '#999999',
          activeTitleColor: '#FFFFFF',
          activeBgColor: '#4A90E2',
          isActiveTitleBold: false,
          height: 72,
          fontSize: 30,
          hasActiveBottom: false,
          textPaddingLeft: 0,
          textPaddingRight: 0,
          leftOffset: 0
        })
      },
      tabStylesCard: {
        type: Object,
        default: () => ({
          bgColor: '#FFFFFF',
          titleColor: '#9B9B9B',
          activeTitleColor: '#FFFFFF',
          activeBgColor: '#4A90E2',
          isActiveTitleBold: false,
          height: 86,
          fontSize: 26,
          textPaddingLeft: 0,
          textPaddingRight: 0,
          topOffset: 14,
          bottomOffset: 14,
          leftOffset: 30,
          rightOffset: 30
        })
      },
      titleType: {
        type: String,
        default: 'icon'
      },
      tabPageHeight: {
        type: [String, Number],
        default: 1334
      },
      isTabView: {
        type: Boolean,
        default: true
      },
      needSlider: {
        type: Boolean,
        default: true
      },
      duration: {
        type: [Number, String],
        default: 300
      },
      timingFunction: {
        type: String,
        default: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
      },
      wrapBgColor: {
        type: String,
        default: '#F9F9F9'
      },
      bottomLineColor: {
        type: String,
        default: '#999999'
      }
    },
    data: () => ({
      currentPage: 0,
      isMoving: false,
      startTime: 0,
      deltaX: 0,
      translateX: 0,
      startPosX: 0,
      startPosY: 0,
      judge: 'INITIAL',
      screenWidth: 750
    }),
    computed:{
      tabtipStyle(){
        const { tipStyle } = this;
        return {top: '10px', right: '10px', color: '#fff', width: '30px', height: '30px', borderRadius: '15px', backgroundColor: '#f53f3f',fontSize: '20px', lineHeight:'28px',...tipStyle}
      }
      
    },
    mounted () {
      this.$light.on("screenWidthChange", (res) => {
        this.screenWidth = res;
        this.$nextTick(()=>{
          this.setPage(this.currentPage)
        })
       });

      if (swipeBack && swipeBack.forbidSwipeBack) {
        swipeBack.forbidSwipeBack(true);
      }
      if (supportsEBForIos && this.needSlider && this.isTabView) {
        setTimeout(() => {
          const tabPageEl = this.$refs['tab-page-wrap'];
          if (tabPageEl && tabPageEl.ref) {
            expressionBinding.enableBinding(tabPageEl.ref, 'pan');
            this.bindExp(tabPageEl);
          }
        }, 20);
      }
    },
    methods: {
      next () {
        let page = this.currentPage;
        if (page < this.tabTitles.length - 1) {
          page++;
        }
        this.setPage(page);
      },
      prev () {
        let page = this.currentPage;
        if (page > 0) {
          page--;
        }
        this.setPage(page);
      },
      startHandler (e) {
        if (supportsEBForIos && e.state === 'start' && this.isTabView && this.needSlider) {
          // list下拉和到最下面问题修复
          setTimeout(() => {
            this.bindExp(this.$refs['tab-page-wrap']);
          }, 0)
        }
      },
      bindExp (element) {
        if (!this.isMoving && element && element.ref) {
          const tabElement = this.$refs['tab-container'];
          const { currentPage, panDist } = this;
          // const dist = currentPage * 750;
          const dist = currentPage * this.screenWidth;

          // x-dist
          const args = [{
            element: tabElement.ref,
            property: 'transform.translateX',
            expression: `{\"type\":\"-\",\"children\":[{\"type\":\"Identifier\",\"value\":\"x\"},{\"type\":\"NumericLiteral\",\"value\":${dist}}]}`
          }];
          expressionBinding.createBinding(element.ref, 'pan', '', args, e => {
            const { deltaX, state } = e;
            if (state === 'end') {
              if (deltaX < -panDist) {
                this.next();
              } else if (deltaX > panDist) {
                this.prev();
              } else {
                this.setPage(currentPage);
              }
            }
          });
        }
      },
      setPage (page, url = null, animated = true) {
        console.log("setPage");
        if (!this.isTabView) {
          this.jumpOut(url);
          return;
        }
        if (this.isMoving === true) {
          return;
        }
        this.isMoving = true;
        const previousPage = this.currentPage;
        const currentTabEl = this.$refs[`lc-tab-title-${page}`][0];
        const { width } = this.tabStyles;
        // const appearNum = parseInt(750 / width);
        const appearNum = parseInt(this.screenWidth / width);
        const tabsNum = this.tabTitles.length;
        // const offset = page > appearNum ? -(750 - width) / 2 : -width * 2;
        const offset = page > appearNum ? -(this.screenWidth - width) / 2 : -width * 2;

        if (appearNum < tabsNum) {
          (previousPage > appearNum || page > 1) && dom.scrollToElement(currentTabEl, {
            offset, animated
          });

          page <= 1 && previousPage > page && dom.scrollToElement(currentTabEl, {
            offset: -width * page,
            animated
          });
        }

        this.isMoving = false;
        this.currentPage = page;

        if (isIos) {
          // 高版本ios 手淘上面会有不固定情况，hack一下
          setTimeout(() => {
            this._animateTransformX(page, animated);
            this.$emit('LcTabPageCurrentTabSelected', { page });
          }, 10);
        } else {
          this._animateTransformX(page, animated);
          this.$emit('LcTabPageCurrentTabSelected', { page });
        }
      },
      jumpOut (url) {
        url && Utils.goToH5Page(url)
      },
      _animateTransformX (page, animated) {
        console.log("_animateTransformX");
        const { duration, timingFunction } = this;
        // 134033 【TS:201904160183-财富业委会-彭泉善-【需求内容】 1、UI组件缺陷：lc】
        const computedDur = animated ? duration : 0;
        const containerEl = this.$refs[`tab-container`];
        dom.getComponentRect(containerEl,(res)=>{
          console.log("getComponentRect"+JSON.stringify(res))
        })
        // const dist = page * 750;
        const dist = page * this.screenWidth;
        console.log("_animateTransformX==="+dist);
        animation.transition(containerEl, {
          styles: {
            transform: `translateX(${-dist}px)`
          },
          duration: computedDur,
          timingFunction,
          delay: 0
        }, () => {
        });
      },
      _onTouchStart (e) {
        if (supportsEB || !this.isTabView || !this.needSlider) {
          return;
        }
        this.startPosX = this._getTouchXPos(e);
        this.startPosY = this._getTouchYPos(e);
        this.deltaX = 0;
        this.startTime = new Date().getTime();
      },
      _onTouchMove (e) {
        if (supportsEB || !this.isTabView || !this.needSlider) {
          return;
        }
        this.deltaX = this._getTouchXPos(e) - this.startPosX;
        this.deltaY = Math.abs(this._getTouchYPos(e) - this.startPosY + 1);
        if (this.judge === 'INITIAL' && Math.abs(this.deltaX) / this.deltaY > 1.73) {
          this.judge = 'SLIDE_ING';
        }
      },
      _onTouchEnd () {
        if (supportsEB || !this.isTabView || !this.needSlider) {
          return;
        }
        if (this.judge === 'SLIDE_ING') {
          if (this.deltaX < -50) {
            this.next();
          } else if (this.deltaX > 50) {
            this.prev();
          }
        }
        this.judge = 'INITIAL';
      },
      _getTouchXPos (e) {
        return e.changedTouches[0]['pageX'];
      },
      _getTouchYPos (e) {
        return e.changedTouches[0]['pageY'];
      }
    }
  };
</script>
