<template>
    <med-container hide-header @topbarHeightHandle="topbarHeightHandle">
        <!-- 头部 -->
        <custom-header
            v-if="backgroundImg"
            ref="customHeaderRef"
            :background="backgroundImg"
            text-color="#000"
            :custom-height="topHeight + 176 + 'px'"
            is-slot
            :is-mask="false"
        >
            <view class="spe-summary-header" :style="{'padding-top': topHeight + 'px'}">
                <view>
                    <view class="c-gap-top-large c-gap-bottom-large">
                        <view v-if="title" class="spe-summary-title c-gap-bottom-small">{{ title }}</view>
                        <view v-if="slogan" class="spe-summary-slogan c-gap-bottom">{{ slogan }}</view>
                        <view
                            v-if="btnText"
                            class="spe-summary-btn"
                            @tap="makePhoneCall('120')"
                        >
                            <view class="spe-summary-btnText">{{ btnText }}</view>
                        </view>
                    </view>
                </view>
            </view>
        </custom-header>
        <!-- 导航 -->
        <view
            id="tabContainer"
            :class="{'spe-summary-fix': tabConf.tabFixed}"
            :style="{top: topHeight + 'px'}"
        >
            <c-navs
                v-if="tabs.length > 1"
                :options="tabs"
                :selected-index="tabSelected"
                selected-color="#00C8C8"
                selected-font-weight="bold"
                :border-bottom="true"
                :height="43"
                color="#252525"
                scroll
                class="spe-summary-nav"
                @itemtap="tabChange"
            >
            </c-navs>
        </view>
        <!-- 占位 -->
        <view v-if="tabConf.tabFixed" :style="{width: '100%', height: '44px'}" ></view>
        <!-- 导航内容 -->
        <view class="spe-summary-wrapper">
            <view
                v-for="(content, cIndex) in contentList"
                :id="'tabItem' + cIndex"
                :key="cIndex"
            >
                <view v-if="cIndex < contentList.length">
                    <!-- img -->
                    <view v-if="content.list[0].img">
                        <view v-if="content.list && content.list.length > 0">
                            <view class="spe-summary-subtitle c-gap-inner-top-large">{{ content.title }}</view>
                            <view class="spe-summary-cont c-gap-inner-top-large">
                                <view
                                    v-for="(item, index) in content.list"
                                    :key="index"
                                    class="spe-summary-img c-gap-bottom-large c-gap-inner-left-large"
                                    :style="{
                                        'background-image': 'url(' + item.img + ')'
                                    } | imgCompress('background-image', {column: 6})"
                                    @tap="toLink(item.url)"
                                >
                                    <view>
                                        <view class="spe-summary-img-tit c-font-17">{{ item.text }}</view>
                                        <view class="spe-summary-img-desc">{{ item.desc }}</view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- tag -->
                    <view v-else>
                        <view v-if="content.list && content.list.length > 0">
                            <view class="spe-summary-subtitle c-gap-inner-top-large">{{ content.title }}</view>
                            <view class="spe-summary-cont2 c-gap-inner-top-large">
                                <view
                                    v-for="(item, index) in content.list"
                                    :key="index"
                                    class="spe-summary-tag c-gap-bottom-large"
                                    @tap="toLink(item.url)"
                                >
                                    <view class="c-font-14 spe-summary-tag-text">{{ item.text }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <view v-if="recommendList && recommendList.length > 0">
            <!-- 分割线 -->
            <view class="spe-summary-separated"/>
            <!-- 推荐列表 -->
            <view :id="'tabItem' + contentList.length" class="spe-summary-wrapper">
                <view class="spe-summary-subtitle c-gap-top-large c-gap-inner-top-large">相关阅读</view>
            </view>
            <recommend-item
                v-for="(recommend, index) in recommendList"
                :key="index"
                :top-line="false"
                :bottom-line="index < recommendList.length - 1"
                :title="recommend.title || ''"
                :doctor="{
                    name: recommend.doctor || '',
                    rank: recommend.information || '',
                    label: recommend.hospi_level || '',
                    hospital: recommend.hospital || '',
                    image: recommend.portrait || ''
                }"
                :image="recommend.imageUrl"
                :url="recommend.url || ''"
            />

            <!-- 加载 -->
            <list-loading
                v-show="loadStatus === 'loading'"
                :status="loadStatus"
            />
            <view v-show="noMore" class="spe-summary-nomore">没有更多内容了</view>
            <view class="swan-security-padding-bottom"></view>
        </view>

    </med-container>
</template>

