<template>
    <med-container
        class="method_page"
        @topbarHeightHandle="topbarHeightHandle"
    >
        <c-navs
            a-if="list.length > 0"
            :options="list"
            :selected-index="tabSelect"
            :height="45"
            selected-color="#00c8c8"
            class="method_fix_nav method_navs"
            :style="{'top': env === 'swan' ? '0rem' : (topbarHeight + 'px'), 'padding': '0 .17rem'}"
            :scroll="list.length > 3"
            @itemtap="handleTabTap"
        />
        <view class="tab-result-wrapper">
            <!-- <c-page-loading  v-if="loading" :z-index="202"></c-page-loading> -->
            <!-- tag -->
            <tag-navs
                a-if="tagList.length > 0"
                :options="tagList"
                :bottom-line="false"
                scroll
                :selected-index="tagSelect"
                :env="env"
                class="method_fix_nav method_wrapper"
                :style="{
                    'top': list.length > 0 ? (tagTop + 46) + 'px' : tagTop + 'px',
                    'padding': env === 'swan' ? '0 .17rem' : '0.1rem 0.17rem',
                }"
                @itemtap="handleTagTap"
            />
            <view
                id="doctor"
                class="method_wrapper"
                :style="{'padding-top': paddingTop + 'px'}"
            >
                <!-- 医生 -->
                <view class="method_doctor">
                    <view v-if="doctor.img" class="method_doctor_wrapper">
                        <c-image
                            has-compress
                            :src="doctor.img"
                            width=".35rem"
                            height=".35rem"
                            :is-round="false"
                            radius="50%"
                        />
                    </view>
                    <view :style="{'margin-left': env === 'swan' ? '0.08rem' : '0rem'}">
                        <view class="method_doctor_name">{{ doctor.name }}</view>
                        <view
                            class="method_doctor_info c-line-clamp1"
                        >{{ doctor.hospital }}&nbsp;{{ doctor.title }}</view>
                    </view>
                </view>
                <view style="margin-top: 0.15rem;"/>
            </view>
            <view class="method_wrapper">
                <!-- 视频 -->
                <view class="SHOW_LOG_MODULE" :data-show="'aid-method-video' + tabSelect">
                    <video
                        v-if="doctor.video"
                        id="methodVideo"
                        :src="doctor.video.src"
                        :poster="doctor.video.poster"
                        :controls="true"
                        :autoplay="fullScreen"
                        direction="90"
                        objectFit="contain"
                        type="video/mp4"
                        :class="env === 'swan' ? 'video-swan' : 'video-h5'"
                        :style="{'width': videoWidth + 'px'}"
                        :x5-video-orientation="fullScreen ? 'landscape' : 'normal'"
                        @play="bindplay"
                    ></video>
                </view>
                <!-- 标题 -->
                <view v-if="tagList" class="tag_list">
                    <view class="method_content_divider"/>
                    <view
                        v-for="(categoryLv1, index) in tagListContent"
                        :key="index"
                        class="module-list"
                    >
                        <view
                            v-if="index < tagList.length - 1"
                            :data-show="'aid-method' + categoryLv1.title + tabSelect"
                            class="SHOW_LOG_MODULE"
                        >
                            <view class="tag_list_hr"/>
                            <tag-list
                                :ref="'categoryLv' + index"
                                :category-lv1="categoryLv1"
                                :index="index"
                                @update="update"
                            />
                        </view>
                    </view>
                </view>
                <!-- 特别提示 -->
                <view
                    v-if="tips"
                    class="method_tips module-list"
                    :style="{'padding-bottom': env === 'swan' ? '0.08rem' : '0.2rem'}"
                >
                    <view
                        class="method_tips_title SHOW_LOG_MODULE"
                        :data-show="'aid-method' + tips.title + tabSelect"
                    >{{ tips.title }}</view>
                    <view class="method_tips_content">
                        <view v-if="tips.description">
                            <view v-for="(desc, index) in tips.description" :key="index">{{ desc }}</view>
                        </view>
                        <view v-if="doctor.video">
                            <c-button
                                primary-color="#000"
                                border-radius="57px"
                                :font-size="17"
                                class="method-btn"
                                @tap.stop="clickBtn"
                            >
                                <c-icon
                                    name="play-circle"
                                    :style="{color: '#00C8C8'}"
                                    font-size="0.17rem"
                                />
                                观看视频
                                {{ title }}
                            </c-button>
                        </view>
                    </view>
                </view>
                <!-- banner入口 -->
                <view
                    v-if="banner.img"
                    class="aid-banner"
                    :style="{'padding-bottom': env === 'swan' ? '0.15rem' : '0.2rem'}"
                >
                    <view class="aid-banner-bar"/>
                    <view class="aid-banner-title">{{ banner.title }}</view>
                    <c-navigate
                        :url="banner.url"
                        :extra="{
                            module: 'aid_banner',
                        }"
                    >
                        <view
                            class="aid-banner-img"
                            :style="{
                                'background-image': 'url(' + banner.img + ')'
                            } | imgCompress('background-image', {column: 12})"
                        />
                    </c-navigate>
                </view>
            </view>

        </view>
    </med-container>
