<template>
    <view>
        <view 
            :style="!isUpfold ? foldStyle : nStyle"
            :class="{
                'med-scorll-float--fold': !isUpfold,
                'med-scorll-float--widthtabbar': widthTabBar
            }"
            class="med-scorll-float swan-security-margin-bottom"
            @tap="upfoldOpen"
        >
            <slot/>
        </view>
    </view>
</template>

<script>
/**
 * @file 漂浮元素 在页面滑动时加折叠等效果
 * @author zhangeryi@baidu.com
 * @categories
 * @tags
 */

// 动效延迟时间
const feedbackDealy = 500;
// 下拉开始时间点
let feedbackBeginTime = null;
export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    props: {
        // 默认样式
        nStyle: {
            type: Object,
            default() {
                return {};
            }
        },
        // 折叠样式
        foldStyle: {
            type: Object,
            default() {
                return {};
            }
        },
        // 是否是在tabBar页面使用 （如果是 则h5自动适配底部tabBar间距）
        widthTabBar: {
            'type': Boolean,
            'default': false
        },
        // 外部控制折叠
        upfold: {
            'type': Boolean,
            'default': true
        }
    },
    data() {
        return {
            upDistance: 0,
            isUpfold: this.upfold
        };
    },
    watch: {
        upfold() {
            this.isUpfold = this.upfold;
        }
    },
    methods: {
        upfoldOpen() {
            this.isUpfold = true;
        },
        scrollStyle(e) {
            const diff = e.scrollTop - this.upDistance;
            if (this.upDistance === 0) {
                this.upDistance = e.scrollTop;
                return;
            }
            // 上滑到顶部，初始为展开状态
            if (e.scrollTop === 0) {
                this.isUpfold = true;
            }
            if (Math.abs(diff) < 44 || e.scrollTop < 0) {
                return;
            }
            // 下拉
            if (diff > 44) {
                this.isUpfold = false;
                feedbackBeginTime = Date.now();
            }
            // 上滑, 滑动距离大于44，且下拉与上滑的间隔超过 feedbackDealy，且 上次记录的下拉时间为空
            else if (diff < -44 && (Date.now() - feedbackBeginTime > feedbackDealy || !feedbackBeginTime)) {
                feedbackBeginTime = null;
                this.isUpfold = true;
            }
            this.upDistance = e.scrollTop;
        }
    }
};
</script>
<style lang="less" scoped>
.med-scorll-float {
    position: fixed;
    z-index: 1;
    right: .17rem;
    bottom: .2rem;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    transition: all .38s cubic-bezier(.2, 0, .2, 1);
    &--fold {
        right: -.2rem;
        opacity: .5;
    }
}
</style>
<style target="h5" lang="less">
.med-scorll-float {
    &--widthtabbar {
        padding-bottom: 46px;
    }
}
</style>