<script>
/**
* @file 急救聚合页
* @author lixue25
*/
import * as conf from '../../../../utils/conf';
import {request} from '../../../../utils/request';
import {navigate} from '../../../../utils/navigate';
import {send} from '../../../../utils/log';
import Container from '../../../../components/common/container';
import CustomHeader from '../../../../components/speTopic/CustomHeader';
import Navs from '@baidu/med-ui/components/Navs/Navs';
import RecommendItem from '../../../../components/speTopic/Recommend/RecommendItem';
import ListLoading from '../../../../components/common/list-loading';

export default {
    config: {
        navigationStyle: 'custom',
        navigationBarTextStyle: 'black'
    },
    components: {
        ListLoading,
        'med-container': Container,
        'custom-header': CustomHeader,
        'c-navs': Navs,
        'recommend-item': RecommendItem,
    },
    data() {
        return {
            topHeight: 0,
            options: '',
            env: '',
            title: '',
            slogan: '',
            btnText: '',
            backgroundImg: '',
            tabs: [],
            tabSelected: 0,
            contentList: [],
            recommendList: [],
            loadStatus: 'init',
            requesting: false,
            noMore: false,
            api: '/med/page/jp/science/topic?query=recall&mtopic=emergency',
            pn: 0,
            tabConf: {
                tabFixed: false,
                tabTop: 0
            },
            isScrollTab: false
        };
    },
    onLoad(options) {
        this.options = options;
        this.getPageData(options);
    },
    onReady() {
        this.env = process.env.MARS_ENV;
    },
    onPageScroll(scrollInfo) {

        this.$refs.customHeaderRef.onPageScroll(scrollInfo);

        // 计算吸顶
        // console.log(scrollInfo);
        // console.log(this.tabs[this.tabSelected].top);
        if (this.tabConf.tabTop) {
            this.tabConf.tabFixed = scrollInfo.scrollTop >= this.tabConf.tabTop;
        }

        if (this.isScrollTab && scrollInfo.scrollTop === this.tabs[this.tabSelected].top) {
            this.isScrollTab = false;
        }
        !this.isScrollTab && this.scrollToView(scrollInfo);
    },
    onReachBottom() {
        !this.noMore && !this.requesting && this.onLoadMore();
    },
    methods: {
        topbarHeightHandle(e) {
            this.topHeight = e;
        },
        scrollToView(scrollInfo) {
            // console.log('toview');
            this.tabs.forEach((item, index) => {
                if (item.top && scrollInfo.scrollTop >= item.top) {
                    this.$set(this, 'tabSelected', index);
                }
            });
            if (this.tabs[0] && scrollInfo.scrollTop < this.tabs[0].top) {
                this.$set(this, 'tabSelected', 0);
            }
        },
        // 获取数据
        getList() {
            return new Promise((resolve, reject) => {
                request({
                    url: conf.apiHost + this.api,
                    method: 'GET',
                    data: Object.assign({
                        vn: 'med',
                        feed: '1',
                        pn: this.pn++
                    }, this.options),
                    isFirstScreen: true,
                    isNeedLogin: false,
                }).then(res => {
                    resolve(res);
                }).catch(() => {
                    reject();
                });
            });
        },
        getPageData(options) {
            this.getList()
                .then(({data, update}) => {
                    // console.log(data);
                    // 页面数据赋值
                    if (data.header) {
                        this.title = data.header.title || '';
                        this.slogan = data.header.slogan || '';
                        this.btnText = data.header.btnText || '';
                        this.backgroundImg = data.header.banner || '';
                    }
                    if (data.entries && data.entries.length > 0) {
                        this.tabs = data.entries.map(item => {
                            return {
                                'text': item.title
                            };
                        });
                        this.contentList = data.entries;
                    }
                    if (data.recommends && data.recommends.length > 0) {
                        this.recommendList = data.recommends;

                        // 站位，滚动获取top
                        this.tabs.push({
                            text: '相关阅读'
                        });
                    }
                    if (!data.recommends || data.recommends.length < 10) {
                        this.noMore = true;
                    }
                    this.$mpUpdated().then(() => {
                        this.setTabsTop();
                        this.tabs.forEach((element, index) => {
                            this.setTabItemTop(index);
                        });
                    });
                    update.call(this);
                }).catch(error => console.error(error));
        },
        // 拨打电话
        makePhoneCall(tel) {
            if (!tel) {
                return;
            }
            this.$api.makePhoneCall({
                phoneNumber: tel,
                fail: err => {
                    this.$api.showModal({
                        title: '拨打失败',
                        content: '请检查是否输入了正确的电话号码',
                        showCancel: false
                    });
                }
            });
            send({
                type: 'b',
                action: 'spe_summary_call',
                extra: Object.assign({
                    ref: this.options.sf_ref || ''
                })
            });
        },
        tabChange(obj) {
            this.isScrollTab = true;
            this.tabSelected = obj.index;
            this.$api.pageScrollTo({
                scrollTop: this.tabs[obj.index].top,
                duration: 300
            });
            send({
                type: 'b',
                action: 'spe_summary_tab',
                extra: Object.assign({
                    ref: this.options.sf_ref || ''
                })
            });
        },
        toLink(url, extra) {
            if (url) {
                navigate({
                    url
                });
            }
            send({
                type: 'b',
                action: 'spe_summary_click',
                extra: Object.assign({
                    ref: this.options.sf_ref || ''
                })
            });
        },
        onLoadMore() {
            this.requesting = true;
            this.loadStatus = 'loading';
            this.getList()
                .then(({data, update}) => {
                    if (data.recommends && data.recommends.length > 0) {
                        this.recommendList = this.recommendList.concat(data.recommends);
                    }
                    if (!data.recommends || data.recommends.length < 10) {
                        this.noMore = true;
                    }
                    this.loadStatus = 'init';
                    this.requesting = false;
                })
                .catch(error => console.error(error));
        },
        setTabsTop() {
            setTimeout(() => {
                this.$api.createSelectorQuery().selectViewport().scrollOffset(viewport => {
                    const scrollTop = viewport.scrollTop;
                    const query = this.$api.createSelectorQuery().select('#tabContainer');
                    query.boundingClientRect(rect => {
                        const {top} = rect || {};
                        if (top) {
                            this.tabConf.tabTop = Math.floor(top + scrollTop - this.topHeight);
                            // console.log(rect);
                        } else {
                            this.setTabsTop();
                        }
                    })
                        .exec();
                }).exec();
            }, 20);
        },
        setTabItemTop(idx) {
            setTimeout(() => {
                this.$api.createSelectorQuery().selectViewport().scrollOffset(viewport => {
                    const scrollTop = viewport.scrollTop;
                    const query = this.$api.createSelectorQuery().select('#tabItem' + idx);
                    query.boundingClientRect(rect => {
                        const {top} = rect || {};
                        if (top) {
                            this.tabs[idx].top = Math.floor(top + scrollTop - this.topHeight - 44);
                            // console.log(rect);
                        } else {
                            this.setTabItemTop(idx);
                        }
                    })
                        .exec();
                }).exec();
            }, 20);
        }
    }
};
</script>

