<template>
    <!-- htmlcs-disable -->
    <view
        v-if="!hideTopBar"
        class="top-bar-wrapper"
        :class="barPageClass || barClass"
    >
        <template-mars target="h5">
            <!-- <share-bar v-if="!isInBaiduApp && !isInApp" :show="shareBar && shareBarShow" @onCloseShareBar="onCloseShareBar"></share-bar> -->
        </template-mars>
        <view
            class="top-bar"
            :class="[
                !isInBaiduApp && !isInApp && shareBar && shareBarShow ? 'share' : '',
                !isFixed ? 'no-fix-wid' : '',
            ]"
            :style="{
                position: isFixed ? 'fixed' : 'absolute',
                height: (barHeight ? barHeight : statusBarHeight + navigationBarHeight + slotHeight) + 'px',
                paddingTop: statusBarHeight + 'px',
                zIndex: zIndex,
                background: barBg,
            }"
        >
            <view
                v-if="!ydShowInput"
                class="bar c-row"
                :style="{
                    height: navigationBarHeight + 'px',
                }"
            >
                <view v-if="!hidePageHeader" class="c-span3 left">
                    <template v-if="!isInApp">
                        <c-icon
                            v-if="navigateBackShow"
                            name="left"
                            :style="{
                                color: textColor,
                                marginLeft: backStyle.marLeft,
                                marginTop: backStyle.marTop,
                            }"
                            :class="{
                                'icon-bg': iconBg,
                            }"
                            font-size="22px"
                            class="icon back-left"
                            @tap="handleIconTap('navigateBack')"
                        />
                        <view v-if="isHigherNavigate" class="icon-blank c-inline-block">
                            <view
                                v-if="iconBg"
                                class="icon-blank-bg"
                                :class="{'icon-bg': iconBg}"
                            />
                        </view>
                        <text
                            v-if="showHome && !hideHome"
                            :style="{
                                color: textColor,
                            }"
                            :class="{
                                'icon-bg': iconBg,
                            }"
                            class="icon m-icon m-icon-home"
                            @tap="handleIconTap('navigateHome')"
                        />
                    </template>
                </view>
                <view
                    v-if="text && !hideTitle && !hidePageHeader"
                    :style="{
                        color: textColor,
                    }"
                    class="title c-span6"
                >
                    <view
                        v-if="icon"
                        class="title-icon"
                        :style="{
                            backgroundImage: 'url(' + icon + ')',
                        }"
                    />
                    {{ text }}
                </view>
                <view v-if="!hidePageHeader && slotTitle" class="c-span6">
                    <slot name="title"></slot>
                </view>
                <view v-if="!hidePageHeader && !(env === 'h5' && slotTitle && !isInApp)" class="c-span3"/>
            </view>
            <!-- 自定义内容插槽 -->
            <slot></slot>
        </view>
        <!-- 吸顶背景延伸（用于被页面内容盖住） -->
        <view
            class="fixedbg"
            :style="{
                top: (barHeight ? barHeight : statusBarHeight + navigationBarHeight + slotHeight) + 'px',
                height: fixedbgHeight + 'px',
                zIndex: fixedbgZindex,
            }"
        />
        <!-- 占位 -->
        <view
            v-if="blank && isFixed"
            class="blank"
            :style="{
                height: (barHeight ? barHeight : statusBarHeight + navigationBarHeight + slotHeight) + 'px',
                background: blankBg,
            }"
        />
    </view>
</template>
<script>
/**
 * @file 自定义头部
 * @author zhangeryi
 * @categories 业务组件
 * @tags [component]
 */