</template>
<script>
/**
* @file 急救专题
* @author lixue25
*/
// 注意：vue 文件中使用组件按照 vue 规范的 components 字段配置即可，无需在 config 中配置 usingComponents
import MedContainer from '../../../components/common/container';
import CNavs from '@baidu/med-ui/components/Navs/Navs';
import TagNavs from '../../../components/speTopic/tagNavs';
// import CAvatar from '@baidu/med-ui/components/Avatar/Avatar';
import CButton from '@baidu/med-ui/components/Button/Button';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import TagList from '../../../components/speTopic/tagList';
// import pageloading from '../../../components/common/pageloading';
import CNavigate from '../../../components/common/navigate';

import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import {request} from '../../../utils/request';
import * as conf from '../../../utils/conf';
import {send, ShowLog} from '../../../utils/log';
import * as domUtil from '../../../utils/domUtil';
import CImage from '@components/common/image';

const showLog = new ShowLog();

export default {
    config: {},
    components: {
        MedContainer,
        CNavs,
        TagNavs,
        // CAvatar,
        TagList,
        CButton,
        CIcon,
        // 'c-page-loading': pageloading,
        CNavigate,
        CImage
    },
    data() {
        return {
            title: '',
            topbarHeight: 0,
            tabs: null,
            display: null,
            list: [],
            tabSelect: 0,
            tagList: [],
            tagListContent: [],
            tagSelect: 0,
            doctor: {},
            tips: [],
            env: 'swan',
            show: false,
            videoWidth: 0,
            arrTop: [], // 存储tag对应位置
            paddingTop: 0,
            tagTop: 0,
            tagIsClick: false,
            fullScreen: false,
            // loading: true,
            videoPlayLogFlag: false,
            responseData: '',
            banner: {}
        };
    },
    onInit(options) {
        const systemInfo = getSystemInfo();
        this.videoWidth = systemInfo.screenWidth - 34;

        this.tabSelect = options.tabSelected ? (+options.tabSelected) : 0;
        this.tagSelect = options.tagSelected ? (+options.tagSelected) : 0;
        this.tagFlag = !!options.tagSelected;

        // 进入全屏播放入口
        // this.fullScreen = options.fromSearch === '1';

        // h5反爬取接入
        if (process.env.MARS_ENV === 'h5') {
            domUtil.getResponseData().then(responseData => {
                window.localStorage.setItem('responseData', JSON.stringify(responseData));
            });
        }

        this.init(options);

    },
    onReady() {
        this.env = process.env.MARS_ENV;
        // 曝光日志
        showLog.init();
    },
    onHide() {
        showLog.remove();
    },
    onPageScroll() {
        this.pause();

        if (!this.tagIsClick) {
            const query = this.$api.createSelectorQuery();
            query.select('#doctor').boundingClientRect(data => {
                this.doctorTop = -(data.top + this.paddingTop);
            }
            ).exec();
            query.selectViewport().scrollOffset().exec(() => {
                this.tagList.forEach(() => {
                    const query = this.$api.createSelectorQuery();
                    query.selectAll('.module-list').boundingClientRect();
                    query.exec(res => {
                        this.queryresult = res;
                    });
                });
            });
            let doctorMap = this.queryresult && this.queryresult[0] && this.queryresult[0].map(item => item.height);
            let count = 0;
            let i = 0;
            // console.log('doctorTop', this.doctorTop);
            // console.log('doctorMap', doctorMap);
            let distance = this.env === 'swan' ? 118 : 158;
            if (doctorMap) {
                for (i; i < this.tagList.length; i++) {
                    count += i > 0 ? doctorMap[i] + 29 : doctorMap[i];
                    if (this.doctorTop < count + distance) {
                        break;
                    }
                }
                if (i === this.tagList.length) {
                    i--;
                }
                this.tagSelect = i;
                // console.log(this.tagSelect);
            }
            // console.log(i);
        }
        else {
            this.tagIsClick = false;
        }
    },
    methods: {
        init(options) {
            request({
                url: conf.apiHost + '/med/page/jp/emergency',
                method: 'GET',
                data: Object.assign(
                    {},
                    options,
                    /* eslint-disable max-len */
                    process.env.MARS_ENV === 'h5' && window.localStorage.getItem('responseData') ? {responseData: window.localStorage.getItem('responseData')} : {}
                    /* eslint-enable max-len */
                ),
                isNeedLogin: false,
                isFirstScreen: true
            }).then(res => {

                this.tabs = res.data.tabs;
                this.display = res.data.display;

                if (String(this.tabs.selected)) {
                    this.tabSelect = this.tabs.selected;
                }

                if (this.tabs.list) {
                    this.list = this.tabs.list;
                    this.list.forEach((e, index) => {
                        e.text = e.type;
                    });
                }
                this.tagList = this.display.data.categoryLv1;
                this.tagListContent = this.display.data.categoryLv1;

                if (this.display.data.tips) {
                    this.tips = this.display.data.tips;
                    this.tagList.push(this.tips);
                }

                this.tagList.forEach((e, index) => {
                    e.text = e.title;
                    e.idx = index;
                });
                this.doctor = this.display.Doctor;

                if (this.env === 'swan') {
                    this.tagTop = 0;
                    if (this.list.length > 0) {
                        this.paddingTop = 104;
                    }
                    else {
                        this.paddingTop = 57;
                    }
                }
                else {
                    this.tagTop = this.topbarHeight;
                    if (this.list.length > 0) {
                        this.paddingTop = 99;
                    }
                    else {
                        this.paddingTop = 54;
                    }
                }
                res.update.call(this, () => {
                    this.banner = res.data.banner || {};
                    // this.loading = false;
                    domUtil.getRect('.module-list', rect => rect[0].length === this.tagList.length + 1)
                        .then(rect => {
                            if (options.type === 'tabClick') {
                                this.tagIsClick = true;
                            }
                            this.arrTop = rect[0];
                            let dist = this.env === 'swan' ? 0 : 39;
                            if (this.tagFlag) {
                                this.pageScroll(dist);
                            }
                            this.video = this.$api.createVideoContext('methodVideo');
                        });

                    // pv日志
                    send({
                        type: 'l',
                        action: 'aidMethodpv',
                        extra: {
                            type: this.list.length > 0 ? this.list[this.tabSelect].type : 'noTab'
                        }
                    });
                    this.videoPlayLogFlag = false;
                });
            }).catch(err => {
                // console.log(err);
                if (process.env.MARS_ENV === 'h5' && err.status === 3) {
                    send({
                        type: 'l',
                        action: 'interceptCrawl'
                    });
                }
            });
        },
        topbarHeightHandle(e) {
            this.topbarHeight = e;
        },
        handleTabTap(obj) {
            this.pause();

            this.tagIsClick = true;

            this.tagSelect = 0;

            this.tagFlag = false;

            this.$api.pageScrollTo({
                scrollTop: 0,
                duration: 0,
                success: () => {
                    showLog.reset();
                }
            });

            this.tabSelect = obj.index;

            obj.q = obj.item.jump_url;
            obj.type = 'tabClick';

            // this.loading = true;

            this.init(obj);

            send({
                type: 't',
                action: 'aidMethodTabTap',
                extra: { // 自定义字段，需要则添加
                    type: obj.item.type
                }
            });
        },
        handleTagTap(obj) {
            this.tagIsClick = true;

            this.tagSelect = obj.index;

            this.pause();

            let dist = this.env === 'swan' ? 0 : 39;
            this.$api.pageScrollTo({
                scrollTop: this.arrTop[obj.index].top - (this.paddingTop + dist),
                duration: 0
            });

            send({
                type: 't',
                action: 'aidMethodTagTap',
                extra: { // 自定义字段，需要则添加
                    title: obj.item.title
                }
            });
        },
        clickBtn() {
            this.tagIsClick = true;

            this.tagSelect = 0;

            this.$api.pageScrollTo({
                scrollTop: 0,
                duration: 0
            });

            send({
                type: 'b',
                action: 'aidScrollToTopVideo'
            });
        },
        update(data) {
            this.tagList[data[1]][data[2]] = data[0];
            let idx = data[1];
            this.tagList[(+idx)]['category' + (+data[2])] = data[0];
        },
        pause() {
            if (this.video && (this.video.video || this.video.videoId)) {
                this.video.pause();
            }
        },
        bindplay() {
            if (!this.videoPlayLogFlag) {
                send({
                    type: 'vid',
                    action: 'aidMethodVideoPlay',
                    extra: {
                        type: this.list.length > 0 ? this.list[this.tabSelect].type : 'noTab'
                    }
                });
                this.videoPlayLogFlag = true;
            }
        },
        pageScroll(dist) {
            this.$api.pageScrollTo({
                scrollTop: Math.floor(this.arrTop[this.tagSelect].top - (this.paddingTop + dist)),
                duration: 0,
                success: () => {
                    const query = this.$api.createSelectorQuery();
                    query.selectViewport().scrollOffset().exec(result => {
                        if (result[0] && result[0].scrollTop < 10) {
                            this.pageScroll(dist);
                        }
                    });
                },
                fail: () => {
                    this.pageScroll(dist);
                }
            });
        }
    }
};