<style lang="less" scoped>
.spe-summary {
    // &-header {

    // }
    &-wrapper {
        padding: 5px 17px 0 17px;
    }

    &-title {
        font-family: PingFang-SC-Semibold;
        font-size: 40px;
        color: #00c8c8;
        line-height: 40px;
    }

    &-slogan {
        width: 60%;
        font-family: PingFang-SC-Regular;
        font-size: 14px;
        color: #555;
        line-height: 20px;
    }

    &-btn {
        display: inline-block;
        padding: .11rem .16rem;
        background: #ff6050;
        border-radius: 18px;
    }

    &-btnText {
        font-family: PingFang-SC-Medium;
        font-size: 14px;
        color: #fff;
        line-height: 14px;
    }

    &-subtitle {
        font-family: PingFangSC-Medium;
        font-size: 19px;
        color: #333;
        letter-spacing: 0;
        line-height: 17px;
    }

    &-cont {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
    }

    &-img {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        box-sizing: border-box;
        height: .8rem;
        width: calc(50% - 6px);
        border-radius: 8px;
        background-repeat: no-repeat;
        background-position: 0 0;
        background-size: 100% 100%;

        &-tit {
            font-weight: bold;
            color: #333;
        }

        &-desc {
            font: 12px/23px 'PingFangSC-Regular', Arial, Helvetica, sans-serif;
            color: #252525;
        }
    }

    &-cont2 {
        display: flex;
        justify-content: flex-start;
        align-items: stretch;
        flex-wrap: wrap;
    }

    &-tag {
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        width: calc(33.3% - 7.5px);
        background: #f8f8f8;
        border-radius: 6px;
        color: #333;
        padding: .1rem;
        margin-right: 11.25px;

        &-text {
            text-align: center;
        }

        &:nth-child(3n) {
            margin-right: 0px;
        }
    }

    &-separated {
        height: .08rem;
        background: #f6f6f6;
    }

    &-nomore {
        padding-bottom: 15px;
        font-size: 14px;
        color: #999;
        text-align: center;
    }

    &-fix {
        width: 100%;
        box-sizing: border-box;
        position: fixed;
        top: 44px;
        background: #fff;
        z-index: 99;
    }
    // &-nav {

    // }
}

</style>
