<template>
    <div class="nav swiper-container" :class="{fixed: isFixed}" ref="nav" style="height: 44px;">
        <div class="swiper-wrapper">
            <div
                class="swiper-slide item"
                :class="{active: index === listIndex}"
                style="width: 100px; line-height: 44px;"
                v-for="(item, index) in list"
                :key="index"
                @click="$emit('tab', index)"
            >{{item.m_name}}</div>
            <i
                class="border"
                :class="direction"
                :style="{left: listIndex * 100 + 'px', right: width - (listIndex + 1) * 100 + 'px'}"
                v-if="list && list.length"
            ></i>
        </div>
    </div>
</template>

<script>
import Swiper from 'swiper'
export default {
    props: ['list', 'listIndex', 'isFixed'],
    data () {
        return {
            width: innerWidth,
            direction: 'forward',
            swiper: {}
        }
    },
    watch: {
        listIndex (newIndex, oldIndex) {
            // slideTo() 默认靠左，slideToClosest() 在 slidesPerView 设置多个的模式下无效
            // 往前时如果应该位移距离 > 当前距离则移动到当前距离，往后是当前 index 倍数（注意是负数）
            if (newIndex > oldIndex) {
                const expectLate = -(newIndex + 1) * 100 + innerWidth
                if (expectLate < this.swiper.getTranslate()) {
                    this.swiper.setTransition(300)
                    this.swiper.setTranslate(expectLate)
                }
            } else {
                const expectLate = -newIndex * 100
                if (expectLate > this.swiper.getTranslate()) {
                    this.swiper.setTransition(300)
                    this.swiper.setTranslate(expectLate)
                }
            }
            this.direction = newIndex > oldIndex ? 'forward' : 'backward'
        }
    },
    mounted () {
        this.swiper = new Swiper(this.$refs.nav, {
            freeMode: true,
            freeModeMomentumRatio: 0.5,
            slidesPerView: 'auto',
            observer: true,
            observeParents: true
        })
    },
    methods: {
        scrollTop () {
            this.swiper.setTranslate(0)
        }
    }
}
</script>

<style lang="less" scoped>
@import 'swiper/dist/css/swiper.css';
.nav {
    text-align: center;
    background-color: #efeff4;
    .item {
        display: inline-block;
        font-weight: bold;
        color: #666;
        &.active {
            color: #409eff;
        }
    }
    .border {
        position: absolute;
        bottom: 0;
        height: 3px;
        background-color: #409eff;
        &.forward {
            transition: left 0.3s 0.1s, right 0.3s;
        }
        &.backward {
            transition: left 0.3s, right 0.3s 0.1s;
        }
    }
}
.fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}
</style>
