<template>
    <view class="chat">
        <!-- top：对话状态/推荐医生 -->
        <view
            :class="{'chat-top': true, 'top-bar-bg': !!topNavBarHasBg}"
        >
            <slot name="top"></slot>
        </view>
        <!-- content：对话流 -->
        <scroll-view
            scroll-y
            :scroll-into-view="toView"
            :scroll-with-animation="isAnimation"
            class="chat-content"
            :style="ctnSty"
            upper-threshold="1"
            @tap="onTapContent"
            @scrolltoupper="$emit('msgScrollToTop')"
            @scroll="$emit('msgScroll', $event)"
        >
            <view :id="view.top"/>
            <view class="chat-content-inner">
                <view :style="{'height': height.top}"/>
                <slot name="content"></slot>
                <view :style="{'height': height.bottom}"/>
            </view>
            <view :id="view.bottom"/>
        </scroll-view>
        <!-- bottom：输入框 -->
        <view class="chat-bottom">
            <slot name="bottom"></slot>
        </view>
    </view>
</template>

<script>

/**
 * @file im布局
 * @author haoyan
 * @categories 业务组件
 * @tags [component]
*/
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import * as core from '../../utils/core';

export default {
    options: {
        addGlobalClass: true
    },
    config: {
        component: true
    },
    props: {
        // 小程序头部是否自定义：是-则需要计算navigationbar和statusbar高度
        isHeadCustom: {
            type: Boolean,
            default: false
        },
        // slot-content区域滚动时，是否使用动画
        isAnimation: {
            type: Boolean,
            default: false
        },
        // 头部是否有背景色
        topNavBarHasBg: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            ctnSty: {
                height: '',
                visibility: 'hidden'
            },

            height: {
                top: '',
                bottom: ''
            },
            sty: {
                top: {},
                content: {},
                bottom: {}
            },
            // 滚动标识
            toView: '',
            view: {
                top: `st_${core.rand()}`,
                bottom: `st_${core.rand()}`
            },
            // 屏幕高度
            screenHei: 0
        };
    },
    mounted() {
        if (process.env.MARS_ENV === 'swan') {
            this.screenHei = getSystemInfo().screenHeight;
        }
        else if (process.env.MARS_ENV === 'h5') {
            this.screenHei = document.documentElement.clientHeight;
        }
    },
    methods: {
        // 滚动到顶/底
        scrollTo(pos) {
            const to = pos => {
                this.getContentHei().then(info => {
                    this.ctnSty = {
                        height: info.contentHei + 'px',
                        visibility: 'visible'
                    };
                    this.$mpUpdated(() => {
                        if (pos === 'top') {
                            this.toView = this.view.top;
                        }
                        else if (pos === 'bottom') {
                            this.toView = this.view.bottom;
                        }
                        else {
                            this.toView = pos;
                        }
                        setTimeout(() => {
                            this.view = {
                                top: `st_${core.rand()}`,
                                bottom: `st_${core.rand()}`
                            };
                        }, 100);
                    });
                });
            };
            to(pos);
        },
        setContentHei() {
            this.getContentHei().then(info => {
                this.ctnSty = {
                    height: info.contentHei + 'px',
                    visibility: 'visible'
                };
                // slot-content高度变化时触发
                this.$emit('contentHeightChange', info);
            });
        },
        onTapContent(e) {
            // 点击对话流内容区域
            this.$emit('tapContent', e);
        },
        // 对话流中内容高度变化
        onHeightChange(info) {
            const {
                pos,
                height
            } = info;

            this.height[pos] = `${height / 100}rem`;
            this.scrollTo('bottom');
        },
        // 计算class='content'区域高度
        getContentHei(conf = {}) {
            return new Promise((resolve, reject) => {
                // 获取屏幕高度
                let navigationBarHeight = 0;
                let statusBarHeight = 0;
                let system = '';
                // 获取top、bottom高度
                let topHei = 0;
                let bottomHei = 0;
                if (process.env.MARS_ENV === 'swan') {
                    const sys = getSystemInfo();
                    navigationBarHeight = sys.navigationBarHeight;
                    statusBarHeight = sys.statusBarHeight;
                    // eslint-disable-next-line
                    system = sys.system.toLocaleLowerCase();
                    this.$api
                        .createSelectorQuery()
                        .selectAll('.chat-top, .chat-bottom')
                        .boundingClientRect(info => {
                            if (info && info.length) {
                                topHei = conf.top || info[0].height;
                                bottomHei = conf.bottom || info[1].height;
                            }
                            /* eslint-disable max-len */
                            resolve({
                                top: topHei,
                                bottom: bottomHei,
                                /* eslint-disable max-len */
                                contentHei: this.screenHei - (this.isHeadCustom ? 0 : (navigationBarHeight + statusBarHeight)) - topHei - bottomHei
                            });
                            /* eslint-enable max-len */
                        }).exec();
                }
                else if (process.env.MARS_ENV === 'h5') {
                    topHei = conf.top || document.querySelector('.chat-top') && document.querySelector('.chat-top').getBoundingClientRect().height;
                    bottomHei = conf.bottom || document.querySelector('.chat-bottom') && document.querySelector('.chat-bottom').getBoundingClientRect().height;
                    resolve({
                        top: topHei,
                        bottom: bottomHei,
                        contentHei: document.documentElement.clientHeight - topHei - bottomHei
                    });
                }
            });
        }
    }
};

</script>

<style lang="less" scoped>
.chat {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    height: 100%;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    border-top-left-radius: 13px;
    border-top-right-radius: 13px;
}
.chat-top {
    position: relative;
}
.top-bar-bg {
    background-image: linear-gradient(134deg, #00CFA3 0%, #05CFCD 61%, #00D3EA 100%);
    z-index: 3;
}
.chat-bottom {
    background-color: #f5f5f5;
    position: relative;
    z-index: 2;
}
.chat-content {
    background-color: #f5f5f5;
    position: relative;
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    height: 100%;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
}
.chat-content-inner {
    padding: .2rem .17rem .15rem;
}
</style>