</script>
<style lang="less">
.method_page {
    overflow-x: hidden;
    min-height: 105vh;
}

.method_fix_nav {
    position: fixed;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 201;
}

.method_navs {
    border-bottom: 1px solid #eee;
    z-index: 203;
}

.method_wrapper {
    padding: 0rem 0.17rem 0 0.17rem;
}

.method_doctor {
    display: flex;
    align-items: center;
    line-height: normal;
}

.method_doctor_wrapper {
    display: flex;
    align-items: center;
    margin-right: .08rem;
}

.method_avatar {
    width: 0.35rem !important;
    height: 0.35rem !important;
    margin-right: .08rem;
    border-radius: 50%;
}

.method_doctor_name {
    font-size: 0.16rem;
    color: #333;
}

.method_doctor_info {
    font-size: 0.13rem;
    color: #999;
}

.tag_list_hr {
    height: 0.08rem;
    margin: 0.13rem -0.17rem 0.2rem -0.17rem;
    background: #f8f8f8;
}

.video-h5 {
    width: 100%;
    height: 1.917rem;
    top: 0;

    .video-h5 > div {
        background-size: contain !important;
    }
}

.video-swan {
    width: 100vw;
    padding-bottom: 0;
    height: 56.22vw;
    top: 0;

    .video-swan > div {
        background-size: contain !important;
    }
}

.method_content_divider {
    margin: 0.10rem 0 0.2rem 0;
}

.method_tips {
    margin: 0.3rem 0 0;
    background: rgba(3, 208, 191, 0.1);
    border-radius: 24px;
    font-family: PingFang-SC-Regular;
    font-size: 0.17rem;
    color: #333;
    letter-spacing: 0;
    line-height: 0.31rem;
    padding: 0.3rem 0.3rem 0.255rem 0.3rem;

    .method_tips_title {
        font-family: PingFangSC-Medium;
        font-size: 0.21rem;
        color: #00c8c8;
    }

    .method-btn {
        margin: 0.15rem 0.3rem;
        border: 0 !important;
    }
}

.aid-banner {
    &-bar {
        height: .08rem;
        margin: .2rem -.17rem .05rem -.17rem;
        background: #f8f8f8;
    }

    &-title {
        font-size: .18rem;
        line-height: .48rem;
        font-weight: bold;
    }

    &-img {
        width: 100%;
        height: .8rem;
        background-size: cover;
        border-radius: 10px;
    }
}

</style>