/* global getCurrentPages, getApp, swan */
import CIcon from '@baidu/med-ui/components/Icon/Icon';
// import ShareBar from './share-bar';
import {navigate, navToH5, tabBar} from '../../utils/navigate';
import * as core from '../../utils/core';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    props: {
        /**
         * 标题
         */
        title: {
            type: String,
            default: ''
        },
        /**
         * 隐藏标题
         */
        hideTitle: {
            type: Boolean,
            default: false
        },
        /**
         * topbar高度
         */
        barHeight: {
            type: Number,
            default: 0
        },
        /**
         * 文字颜色
         */
        textColor: {
            type: String,
            default: '#fff'
        },
        /**
         * 延迟设置文字颜色
         */
        delaySetHeaderColor: {
            type: Boolean,
            default: false
        },
        /**
         * 延迟进行设备兼容
         */
        delayCompateDevices: {
            type: Boolean,
            default: false
        },
        /**
         * topbar样式名称
         */
        barClass: {
            type: String,
            default: 'green'
        },
        /**
         * 层级
         */
        zIndex: {
            type: Number,
            default: 99
        },
        /**
         * 是否需要占位
         */
        blank: {
            type: Boolean,
            default: true
        },
        /**
         * bar背景颜色
         */
        barBg: {
            type: String,
            default: ''
        },
        /**
         * 占位背景颜色
         */
        blankBg: {
            type: String,
            default: ''
        },
        /**
         * 插槽高度
         */
        slotHeight: {
            type: Number,
            default: 0
        },
        /**
         * 吸顶背景延伸高度
         */
        fixedbgHeight: {
            type: Number,
            default: 0
        },
        /**
         * 吸顶背景延伸层级 （页面内容设置position:relative z-index 来盖住延伸背景）
         */
        fixedbgZindex: {
            type: Number,
            default: 0
        },
        /**
         * 是否吸顶
         */
        isFixed: {
            type: Boolean,
            default: true
        },
        /**
         * 是否隐藏home
         */
        hideHome: {
            type: Boolean,
            default: false
        },
        /**
         * 是否隐藏回退按钮
         */
        hideBack: {
            type: Boolean,
            default: false
        },
        /**
         * 是否隐藏topbar
         */
        hideTopBar: {
            type: Boolean,
            default: false
        },
        /**
         * 标题文案左侧图标
         */
        icon: {
            type: String,
            default: ''
        },
        /**
         * 是否阻止返回
         */
        backDetain: {
            type: Boolean,
            default: false
        },
        /**
         * home 的返回地址
         */
        url: {
            type: String,
            default: ''
        },
        /**
         * icon是否带背景
         */
        iconBg: {
            type: Boolean,
            default: false
        },
        /**
         * 医典自定义头部
         */
        ydShowInput: {
            type: Boolean,
            default: false
        },
        /**
         * home跳转指定页面
         */
        newHomeUrl: {
            type: String,
            default: ''
        },
        /**
         * 分享bar配置
         */
        shareBar: {
            type: Boolean,
            default: false
        },
        /**
         * topbarHeight是否计算sharebar的高度
         */
        calShareBar: {
            type: Boolean,
            default: true
        },
        // 是否启用title插槽
        slotTitle: {
            type: Boolean,
            default: false
        }
    },
    components: {
        CIcon
        // ShareBar
    },
    data() {
        return {
            statusBarHeight: 20,
            navigationBarHeight: 44,
            shareBarHeight: 0,
            navigateBackShow: false,
            isHigherNavigate: false,
            hidePageHeader: false,
            showHome: false,
            barPageClass: '',
            text: '',
            isInApp: false,
            isInBaiduApp: true,
            shareBarShow: true,
            env: process.env.MARS_ENV,
            backStyle: {
                marLeft: '',
                marTop: ''
            },

            // 是否返回至首页
            backToHome: false
        };
    },
    watch: {
        title(title) {
            this.text = title;
        },
        barClass(v) {
            // 微信定制(滚动时不显示悬浮title)
            if (process.env.MARS_ENV === 'h5') {
                const ua = require('@searchfe/user-agent');
                const pages = getCurrentPages();
                const curPage = pages && pages.length ? pages[pages.length - 1] : {};
                if (!/\/wz.+?\//.test(curPage.route)) {
                    return;
                }
                if (ua.isWeixinApp()) {
                    this.barPageClass = 'transparent';
                }
            }
        },
        backDetain(nVal) {
            this.backDetain = nVal;
        },
        textColor(v) {
            this.setHeaderColor(v);
        },
        delaySetHeaderColor(v) {
            !v && this.setHeaderColor(this.textColor);
        },
        delayCompateDevices(v) {
            !v && this.compateDevices(getSystemInfo());
        },
        slotHeight(v) {
            /**
             * topbar高度改变
             */
            this.$emit('topbarHeightChange', this.topbarHeightGetter());
        }
    },
    created() {
        let pages = getCurrentPages();
        let curPage = pages && pages.length ? pages[pages.length - 1] : {};
        let query = {};
        let SystemInfo = getSystemInfo();

        // 是否在手百内
        this.isInBaiduApp = SystemInfo.host === 'baiduboxapp' || /\bbaidubox/.test((navigator || {}).userAgent || '');

        // 是否隐藏home
        let globalHideHome;

        if (process.env.MARS_ENV === 'swan') {
            // 小程序关闭topbar分享展示
            this.shareBar = false;

            // 设置bar高度
            this.statusBarHeight = SystemInfo.statusBarHeight;
            this.navigationBarHeight = SystemInfo.navigationBarHeight;

            // 后退按钮
            // this.isHigherNavigate =
            //     core.compareVersion(SystemInfo.swanNativeVersion, '2.28.0') >= 0
            //     && tabBar.indexOf(curPage.uri) === -1;
            this.navigateBackShow = tabBar.indexOf(curPage.uri) === -1;
            !this.delaySetHeaderColor && this.setHeaderColor(this.textColor);

            // 统计小程序topbar展现
            this.$api.reportAnalytics('topbar_show');

            // 设置query
            query = curPage.options;

            if (query.back_route === 'home') {
                this.backToHome = true;
            }

            // 判断机型
            !this.delayCompateDevices && this.compateDevices(SystemInfo);
            // home
            globalHideHome = getApp().globalData.hdhome;
        } else if (process.env.MARS_ENV === 'h5') {
            this.isInApp = getApp().globalData.isInApp;

            // 设置bar高度
            if (this.isInApp) {
                this.statusBarHeight = SystemInfo.statusBarHeight;
                this.navigationBarHeight = SystemInfo.navigationBarHeight;
                let timeout = setTimeout(() => {
                    this.setHeaderColor(this.textColor);
                    clearTimeout(timeout);
                }, 100);
            } else {
                this.statusBarHeight = 0;
                this.navigationBarHeight = 44;
            }
            // TODO 内测阶段，分享回流关闭
            // this.shareBarHeight = (!this.isInBaiduApp) && (!this.isInApp) && this.shareBar ? 60 : 0;
            // 后退按钮
            this.navigateBackShow = !this.hideBack && pages.length > 1;

            // 设置query
            query = core.getQueryObject(curPage.path);

            // home
            globalHideHome = getApp().globalData.hdhome || window.sessionStorage.getItem('hdhome');
        }
        this.showHome = curPage.uri.indexOf('brand/home/index') === -1 && !globalHideHome;

        // 设置title
        this.text = this.title || decodeURIComponent(query.title || '百度健康');

        // 微信 + 问诊定制
        if (process.env.MARS_ENV === 'h5') {
            const ua = require('@searchfe/user-agent');
            if (ua.isWeixinApp()) {
                if (/\/wz.+?\//.test(curPage.route)) {
                    this.hidePageHeader = true;
                }
            }
        }
    },
    mounted() {
        // 是否隐藏topbar
        if (this.isHideTopBar()) {
            this.hideTopBar = true;
        }

        /**
         * 获取topbar高度
         */
        this.$emit('topbarHeightHandle', this.topbarHeightGetter());
    },
    methods: {
        onPageScroll(scrollTop) {
            // TODO 内测阶段，分享回流关闭
            // if (process.env.MARS_ENV === 'h5' && !this.isInBaiduApp && !this.isInApp) {
            //     if (scrollTop > 5) {
            //         this.shareBarShow = false;
            //         this.shareBarHeight = 0;
            //     }
            //     else {
            //         this.shareBarShow = true;
            //         this.shareBarHeight = 60;
            //     }
            //     this.$emit('topbarHeightHandle', this.topbarHeightGetter());
            // }
        },
        onCloseShareBar() {
            this.shareBar = false;
        },
        compateDevices(SystemInfo) {
            if (SystemInfo.platform === 'ios' || SystemInfo.platform === 'devtools') {
                this.backStyle.marLeft = '6px';
            }
            if (SystemInfo.platform === 'android') {
                this.backStyle.marLeft = '0.01rem';
            }
            if (SystemInfo.brand === 'Redmi' || SystemInfo.brand === 'OnePlus') {
                this.backStyle.marTop = '0.01rem';
                this.backStyle.marLeft = '0.01rem';
            }
        },
        setHeaderColor(color) {
            color = color === 'white' ? '#fff' : color === 'black' ? '#000' : color;
            const hex = this.toHexColor(color).toLowerCase();
            if (hex === '#ffffff' || hex === '#000000') {
                this.$api.setNavigationBarColor({
                    frontColor: hex,
                    backgroundColor: '#ffffff' // backgroundColor必须，随便写一个
                });
            }
        },
        toHexColor(color = '') {
            if (/#\w{3}/.test(color)) {
                return (
                    '#' +
                    color
                        .replace('#', '')
                        .split('')
                        .map(d => d + d)
                        .join('')
                );
            } else if (/#\w{6}/.test(color)) {
                return color;
            } else if (/rgb?\(.+\)/.test(color)) {
                const arr = [];
                color.replace(/(\d+)/g, (w, $1) => arr.push($1));
                return '#' + arr.map(d => parseInt(d, 10).toString(16)).join('');
            }
            return '';
        },
        handleIconTap(eventName) {
            if (eventName === 'navigateBack' && this.backToHome) {
                this.toHomePage();
                return;
            }
            this.$emit('introPageHome', eventName);
            if (this.backDetain) {
                /**
                 * 阻止返回
                 */
                this.$emit(eventName, this[eventName]);
            } else {
                this[eventName]();
            }
        },
        navigateBack(delta = 1) {
            let pages = getCurrentPages();
            if (pages.length === 1 && process.env.MARS_ENV === 'swan') {
                swan.exit();
            } else {
                navigate({
                    openType: 'navigateBack',
                    // 返回的页面数，默认为1
                    delta
                });
            }
        },
        navigateHome() {
            //指定了页面
            if (this.newHomeUrl) {
                navigate({
                    url: this.newHomeUrl
                });
            } else {
                if (this.url) {
                    navToH5(this.url);
                } else {
                    if (process.env.MARS_ENV === 'swan') {
                        this.$api.reportAnalytics('topbar_home');
                    }

                    this.toHomePage();
                }
            }
        },
        toHomePage() {
            // mars 对 navigate 的跳转依赖 pages 目录，故当路由中不存在 pages 时，进行兼容跳转
            if (process.env.MARS_ENV === 'h5') {
                const curPathname = this.$route.path;
                if (curPathname.indexOf('pages') === -1) {
                    const {origin, pathname} = window.location;
                    window.location.href = `${origin}${pathname.replace(curPathname, '/pages/brand/home/index')}`;
                    return;
                }
            }
            navigate({
                openType: 'relaunch',
                url: '/pages/brand/home/index'
            });
        },
        topbarHeightGetter() {
            const shareBarHeight = this.calShareBar ? this.shareBarHeight : 0;
            let height = this.barHeight
                ? this.barHeight + shareBarHeight
                : this.statusBarHeight + this.navigationBarHeight + this.slotHeight + shareBarHeight;
            return height;
        },
        // 判断是否为iframe嵌入页面 若是则隐藏topbar
        isHideTopBar() {
            if (process.env.MARS_ENV === 'h5' && self.location !== top?.location && (/selfLocationFrom=topic/g).test(self.location.href)) {
                return true;
            }
            return false;
        }
    }
};
</script>
<style lang="less">
.top-bar-wrapper {
    // 做成样式autoprefixer可以加前缀
    &.green {
        .top-bar,
        .blank {
            background: linear-gradient(to right, #00cfa3, #05cfcd, #00d3ea);
        }
    }
    &.greentj {
        .top-bar,
        .blank {
            background: linear-gradient(134deg, #489af6 0%, #82cbff 100%);
        }
    }
    &.pinkhpv {
        .top-bar,
        .blank {
            background: linear-gradient(134deg, #ff6d8a 0%, #fc7967 100%);
        }
    }
    &.grey {
        .top-bar,
        .blank {
            background: #f5f5f5;
        }
    }
    &.vacc {
        .top-bar,
        .blank {
            // background: linear-gradient(90deg, #FD503E 0%, #FF3E00 100%, #F7603E 100%);
            background: #fd503e; // 202108 疫苗先买后约需求，对支付结果页统一进行UI迭代
        }
    }
    &.exam {
        .top-bar,
        .blank {
            background: linear-gradient(134deg, #489af6 0%, #82cbff 100%);
        }
    }
    &.red {
        .top-bar,
        .fixedbg,
        .blank {
            background-image: linear-gradient(90deg, #fd503e 0%, #ff8372 100%);
        }
    }
    &.yellow {
        .top-bar,
        .fixedbg,
        .blank {
            background-image: linear-gradient(90deg, #fe7a4b 0%, #ffa471 54%, #fdca7c 100%);
        }
    }
    &.pink {
        .top-bar,
        .fixedbg,
        .blank {
            background-image: linear-gradient(90deg, #ff88a1 0%, #ffbaca 100%);
        }
    }
    &.white {
        .top-bar {
            background: #fff;
        }
    }
    &.blue {
        .top-bar,
        .blank {
            background: linear-gradient(to right, #489af6, #82cbff);
        }
    }
    &.greenToBlue {
        .top-bar,
        .blank {
            background: linear-gradient(134deg, #00CFA3 0%, #05CFCD 61%, #00D3EA 100%);
        }
    }
    &.f5 {
        .top-bar,
        .blank {
            background: linear-gradient(180deg, #fff 0%, #f5f5f5 100%);
        }
    }
    &.transparent {
        .top-bar,
        .blank {
            background: transparent;
        }
    }
    &.wz618green {
        .top-bar,
        .blank {
            background: #0faba9;
        }
    }
    .top-bar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        box-sizing: border-box;
        &.no-fix-wid {
            .bar {
                width: 100%;
            }
        }
        .bar {
            align-items: center;
            .title {
                font-size: 0.18rem;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-weight: bold;
                text-align: center;
            }
            .left {
                text-align: left;
                padding-left: 11px;
                white-space: nowrap;
                .icon {
                    position: relative;
                    font-size: 22px;
                    display: inline-block;
                    vertical-align: middle;
                    width: 32px;
                    height: 32px;
                    line-height: 32px;
                    text-align: center;
                    &-blank {
                        width: 50px;
                        height: 50px;
                        &-bg {
                            width: 32px;
                            height: 32px;
                            margin: 0 auto;
                            margin-top: 50%;
                            transform: translate(-3px, -50%);
                        }
                    }
                    &-bg {
                        background: rgba(0, 0, 0, 0.15);
                        border-radius: 100%;
                    }
                }
            }
        }
        // TODO 内测阶段，分享回流关闭
        // &.share {
        //     top: 60px;
        // }
    }
    .fixedbg {
        position: fixed;
        left: 0;
        right: 0;
    }
    .back-left {
        margin-right: 17px;
    }
    .title-icon {
        width: 20px;
        height: 20px;
        display: inline-block;
        vertical-align: text-top;
        background-size: 100% 100%;
        margin-right: 0.02rem;
    }
}
</style>
