<template>
    <c-container
        :menu="menu"
        :title="pageTitle"
        :is-skt-show="!isPageRender"
        skt-tpl="speTopic"
        @topbarHeightHandle="topbarHeightHandle"
    >
        <canvas v-if="false"/>
        <view
            :style="{
                top: env === 'swan' ? '0' : topbarHeight + 'px'
            }"
            class="speTopic-group-navs"
        >
            <navs
                v-if="navs && navs.length > 0"
                :options="navs"
                :selected-color="navConfig.selectedColor"
                :color="navConfig.color"
                :font-size="navConfig.fontSize"
                :selected-index="navConfig.selectedIndex"
                @itemtap="onClickNavs"
            />
        </view>
        <view class="speTopic-group-content">
            <view v-if="loading" class="speTopic-group-content-loading">
                <c-page-loading :z-index="99"/>
            </view>
            <view
                v-if="!loading && recommends && recommends.length"
                :style="{
                    marginTop: '41px'
                }"
                v-bind:class="showLogClass"
                :data-show="'spe-topic-group-' + navConfig.selectedIndex"
            >
                <recommends
                    :recommends="recommends"
                    :show-log-class="showLogClass"
                    page="group"
                    module="speTopic-group"
                />
                <list-loading
                    v-show="loadStatus === 'loading'"
                    :status="loadStatus"
                />
            </view>
        </view>
    </c-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 {isUnRead} from '@utils/msg';
import Recommends from '@components/speTopic/Recommend/index';
import CContainer from '@commonComponents/container';
import CPageLoading from '@commonComponents/pageloading';
import ListLoading from '@commonComponents/list-loading';
import Navs from '@baidu/med-ui/components/Navs/Navs';

export default {
    data() {
        return {
            pageTitle: ' ',
            tabs: [],
            recommends: [],
            navs: [],
            navConfig: {
                selectedColor: '#00C8C8',
                color: '#2A2A2A',
                fontSize: 15,
                selectedIndex: 0
            },
            env: 'swan',
            topbarHeight: 0,
            isPageRender: false,
            loading: false,
            menu: [],
            showLogClass: 'SHOW_LOG_MODULE_' + core.rand(6),
            showLogIns: null,
            pn: 0,
            loadStatus: 'init',
            hasMore: '0',
            requesting: false
        };
    },
    onLoad(options) {
        this.env = process.env.MARS_ENV;
        this.getPageData(options);
        isUnRead();
    },
    onShow() {
        this.$api.setTabBarStyle({
            color: '#aaaaaa',
            selectedColor: '#01c8c7'
        });
    },
    onHide() {
        if (this.showLogIns) {
            this.showLogIns.reset();
            this.showLogIns.remove();
        }
    },
    onReachBottom() {
        this.hasMore === '1' && !this.requesting && this.onLoadMore();
    },
    methods: {
        getPageData(options) {
            const data = ['query', 'mtopic'].reduce((r, key) => {
                if (options[key]) {
                    r[key] = options[key];
                }
                return r;
            }, {});

            this.getDataBase(data, '/med/page/jp/feed/list')
            .then(data => {
                const dataKeyHash = ['pageTitle', 'tabs', 'recommends'];
                dataKeyHash.forEach(key => this[key] = data[key]);
                this.getNavs(this.tabs);

                this.$mpUpdated(() => {
                    this.isPageRender = true;
                    if (process.env.MARS_ENV === 'swan') {
                        this.$mp.scope.removeSkeleton();
                    }

                    // 更新数据，页面渲染完成后，获取nav的top值，用于吸顶判断
                    try {
                        this.showLogIns = new ShowLog();
                        this.showLogIns.SIGN = '.' + this.showLogClass;
                        this.showLogIns.init();
                    } catch (error) {
                        console.error(error);
                    }
                });
            })
            .catch(error => console.error(error));
        },
        topbarHeightHandle(e) {
            this.topbarHeight = e;
        },
        getNavs(tabs) {
            if (tabs && tabs[0]) {
                tabs.forEach((tab, index) => {
                    this.navs.push({text: tab.text});
                    if (tab.selected === '1') {
                        this.navConfig.selectedIndex = index;
                    }
                });
            }
        },
        onClickNavs({item, index}) {
            this.navConfig.selectedIndex = index;
            this.loading = true;
            this.pn = 0;

            this.getDataBase({}, this.tabs[index].xhrUrl)
            .then(data => {
                this.recommends = data.recommends;
                this.loading = false;
            });

            send({
                type: 't',
                action: 'sideslip',
                extra: {
                    page: 'speTopicGroup'
                }
            });

            try {
                if (this.showLogIns) {
                    this.showLogIns.reset();
                    this.showLogIns.__fetchRects();
                }
            } catch (error) {
                console.log(error);
            }
        },
        getDataBase(params, url) {
            params.pn = this.pn;
            this.requesting = true;
            return new Promise((resolve, reject) => {
                request({
                    url: conf.apiHost + url,
                    method: 'GET',
                    data: params,
                    isFirstScreen: true,
                    isNeedLogin: false,
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(({data, update}) => {
                    if (this.navConfig.selectedIndex === 0) {
                        data.recommends.unshift({
                            style: '2',
                            imageUrl: 'https://expertimg.cdn.bcebos.com/expertcms/med/banner_sari3.png',
                            ratio: 124 / 375,
                            /* eslint-disable */
                            url: '/pages/speTopic/activity/index?pd=med&openapi=1&from_sf=1&resource_id=5216&vn=med&atn=sarihome&sf_ref=list_fybook'
                        });
                    }
                    resolve(data);
                    this.hasMore = data.hasMore || '0';
                    this.requesting = false;
                    update.call(this);

                    this.pn++;
                })
                .catch(error => reject(error));
            });
        },
        onLoadMore() {
            let next;
            const tabIndex = this.navConfig.selectedIndex;
            this.requesting = true;
            if (this.tabs && this.tabs[tabIndex]) {
                next = this.tabs[tabIndex].next;

                next && (this.loadStatus = 'loading');

                next && request({
                    url: conf.apiHost + next,
                    method: 'GET',
                    data: {
                        pn: this.pn
                    },
                    isFirstScreen: true,
                    isNeedLogin: false,
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(({data, update}) => {
                    this.recommends = this.recommends.concat(data.recommends);
                    this.pn++;

                    this.loadStatus = 'init';
                    this.requesting = false;

                    this.hasMore = data.hasMore || '0';
                    update.call(this);

                    send({
                        type: 't',
                        action: 'slideUp',
                        extra: {
                            page: 'speTopicGroup',
                            pn: this.pn
                        }
                    });
                })
                .catch(error => console.error(error));
            }
        }
    },
    components: {
        Navs,
        Recommends,
        ListLoading,
        CContainer,
        CPageLoading
    }
};
</script>

<style lang="less" scoped>
.speTopic-group {
    &-navs {
        position: fixed;
        top: 44px;
        width: 100%;
        z-index: 100;
        border-bottom: 1px solid #f1f1f1;
    }
    &-content {
        position: relative;

        &-loading {
            height: 80px;
            height: 80vh;
        }
    }
}
</style>
