<template>
    <view :class="'custom-class ' + utils.bem('tabs', [type])">
        <van-sticky :disabled="!sticky" :z-index="zIndex" :offset-top="offsetTop" :container="container" @scroll="onTouchScroll">
            <view :class="utils.bem('tabs__wrap', { scrollable }) + ' ' + (type === 'line' && border ? 'van-hairline--top-bottom' : '')">
                <slot name="nav-left" />

                <scroll-view
                    :scroll-x="scrollable"
                    scroll-with-animation
                    :scroll-left="scrollLeft"
                    :class="utils.bem('tabs__scroll', [type])"
                    :style="color ? 'border-color: ' + color : ''"
                >
                    <view :class="utils.bem('tabs__nav', [type]) + ' nav-class'" :style="getters.tabCardTypeBorderStyle(color, type)">
                        <view v-if="type === 'line'" class="van-tabs__line" :style="lineStyle" />
                        <view
                            :data-index="index"
                            :class="
                                getters.tabClass(index === currentIndex, ellipsis) +
                                ' ' +
                                utils.bem('tab', { active: index === currentIndex, disabled: item.disabled, complete: !ellipsis })
                            "
                            :style="
                                getters.tabStyle(index === currentIndex, ellipsis, color, type, item.disabled, titleActiveColor, titleInactiveColor, swipeThreshold, scrollable)
                            "
                            @tap="onTap"
                            v-for="(item, index) in tabs"
                            :key="index"
                        >
                            <view :class="ellipsis ? 'van-ellipsis' : ''" :style="item.titleStyle">
                                {{ item.title }}
                                <van-info v-if="item.info !== null || item.dot" :info="item.info" :dot="item.dot" custom-class="van-tab__title__info" />
                            </view>
                        </view>
                    </view>
                </scroll-view>

                <slot name="nav-right" />
            </view>
        </van-sticky>

        <view class="van-tabs__content" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @touchcancel="onTouchEnd">
            <view :class="utils.bem('tabs__track', [{ animated }]) + ' van-tabs__track'" :style="getters.trackStyle({ duration, currentIndex, animated })">
                <slot />
            </view>
        </view>
    </view>
