<template>
    <view class="navs-box">
        <view 
            id="navs"
            class="navs"
            :class="{'navs__fix': __navFixed}"
            :style="{top: __navFixed ? topHeight + 'px' : 'auto'}"
        >
            <!-- 顶部slot -->
            <slot name="header"></slot>
            <!-- 导航区域 -->
            <view class="navs__main">
                <scroll-view
                    scroll-x
                    :scroll-into-view="'marsUINavItem' + (mIndex - 1 < 0 ? 0 : mIndex - 1)"
                    class="navs__main__scroll"
                    :scroll-left="scrollLeft"
                    :scroll-with-animation="true"
                    :style="scrollComponentStyle"
                >
                    <view class="navs__main__scroll__list" :style="boxStyle">
                        <!-- 导航项 -->
                        <view
                            v-for="(item, index) in list"
                            :id="'marsUINavItem' + index"
                            :key="item.id || 'nav_' + item.text + index"
                            class="navs__main__scroll__item"
                            :style="mIndex === index ? __selectedItemStyle : itemStyle"
                            @tap="swiperNav(index)"
                        >
                            <view 
                                class="navs__main__scroll__item__cont text-background"
                                :style="mIndex === index ? __selectedFontStyle : fontStyle"
                            >
                                <!-- icon -->
                                <text 
                                    v-if="iconConf.enable && mIndex === index"
                                    :class="['navs__main__scroll__item__icon', 'm-icon', 'c-gap-right-small', iconConf.icon]"
                                    style="font-size: 19px"
                                />
                                <!-- 文字 -->
                                <text class="navs__main__scroll__item__text">{{ item.text }}</text>
                            </view>
                        </view>
                        <!-- 展开收起按钮空白 -->
                        <view v-if="enableExpand" class="navs__main__scroll__expand__blank"/>
                    </view>
                </scroll-view>
                <!-- 展开收起按钮 -->
                <view 
                    v-if="enableExpand" 
                    class="navs__main__scroll__expand__btn"
                    :class="{'navs--zindex': openExpand}"
                    :style="{
                        'background': openExpand ? 'transparent' : panelIconBg || scrollComponentStyle['background'] || scrollComponentStyle['background-color'] || scrollComponentStyle['background-image'],
                    }"
                    @tap.stop="onExpand"
                >
                    <c-icon 
                        class="navs__main__scroll__expand__i" 
                        :class="{'navs__main__scroll__expand__i-open': openExpand}"
                        :style="{
                            color: panelIconColor,
                        }"
                        name="down"
                    />
                </view>
                <template v-if="enableExpand">
                    <!-- 展开收起面板 -->
                    <template v-if="openExpand">
                        <!-- 提示语 -->
                        <view 
                            class="c-color-gray navs__main__scroll__expand__tips img-background"
                            :style="{
                                backgroundImage: scrollComponentStyle['background-image'],
                            }"
                        >
                            <text
                                class="text-background"
                                :style="{
                                    backgroundImage: fontStyle['background-image'],
                                }"
                            >{{ panelText }}</text>
                        </view>
                        <!-- 更多面板 -->
                        <view class="navs__main__scroll__expand__panel">
                            <view class="navs__main__scroll__expand__cont" :style="panelStyle">
                                <view
                                    v-for="(item, index) in list"
                                    :key="index"
                                    class="navs__main__scroll__expand__cont__item"
                                    :style="mIndex === index ? __panelItemActStyle : panelItemStyle"
                                    @tap.stop="swiperNav(index)"
                                >
                                    <text>{{ item.text }}</text>
                                </view>
                            </view>
                        </view>
                    </template>
                    <!-- 展开收起蒙层 -->
                    <view
                        v-show="enableExpand && openExpand"
                        class="c-gap-bottom navs__main__scroll__expand__mask"
                        @touchstart.stop="onExpand('mask')"
                    >
                        <view class="c-gap-bottom navs__main__scroll__expand__mask__cont"/>
                    </view>
                </template>
            </view>
        </view>
        <!-- 吸顶空白 -->
        <view 
            v-if="__navFixed"
            :style="{
                height: navConf.height + 'px',
            }"
        />
    </view>
