<template>
    <med-container
        :menu="menu"
        :naviBgColor="naviBgColor"
        :title="pageTitle"
        class="swan-security-padding-bottom"
        @topbarHeightHandle="topbarHeightHandle"
    >
        <view
            class="spe-topic-im"
            v-bind:class="showLogClass"
            :data-show="from ? 'speTopicActivityIm-' + from : 'speTopicActivityIm'"
        >
            <view>
                <view>
                    <swiper
                        v-if="reload"
                        :current="currentIndex"
                        :style="{
                            height: ContentHeight + 'px'
                        }"
                        class="phoebewang"
                        previous-margin="15px"
                        next-margin="15px"
                        @change="onPageChange"
                    >
                        <swiper-item
                            v-for="(page, pageIndex) in pageMap"
                            :key="pageIndex"
                        >
                                <view
                                    :id="'spetopview' + pageIndex"
                                    class="spe-topic-im-view c-gap-top-ll">
                                    <view :style="{
                                        margin: '0 -15px'
                                    }">
                                    <scroll-view
                                        scroll-y
                                        :style="{
                                            height: ContentHeight - 40 + 'px'
                                        }"
                                    >
                                        <view class="c-gap-inner-right-large c-gap-inner-left-large">
                                            <view class="spe-topic-im-view-header">{{ page.title }}</view>
                                            <view class="c-line-top spe-topic-im-view-line"></view>
                                            <view class="spe-topic-im-view-im">
                                                <im-msg
                                                    v-for="(msg, i) in page.msgList"
                                                    :key="i"
                                                    :msg="msg"
                                                    :is-last="i === page.msgList.length - 1"
                                                    :reply-stl="{
                                                        bgColor: '#f7f7f7'
                                                    }"
                                                    class="c-blocka"
                                                    ></im-msg>
                                                    <view class="im-bottom-placeholder"></view>
                                            </view>
                                        </view>
                                    </scroll-view>
                                    </view>
                                </view>
                                <b-navigate
                                    v-if="wzButton && wzButton.url"
                                    :url="wzButton.url"
                                    class="spe-topic-activity-share-wrapper">
                                    <view
                                    class="spe-topic-activity-share">{{wzButton.btnText}}</view>
                                </b-navigate>
                        </swiper-item>
                    </swiper>
                    <view v-if="isLoading === 'loading'" class="spe-topic-im-loading-wrapper">
                        <view class="spe-topic-im-loading">
                            <list-loading
                                status="loading"
                            />
                        </view>
                    </view>
                </view>
            </view>
            <view class="spe-topic-im-footer swan-security-padding-bottom">
                <view
                    :class="[
                        beforeStatus ? 'green' : 'gray'
                    ]"
                    class="c-gap-right-ll"
                    @tap="onBefore">上一篇</view>
                <view
                    :class="[
                        nextStatus ? 'green' : 'gray'
                    ]"
                    @tap="onAfter">下一篇</view>
            </view>
        </view>
    </med-container>
</template>

<script>

/**
* @file 对话流
* @author yantingxi
*/
import * as conf from '../../../../utils/conf';
import * as core from '../../../../utils/core';
import {request} from '../../../../utils/request';
import {send, ShowLog} from '../../../../utils/log';
import {shareBdBox} from '../../../../utils/share';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import Container from '../../../../components/common/container';
import ImMsg from '../../../../components/im/im-msg';
import ListLoading from '../../../../components/common/list-loading';
import Navigate from '../../../../components/common/navigate';