</template>
<script module="utils" lang="wxs" src="@/node_modules/@vant/weapp/dist/wxs/utils.wxs"></script>
<script module="getters" lang="wxs" src="@/node_modules/@vant/weapp/dist/tabs/index.wxs"></script>
<script>
import { VantComponent } from '../common/component';
import { touch } from '../mixins/touch';
import { isDef, addUnit } from '../common/utils';
export default {
    data() {
        return {
            tabs: [],
            lineStyle: '',
            scrollLeft: 0,
            scrollable: false,
            trackStyle: '',
            currentIndex: null,
            container: null
        };
    },
    mixins: [touch],
    classes: ['nav-class', 'tab-class', 'tab-active-class', 'line-class'],
    '../tab/index': {
        name: 'tab',
        type: 'descendant',
        current: 'tabs',

        linked(target) {
            target.index = this.children.length - 1;
            this.updateTabs();
        },

        unlinked() {
            this.children = this.children.map((child, index) => {
                child.index = index;
                return child;
            });
            this.updateTabs();
        }
    },
    props: {
        color: {
            type: String
        },
        sticky: Boolean,
        animated: {
            type: Boolean
        },
        swipeable: Boolean,
        lineWidth: {
            type: [String, Number],
            default: -1
        },
        lineHeight: {
            type: [String, Number],
            default: -1
        },
        titleActiveColor: String,
        titleInactiveColor: String,
        active: {
            type: [String, Number],
            default: 0
        },
        type: {
            type: String,
            default: 'line'
        },
        border: {
            type: Boolean,
            default: true
        },
        ellipsis: {
            type: Boolean,
            default: true
        },
        duration: {
            type: Number,
            default: 0.3
        },
        zIndex: {
            type: Number,
            default: 1
        },
        swipeThreshold: {
            type: Number,
            default: 4
        },
        offsetTop: {
            type: Number,
            default: 0
        },
        lazyRender: {
            type: Boolean,
            default: true
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.setLine(true);
            this.scrollIntoView();
        });
    },
    methods: {
        updateContainer() {
            this.setData({
                container: () => uni.createSelectorQuery().in(this).select('.van-tabs')
            });
        },
        updateTabs() {
            const { children = [], data } = this;
            this.setData({
                tabs: children.map((child) => child.data),
                scrollable: this.children.length > data.swipeThreshold || !data.ellipsis
            });
            this.setCurrentIndexByName(this.getCurrentName() || data.active);
        },
        trigger(eventName, child) {
            const { currentIndex } = this;
            const currentChild = child || this.children[currentIndex];
            if (!isDef(currentChild)) {
                return;
            }
            this.$emit(eventName, {
                index: currentChild.index,
                name: currentChild.getComputedName(),
                title: currentChild.data.title
            });
        },
        onTap(event) {
            const { index } = event.currentTarget.dataset;
            const child = this.children[index];
            if (child.data.disabled) {
                this.trigger('disabled', child);
            } else {
                this.setCurrentIndex(index);
                this.$nextTick(() => {
                    this.trigger('click');
                });
            }
        },
        // correct the index of active tab
        setCurrentIndexByName(name) {
            const { children = [] } = this;
            const matched = children.filter((child) => child.getComputedName() === name);
            if (matched.length) {
                this.setCurrentIndex(matched[0].index);
            }
        },
        setCurrentIndex(currentIndex) {
            const { data, children = [] } = this;
            if (!isDef(currentIndex) || currentIndex >= children.length || currentIndex < 0) {
                return;
            }
            children.forEach((item, index) => {
                const active = index === currentIndex;
                if (active !== item.data.active || !item.inited) {
                    item.updateRender(active, this);
                }
            });
            if (currentIndex === data.currentIndex) {
                return;
            }
            const shouldEmitChange = data.currentIndex !== null;
            this.setData({
                currentIndex
            });
            this.$nextTick(() => {
                this.setLine();
                this.scrollIntoView();
                this.updateContainer();
                this.trigger('input');
                if (shouldEmitChange) {
                    this.trigger('change');
                }
            });
        },
        getCurrentName() {
            const activeTab = this.children[this.currentIndex];
            if (activeTab) {
                return activeTab.getComputedName();
            }
        },
        setLine(skipTransition) {
            if (this.type !== 'line') {
                return;
            }
            const { color, duration, currentIndex, lineWidth, lineHeight } = this;
            this.getRect('.van-tab', true).then((rects = []) => {
                const rect = rects[currentIndex];
                if (rect == null) {
                    return;
                }
                const width = lineWidth !== -1 ? lineWidth : rect.width / 2;
                const height = lineHeight !== -1 ? `height: ${addUnit(lineHeight)}; border-radius: ${addUnit(lineHeight)};` : '';
                let left = rects.slice(0, currentIndex).reduce((prev, curr) => prev + curr.width, 0);
                left += (rect.width - width) / 2;
                const transition = skipTransition ? '' : `transition-duration: ${duration}s; -webkit-transition-duration: ${duration}s;`;
                this.setData({
                    lineStyle: `
          ${height}
          width: ${addUnit(width)};
          background-color: ${color};
          -webkit-transform: translateX(${left}px);
          transform: translateX(${left}px);
          ${transition}
        `
                });
            });
        },
        // scroll active tab into view
        scrollIntoView() {
            const { currentIndex, scrollable } = this;
            if (!scrollable) {
                return;
            }
            Promise.all([this.getRect('.van-tab', true), this.getRect('.van-tabs__nav')]).then(([tabRects, navRect]) => {
                const tabRect = tabRects[currentIndex];
                const offsetLeft = tabRects.slice(0, currentIndex).reduce((prev, curr) => prev + curr.width, 0);
                this.setData({
                    scrollLeft: offsetLeft - (navRect.width - tabRect.width) / 2
                });
            });
        },
        onTouchScroll(event) {
            this.$emit('scroll', event.detail);
        },
        onTouchStart(event) {
            if (!this.swipeable) {
                return;
            }
            this.touchStart(event);
        },
        onTouchMove(event) {
            if (!this.swipeable) {
                return;
            }
            this.touchMove(event);
        },
        // watch swipe touch end
        onTouchEnd() {
            if (!this.swipeable) {
                return;
            }
            const { tabs, currentIndex } = this;
            const { direction, deltaX, offsetX } = this;
            const minSwipeDistance = 50;
            if (direction === 'horizontal' && offsetX >= minSwipeDistance) {
                if (deltaX > 0 && currentIndex !== 0) {
                    this.setCurrentIndex(currentIndex - 1);
                } else if (deltaX < 0 && currentIndex !== tabs.length - 1) {
                    this.setCurrentIndex(currentIndex + 1);
                }
            }
        }
    },
    watch: {
        color: {
            handler: function (skipTransition) {
                if (this.type !== 'line') {
                    return;
                }
                const { color, duration, currentIndex, lineWidth, lineHeight } = this;
                this.getRect('.van-tab', true).then((rects = []) => {
                    const rect = rects[currentIndex];
                    if (rect == null) {
                        return;
                    }
                    const width = lineWidth !== -1 ? lineWidth : rect.width / 2;
                    const height = lineHeight !== -1 ? `height: ${addUnit(lineHeight)}; border-radius: ${addUnit(lineHeight)};` : '';
                    let left = rects.slice(0, currentIndex).reduce((prev, curr) => prev + curr.width, 0);
                    left += (rect.width - width) / 2;
                    const transition = skipTransition ? '' : `transition-duration: ${duration}s; -webkit-transition-duration: ${duration}s;`;
                    this.setData({
                        lineStyle: `
                                ${height}
                                width: ${addUnit(width)};
                                background-color: ${color};
                                -webkit-transform: translateX(${left}px);
                                transform: translateX(${left}px);
                                ${transition}
                              `
                    });
                });
            },

            immediate: true
        },

        animated: {
            handler: function () {
                this.children.forEach((child, index) => child.updateRender(index === this.currentIndex, this));
            },

            immediate: true
        },

        lineWidth: {
            handler: function (skipTransition) {
                if (this.type !== 'line') {
                    return;
                }
                const { color, duration, currentIndex, lineWidth, lineHeight } = this;
                this.getRect('.van-tab', true).then((rects = []) => {
                    const rect = rects[currentIndex];
                    if (rect == null) {
                        return;
                    }
                    const width = lineWidth !== -1 ? lineWidth : rect.width / 2;
                    const height = lineHeight !== -1 ? `height: ${addUnit(lineHeight)}; border-radius: ${addUnit(lineHeight)};` : '';
                    let left = rects.slice(0, currentIndex).reduce((prev, curr) => prev + curr.width, 0);
                    left += (rect.width - width) / 2;
                    const transition = skipTransition ? '' : `transition-duration: ${duration}s; -webkit-transition-duration: ${duration}s;`;
                    this.setData({
                        lineStyle: `
                                ${height}
                                width: ${addUnit(width)};
                                background-color: ${color};
                                -webkit-transform: translateX(${left}px);
                                transform: translateX(${left}px);
                                ${transition}
                              `
                    });
                });
            },

            immediate: true
        },

        lineHeight: {
            handler: function (skipTransition) {
                if (this.type !== 'line') {
                    return;
                }
                const { color, duration, currentIndex, lineWidth, lineHeight } = this;
                this.getRect('.van-tab', true).then((rects = []) => {
                    const rect = rects[currentIndex];
                    if (rect == null) {
                        return;
                    }
                    const width = lineWidth !== -1 ? lineWidth : rect.width / 2;
                    const height = lineHeight !== -1 ? `height: ${addUnit(lineHeight)}; border-radius: ${addUnit(lineHeight)};` : '';
                    let left = rects.slice(0, currentIndex).reduce((prev, curr) => prev + curr.width, 0);
                    left += (rect.width - width) / 2;
                    const transition = skipTransition ? '' : `transition-duration: ${duration}s; -webkit-transition-duration: ${duration}s;`;
                    this.setData({
                        lineStyle: `
                                ${height}
                                width: ${addUnit(width)};
                                background-color: ${color};
                                -webkit-transform: translateX(${left}px);
                                transform: translateX(${left}px);
                                ${transition}
                              `
                    });
                });
            },

            immediate: true
        },

        active: {
            handler: function (name) {
                if (name !== this.getCurrentName()) {
                    this.setCurrentIndexByName(name);
                }
            },

            immediate: true
        },

        swipeThreshold: {
            handler: function (value) {
                this.setData({
                    scrollable: this.children.length > value || !this.ellipsis
                });
            },

            immediate: true
        }
    }
};
</script>
<style>
@import './index.css';
</style>