</template>
<script>
/**
 * @file 活动Navs定制化
 * @author mayifan02
 * @categories
 * @tags
 */
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import {ubcSend} from '@utils/log';
import {throttle, debounce} from '@utils/core';
export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    props: {
        /**
         * 数据
         * @property text 文字
         */
        list: {
            type: Array,
            default: () => ([])
        },
        /**
         * 展开全部
         */
        enableExpand: {
            type: Boolean,
            default: false
        },
        /**
         * icon 配置
         */
        iconConf: {
            type: Object,
            default: () => {
                return {
                    icon: 'm-icon-location',
                    enable: false
                };
            }
        },
        /**
         * 页面滚动距离
         */
        pageScroll: {
            type: Number,
            default: 0
        },
        /**
         * 吸顶
         */
        enableFixed: {
            type: Boolean,
            default: false
        },
        /**
         * topBar高度
         */
        topHeight: {
            type: Number,
            default: 44
        },
        /**
         * scroll组件样式
         */
        scrollComponentStyle: {
            type: Object,
            default: () => {
                return {
                    'background-image': 'linear-gradient(to top, rgb(243, 65, 13), rgb(255, 123, 82))'
                };
            }
        },
        /**
         * 内部容器样式
         */
        boxStyle: {
            type: Object,
            default: () => {
                return {
                    padding: '9px 13px'
                };
            }
        },
        /**
         * 选中项
         */
        selectedIndex: {
            type: Number,
            default: 0
        },
        /**
         * 选中tab样式
         */
        selectedItemStyle: {
            type: Object,
            default: () => {
                return {
                    'box-shadow': '-0.122px -0.993px 2px 0px rgba(253, 201, 188, 0.004),inset 0px 2px 3px 0px rgba(232, 148, 5, 0.71),inset 0px 1px 1px 0px rgba(232, 148, 5, 0.52)',
                    'background-image': 'linear-gradient(to top, #fec871, #fee5b3)',
                    'font-weight': 'bold'
                };
            }
        },
        /**
         * tab样式
         */
        itemStyle: {
            type: Object,
            default: () => {
                return {
                    'line-height': '30px',
                    'padding': '0 11px',
                    'font-size': '18px',
                    'display': 'inline-block',
                    'border-radius': '333px'
                };
            }
        },
        /**
         * 选中文字样式
         */
        selectedFontStyle: {
            type: Object,
            default: () => {
                return {
                    'background-image': 'linear-gradient(to top, #f3410d, #ff7b52)'
                };
            }
        },
        /**
         * 文字样式
         */
        fontStyle: {
            type: Object,
            default: () => {
                return {
                    'background-image': 'linear-gradient(0 , #ffefcf, #ffefcf)'
                };
            }
        },
        /**
         * 面板箭头背景
         */
        panelIconBg: {
            type: String,
            default: ''
        },
        /**
         * 面板提示文字
         */
        panelText: {
            type: String,
            default: '请选择品类'
        },
        /**
         * 面板样式
         */
        panelStyle: {
            type: Object,
            default: () => {
                return {
                    'background': '#D03F02'
                };
            }
        },
        /**
         * 展开面板Item样式
         */
        panelItemStyle: {
            type: Object,
            default: () => {
                return {
                    'background': '#9D2001',
                    'color': 'rgba(255,255,255, 0.8)',
                };
            }
        },
        /**
         * 展开面板Item激活样式
         */
        panelItemActStyle: {
            type: Object,
            default: () => {
                return {
                    'background': '#fff',
                    'color': '#F74F1D',
                    'font-weight': 'bold'
                };
            }
        },
        /**
         * 面板icon颜色
         */
        panelIconColor: {
            type: String,
            default: '#fff'
        },
        /**
         * 内容区域
         * @property top
         * @property bottom
         */
        contentAnchorArr: {
            type: Array,
            default: () => {
                return [];
            }
        },
        /**
         * 打点
         */
        log: {
            type: Object,
            default: () => {
                return {
                    page: '',
                    value: 'navitem',
                    ext: {
                        pd: 'act'
                    }
                };
            }
        }
    },
    components: {
        CIcon
    },
    data() {
        const sys = getSystemInfo();
        return {
            windowWidth: 0,
            // 上次滚动距离
            upDistScroll: 0,
            // 导航滚动距离
            scrollLeft: 0,
            // 当前选中项
            mIndex: 0,
            // 导航配置
            navConf: {
                top: 0,
                bottom: 0,
                height: 0,
                maxDistance: 0,
                fixed: false
            },
            // 展开收起
            openExpand: false,
            // 状态栏高度
            statusBarHeight: sys.statusBarHeight || 0,
            // 锚点滚动
            anchorTimerId: null,
            // 手动点击时禁用滚动锚点
            disableScrollAnchor: false,
            disableScrollAnchorId: null,
            scrollEndId: null
            // scrollTimerId: null
        };
    },
    computed: {
        /** 选中字体样式 */
        __selectedFontStyle() {
            return Object.assign({}, this.fontStyle, this.selectedFontStyle);
        },
        /** 选中item样式  */
        __selectedItemStyle() {
            return Object.assign({}, this.itemStyle, this.selectedItemStyle);
        },
        /** 选中panel item样式  */
        __panelItemActStyle() {
            return Object.assign({}, this.panelItemStyle, this.panelItemActStyle);
        },
        /** 是否吸顶 */
        __navFixed() {
            return this.enableFixed && this.navConf.fixed;
        }
    },
    created() {
        this.windowWidth = getSystemInfo().windowWidth;
        this.mIndex = this.selectedIndex;
    },
    mounted() {
        this.$mpUpdated(() => {
            this.setScollLeft(this.selectedIndex);
            if (this.enableFixed) {
                this.setElementTop('#navs').then(res => {
                    Object.assign(this.navConf, {...res});
                    this.$emit('navHeightSuccess');
                });
            }
        });
    },
    watch: {
        selectedIndex(nval, oval) {
            if (nval !== oval) {
                this.mIndex = nval;
            }
        },
        // 页面滚动距离
        pageScroll(nval, oval) {
            if (nval) {
                // 页面滚动结束判断
                clearTimeout(this.scrollEndId);
                this.scrollEndId = setTimeout(() => {
                    this.onPageScrollEnd();
                }, 500);
                // 吸顶
                this.handleFixed(nval);
                // 导航锚点
                this.scrollAnchor();
            }
        },
        contentAnchorArr(nval, oval) {
            if (nval && nval.length > 0) {
                const lastIndex = nval.length - 1;
                this.navConf.maxDistance = nval[lastIndex].bottom;
            }
        }
    },
    methods: {
        // 页面滚动结束
        onPageScrollEnd() {
            // 滚动结束处理吸顶，有可能最后一次更新没生效
            this.__handleFixed(this.pageScroll);
            // 滚动结束处理锚点，有可能最后一次更新没生效
            this.__scrollAnchor();
        },
        // 处理吸顶
        handleFixed: throttle(function (nval) {
            this.__handleFixed(nval);
        }, 50),
        __handleFixed(nval) {
            const {maxDistance, top} = this.navConf;
            let isFixed = false;
            // 导航吸顶
            if (maxDistance && top) {
                isFixed = (nval >= top && nval <= maxDistance);
            } else if (top) {
                isFixed = nval >= top;
            }
            this.$set(this.navConf, 'fixed', isFixed);
        },
        // 设置滚动距离
        setScollLeft(index) {
            let w = this.windowWidth;
            let leng = this.list.length;
            let disX = ((index) * w) / leng;
            this.scrollLeft = disX;
        },
        // navitem点击
        swiperNav(index) {
            if (this.openExpand) {
                this.openExpand = false;
            }
            this.mIndex = index;
            /**
             * 点击按钮
             * @property {index, item}
             */
            this.$emit('swiperNav', {index, item: this.list[index]});

            if (this.contentAnchorArr && this.contentAnchorArr.length) {
                const {top} = this.contentAnchorArr[index];
                this.scrollPageTo(top);
            }
            ubcSend({
                page: this.log.page,
                type: 'clk',
                value: this.log.value,
                ext: Object.assign({
                    pd: 'act',
                    value_id: this.list[index].id || index
                }, this.log.ext || {})
            });
        },
        // 滚动到指定位置
        scrollPageTo(top = 0) {
            // 手动点击nav锚点，避免滚动锚点同时执行
            this.disableScrollAnchor = true;
            this.$api.pageScrollTo({scrollTop: top, duration: 150});
            clearTimeout(this.disableScrollAnchorId);
            this.disableScrollAnchorId = setTimeout(() => {
                this.disableScrollAnchor = false;
            }, 400);
        },
        // 滚动锚点
        scrollAnchor: debounce(function () {
            this.__scrollAnchor();
        }, 30, true),
        // 滚动锚点
        __scrollAnchor() {
            if (!(this.contentAnchorArr && this.contentAnchorArr.length && !this.disableScrollAnchor)) {
                return;
            }
            for (let i = this.contentAnchorArr.length - 1; i >= 0; i--) {
                if (Math.round(this.pageScroll) >= this.contentAnchorArr[i].top) {
                    this.mIndex = i;
                    break;
                }
            }
            if (this.pageScroll <= this.contentAnchorArr[0].top) {
                this.mIndex = 0;
            }
        },
        /**
         * 获取元素距离顶部距离
         * @property elementId 元素ID
         * @property subNavHeight 减nav高度
         * @property customHeight 添加其他高度
         */
        setElementTop(elementId = '#recommend-header', subNavHeight = false, customHeight = 0) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    this.$api.createSelectorQuery().selectViewport().scrollOffset(viewport => {
                        const scrollTop = viewport.scrollTop;
                        const query = this.$api.createSelectorQuery().select(elementId);
                        query.boundingClientRect(rect => {
                            const {top, bottom, height} = rect || {};
                            if (top && bottom && height) {
                                let commValue = scrollTop - this.topHeight + customHeight;
                                // 减nav高度
                                if (subNavHeight) {
                                    commValue -= this.navConf.height;
                                }
                                resolve({
                                    top: Math.floor(top + commValue),
                                    bottom: Math.floor(bottom + commValue),
                                    height
                                });
                            } else {
                                this.setElementTop();
                            }
                        })
                            .exec();
                    }).exec();
                }, 20);
            });
        },
        // 展开收起
        onExpand(type) {
            this.openExpand = !this.openExpand;
        },
    }
};
</script>
<style lang="less" scoped>
.text-background {
    -webkit-text-fill-color: transparent;
    color: transparent;
    background-clip: text;
}
.navs {
    position: relative;
    &__fix {
        width: 100%;
        box-sizing: border-box;
        position: fixed;
        left: 0;
        z-index: 802;
    }
    &__main {
        position: relative;
        &__scroll {
            position: relative;
            background-color: transparent;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            white-space: nowrap;
            box-sizing: border-box;
            &__list {
                display: flex;
                justify-content: space-between;
            }
            &__item {
                display: flex;
                justify-content: center;
                align-items: center;
                flex-shrink: 0;
                text-align: center;
                box-sizing: border-box;
                background-size: 100% 100%;
                background-repeat: no-repeat;
                &:nth-child(1) {
                    margin-left: 0 !important;
                }
            }
            &__expand {
                &__blank {
                    width: 41px;
                    height: 1px;
                    flex-shrink: 0;
                }
                &__btn {
                    position: absolute;
                    right: 0;
                    top: 0;
                    z-index: 99;
                    height: 100%;
                    width: 41px;
                    display:flex;
                    justify-content:center;
                    align-items:center;
                }
                &__i {
                    transform: rotate(0deg);
                    transform-origin: center center;
                    transition: All .16s cubic-bezier(.46, 0, 1, 1);
                    &-open {
                        transform: rotate(180deg);
                        transform-origin: center center;
                        transition: All .3s cubic-bezier(.42, 0, .52, 1);
                    }
                }
                &__tips {
                    z-index: 800;
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    display: flex;
                    align-items: center;
                    height: 100%;
                    padding-left: 17px;
                    background: #fff;
                    transition: all .3s cubic-bezier(.42, 0, .52, 1);
                    font-weight: bold;
                }
                &__panel {
                    position: absolute;
                    top: 100%;
                    left: 0;
                    right: 0;
                    overflow: hidden;
                    z-index: 800;
                    transition: all .3s cubic-bezier(.42, 0, .52, 1);
                }
                &__cont {
                    width: 100%;
                    background: #fff;
                    box-sizing: border-box;
                    padding-top: 10px;
                    display: flex;
                    flex-wrap: wrap;
                    margin-bottom: -5px;
                    &__item {
                        padding: 0 16px;
                        height: 30px;
                        line-height: 28px;
                        box-sizing: border-box;
                        border: 1px solid transparent;
                        border-radius: 5px;
                        font-size: 13px;
                        text-align: center;
                        margin-left: 3.62vw;
                        margin-bottom: 3.62vw;
                    }
                }
                &__mask {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    z-index: 799;
                    &__cont {
                        background-color: rgba(0, 0, 0, .5);
                        height: 100vh;
                        width: 100vw;
                    }
                }
            }
        }
    }
    &--zindex {
        z-index: 803;
    }
}
</style>