export default {
    data() {
        return {
            pageTitle: '网友在线咨询案例',
            menu: [],
            isLoading: 'loading',
            ContentHeight: 900,
            topbarHeight: 0,

            naviBgColor: '#f6f6f6',

            imConfig: {
                mainBgColor: '#FFF',
                left: {
                    // 消息内背景色
                    bgColor: '#f7f7f7',
                    // 文字颜色
                    textColor: '#000'
                },
                // 消息列表右侧配置
                right: {
                    // 消息内背景色
                    bgColor: '#03D0BF',
                    // 文字颜色
                    textColor: '#fff'
                }
            },

            showLogClass: 'SHOW_LOG_MODULE_' + core.rand(6),
            showLogIns: null,

            isFirstScreen: true,
            scrollToLeft: false,
            reload: true,
            msgList: [],
            title: '',
            beforeApi: true,
            nextApi: true,
            curID: 0,
            currentPage: 0,
            currentPageIndex: 0,
            beforeStatus: true,
            nextStatus: true,
            pageMap: [],
            currentIndex: 0,
            options: {},

            shareInfo4Bd: {
                title: '新冠肺炎防护手册',
                content: '关于新冠肺炎的全人群实用指南，有它，一本就够',
                imageUrl: 'https://expertimg.cdn.bcebos.com/expertcms/med/sari_icon.png'
            },
            wzButton: {}
        };
    },
    onLoad(options) {
        this.getPageData(options);
        this.from = options.sf_ref || '';
        this.options = Object.assign({}, options);
    },
    mounted() {
        this.getContentHeight();
        if (process.env.MARS_ENV === 'h5') {
            window.removeEventListener('resize', this.onResize);
            window.addEventListener('resize', this.onResize);
        }
    },
    onShareAppMessage() {
        return this.shareInfo4Bd;
    },
    onShow() {
        if (process.env.MARS_ENV === 'swan') {
            this.$api.setNavigationBarColor({
                backgroundColor: this.naviBgColor,
                frontColor: '#000000'
            });
        }
        if (process.env.MARS_ENV === 'h5') {
            shareBdBox(this.shareInfo4Bd);
        }
    },
    onHide() {
        if (this.showLogIns) {
            this.showLogIns.reset();
            this.showLogIns.remove();
        }
    },
    methods: {
        getPageData(options = {}, url) {

            this.getPageDataBase(options, url).then(({data, update}) => {
                this.pageMap = this.fetchPageMap(options, data);
                update.call(this);
                this.fetchChangePageStatus();
                this.reload = false;
                this.$mpUpdated(() => {
                    this.isLoading = 'init';
                    this.reload = true;

                    if (this.isFirstScreen) {
                        this.isFirstScreen = !this.isFirstScreen;
                    }

                    send({
                        type: 't',
                        action: 'scroll',
                        extra: {
                            page: 'im-card' + this.currentIndex
                        }
                    });

                    // 更新数据，页面渲染完成后，获取nav的top值，用于吸顶判断
                    try {
                        this.showLogIns = new ShowLog();
                        this.showLogIns.SIGN = '.' + this.showLogClass;
                        this.showLogIns.init();
                    } catch (error) {
                        console.error(error);
                    }
                });
            });
        },
        fetchImData(list) {
            let newList = [];
            const typeMap = {
                answer: 1,
                ask: 0
            };
            if (list && list.length > 0) {
                newList = list.map(item => {
                    item.from = typeMap[item.type];
                    item.type = 'text';
                    item.content = [{type: item.type, text: item.content}];
                    return item;
                });
            }
            return newList;
        },
        getPageDataBase(options, url) {
            this.isLoading = 'loading';

            return new Promise((resolve, reject) => {
                request({
                    url: url ? url : conf.apiHost + '/med/page/sariconsult',
                    method: 'GET',
                    data: url ? {} : options,
                    isFirstScreen: this.isFirstScreen,
                    isNeedLogin: false,
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(({data, update}) => {
                    if (data.content && data.content && data.content) {
                        this.curID = data.curID;
                        this.wzButton = data.wzButton || {};

                        this.currentPage = data.curPage || 0;
                        this.nextApi = data.nextApi || '';
                        this.beforeApi = data.beforeApi || '';
                        this.currentSize = data.content.length;

                        resolve({data: data.content, update});
                    } else {
                        reject();
                    }
                })
                .catch(error => reject(error));
            });
        },
        topbarHeightHandle(e) {
            this.topbarHeight = e;
        },
        onPageChange({detail}) {
            let current = Number(detail.current);
            let currentSize = this.currentSize;

            if (this.currentPage !== 0) {
                ++currentSize;
            }

            if (this.beforeApi && current < 1) {
                this.getPageData({}, this.beforeApi);
                this.scrollToLeft = true;
            } else if (this.nextApi && current >= currentSize) {
                this.getPageData({}, this.nextApi);
                this.scrollToLeft = false;
            }

            this.currentPageIndex = current;

            this.fetchChangePageStatus();

            send({
                type: 't',
                action: 'scroll',
                extra: {
                    page: 'im-card' + current
                }
            });
        },
        onBefore() {
            if (!this.beforeStatus || this.isLoading === 'loading') {
                return;
            }

            if (!this.options.size) {
                this.currentIndex = this.currentPageIndex - 1;
            } else {
                this.currentIndex--;
            }
        },
        onAfter() {
            if (!this.nextStatus || this.isLoading === 'loading') {
                return;
            }

            if (!this.options.size) {
                this.currentIndex = this.currentPageIndex + 1;
            } else {
                this.currentIndex++;
            }
        },
        getContentHeight(reloaded) {
            const query = this.$api.createSelectorQuery();
            query.select('.spe-topic-im-footer').boundingClientRect(data => {
                    if (data) {
                        let height;
                        height = data.height || 44;
                        const sysInfo = getSystemInfo();
                        this.ContentHeight = sysInfo.windowHeight - height;
                        if (process.env.MARS_ENV === 'h5') {
                            console.log('1', sysInfo.screenHeight);
                            console.log('2', this.topbarHeight);
                            this.ContentHeight = sysInfo.screenHeight - this.topbarHeight - height;
                        }
                    } else {
                        !reloaded && this.getContentHeight(true);
                    }
                }
            ).exec();
        },
        fetchPageMap(options, list) {
            let pageMap = list;

            pageMap = pageMap.map((item, index) => {
                return {
                    title: item.data.goods.title,
                    msgList: this.fetchImData(item.data.goods.msgList)
                };
            });

            pageMap = [{}, ...pageMap, {}];

            !this.beforeApi && pageMap.shift();
            !this.nextApi && pageMap.pop();

            if (this.isFirstScreen) {
                if (this.beforeApi) {
                    this.currentIndex = parseInt(options.id % 5, 10) + 1;
                } else {
                    this.currentIndex = parseInt(options.id % 5, 10) || 0;
                }
            } else {
                let currentSize = this.currentSize;
                this.currentIndex = this.scrollToLeft
                    ? this.beforeApi ? currentSize : currentSize - 1 : 1;
            }

            if (!this.options.size) {
                this.currentIndex = Number(this.options.id);
            }

            this.currentPageIndex = this.currentIndex;

            return pageMap;
        },
        fetchChangePageStatus() {
            if (this.currentPage === 0 && this.currentPageIndex <= 0) {
                this.beforeStatus = false;
            } else if (!this.nextApi
                && this.currentPageIndex >= this.currentSize)
            {
                this.nextStatus = false;
            } else if (!this.options.size && this.currentPageIndex >= this.currentSize - 1) {
                this.nextStatus = false;
            } else {
                this.beforeStatus = true;
                this.nextStatus = true;
            }
        },
        onResize: core.debounce(function () {
            this.getContentHeight();
        }, 300)
    },
    components: {
        ImMsg,
        ListLoading,
        'b-navigate': Navigate,
        'med-container': Container
    }
};
</script>

<style lang="less" scoped>
.spe-topic-im {
    background: #f6f6f6;
    padding-bottom: 44px;
    &-view {
        height: calc(100% - 104px);
        margin: 20px 7px;
        padding: 0 10px;
        background: #FFF;
        box-shadow: 0 10px 50px 0 rgba(0,0,0,.08);
        border-radius: 15px 15px 0 0;
        overflow: hidden;

        &-header {
            font-size: .24rem;
            color: #333;
            line-height: normal;
            padding: 20px 13px 15px;
            font-weight: bold;
        }

        &-line {
            margin: 0 -10px;
        }

        &-im {
            margin-top: 18px;
        }
    }

    &-loading {
        position: absolute;
        top: 20px;
        bottom: 65px;
        left: 20px;
        right: 20px;
        background: #FFF;
        padding-top: 65%;
        box-shadow: 0 10px 50px 0 rgba(0,0,0,.08);
        border-radius: 15px;

        &-wrapper {
            position: absolute;
            top:0 ;
            bottom: 0;
            left: 0;
            right: 0;
            background: #FFF;
        }
    }

    &-footer {
        position: fixed;
        bottom: 0;
        left: 0;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        background: #f6f6f6;
        font-weight: bold;
    }
}
.im-bottom-placeholder {
    width: 100%;
    height: 70px;
    display: block;
}
.spe-topic-activity-share {
    height: 44px;
    line-height: 44px;
    background-image: linear-gradient(-134deg, #00D3EA 0%, #05CFCD 61%, #00CFA3 100%);
    border-radius: 22px;
    font-size: 17px;
    text-align: center;
    color: #fff;
    margin: 0 auto;
    &-wrapper {
        position: absolute;
        left: 7px;
        bottom: 20px;
        width: calc(100% - 44px);
        margin: 0 auto;
        background: #fff !important;
        padding: 10px 15px;
        border-radius: 0 0 15px 15px;
        z-index: 999;
    }
}
</style>

<style lang="stylus">
.spe-topic-im {
    [class*=im-list] {
        padding: 15px 0 15px 0;
    }

    &-footer {
        .green {
            color: #00C8C8;
        }
        .gray {
            color: #999;
        }
    }
}
</style>