<script>
/**
* @file app
* @author haoyan
*/

/* global getApp, swan, Page, getCurrentPages, _pages */
import {sendPageLog, WEBB_KEY, sendErrorLog} from './utils/monitor';
import * as core from './utils/core';
import * as pageUtil from './utils/pageUtil';
import * as Coop from './utils/platformCooperation';
import {Vue} from '@marsjs/core';
import {prefetchData} from './utils/prefetch';
import {isBack} from './utils/navigate';
import {basePages, setPageInfo} from './utils/pagetit';
import {addRemClass} from './utils/remPage';
import {ubcInit, ubcSend, UbcPage} from './utils/log';
import {Mars, Hybrid} from '@baidu/med-utils';
import {appToH5CacheSync} from './utils/cache';
import {getCloseDetainPage} from './utils/closeDetainPage';
import {request} from './utils/request';
import * as conf from './utils/conf';
import share from './utils/share';
import cookie from './utils/cookie';
import {COOKIE_KEY} from './utils/constant';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';

Mars.use && Mars.use({
    beforeNavigateCurrent: conf => {
        // 性能日志数据收集
        // 过滤掉，手动relauch的页面性能日志
        if (conf.openType === 'relaunch') {
            getApp().globalData.m && (getApp().globalData.m.navigateStart = 0);
        }
        else {
            getApp().globalData.m && (getApp().globalData.m.navigateStart = Date.now());
        }
    },
    interceptNavigation: conf => {
        let navigateFlag = false;
        if (process.env.MARS_ENV === 'h5') {
            navigateFlag = Coop.interceptNavigation(conf);
        }
        return navigateFlag;
    },
    MARS_ENV: process.env.MARS_ENV,
    _pages: _pages,
    isInApp: () => getApp().globalData.isInApp
});

let independentPages;
if (process.env.MARS_ENV === 'swan') {
    independentPages = getApp() && getApp().__pages__ || undefined;
}

// Hybrid.use && Hybrid.use({
//     getOriginApis: () => {
//         return getApp().globalData._apis;
//     }
// });

const filterImgCache = new Map();

Vue.filter('imgCompress', (value, key, extra) => {
    if (core.isObject(value) && value[key]) {
        // 判断缓存是否生效
        const imgCache = filterImgCache.get(value[key]);
        if (imgCache) {
            return imgCache;
        }
        // 记录缓存
        filterImgCache.set(value[key], value);
        // url 替换
        // TODO:
        // /(?<=\(")[^\(\)]+(?="\))/g
        // 此正则小程序IOS真机报错..，临时先替换两次解决
        value[key] = value[key].replace(/url\("?'?.*"?'?\)/, e => {
            return e ? 'url(' + core.imgCompress(e.replace(/"|'|url|\(|\)/g, ''), extra) + ')' : e;
        });
        return value;
    }
    return value;
});

export default {
    globalData: {
        MARS_ENV: `${process.env.MARS_ENV}`,

        /* eslint-disable */
        _pages: _pages,
        /* eslint-enable */
        /* eslint-disable */
        _apis: {},
        /* eslint-enable */
        curPages: [],
        // 来源字段
        ref: '',
        // APP宿主使用
        isInApp: false,
        // 进入小程序的path
        path: '',
        login: {
            baiduid: '',
            sid: '',
            bduss: ''
        },
        loginStatus: {status: 1, cxt: null},
        // 日志全局字段
        log: {
            lid: '',
            applid: '',
            referlid: '',
            pd: 'med'
        },
        m: {
            navigateStart: 0,
            invokeStart: 0
        },
        city: {
            realName: '',
            realCode: '',
            name: '', // 实际选择地址
            code: '', // 城市编号
            lat: '',
            lng: '',
            province: '',
            district: '',
            placeName: ''
        },
        // 带详细坐标的地址
        medDetailAddress: {
            realName: '',
            realCode: '',
            name: '', // 实际选择地址
            code: '', // 城市编号
            lat: '',
            lng: '',
            province: '',
            district: '',
            placeName: '',
            contactId: '' // 收货人id
        },
        // 购药购物车数据
        gyTrolleys: [],
        // 购药去结算数据
        // 重构后
        gyToOrderConfirmSkus: [],
        gyToOrderConfirmDrugs: [],
        appVersion: '2.0.0',
        // 时长日志信息
        conf: {},
        network: {status: 1, cxt: null},
        system: null,
        // H5左上角房子屏蔽
        hdhome: false,
        // 登录改造兼容button方式
        canIUseLoginButton: false,
        // 小程序场景值
        scene: '',
        // 实验SID值（需在业务端根据后端透传然后赋值）
        sid: '',
        // 从chat页返回展示弹窗的条件
        chatBackDiaInfo: {},
        sf_ref: '', // 外部来源
        // H5是否支持webp
        supportWebp: null
    },
    onLaunch(info) {
        let q = {};
        if (process.env.MARS_ENV === 'swan') {
            q = info.query;
        }
        else if (process.env.MARS_ENV === 'h5') {
            q = info;
        }
        // 透传lid
        if (q.lid) {
            getApp().globalData.log.lid = q.lid;
        }
        else {
            const lid = core.rand(10);
            getApp().globalData.log.lid = lid;
            // history模式不需要lid参数
            if (process.env.MARS_ENV === 'h5' && this.$router && this.$router.mode !== 'history') {
                let path = window.location.hash.split('?')[0];
                let query = core.getQueryObject(window.location.href);
                query.lid = lid;
                path = path + '?' + core.getQueryStr(query);
                window.history.replaceState(null, null, path);
            }
        }
        getApp().globalData.log.applid = q.applid || '';
        getApp().globalData.log.referlid = q.referlid || getApp().globalData.log.lid;
        // 透传ref
        getApp().globalData.ref = q.sf_ref || q.ref || '';


        // 小程序版本分布日志
        if (process.env.MARS_ENV === 'swan') {
            swan.reportAnalytics('app_version', {
                v: getApp().globalData.appVersion
            });
            // 小程序开启-数据预取
            prefetchData(info);
            getApp().globalData.canIUseLoginButton = swan.canIUse('button.open-type.login');
        }

        // 判断APP宿主环境
        if (process.env.MARS_ENV === 'h5') {
            // H5左上角房子显示设置
            if (q.hasOwnProperty('hdhome')) {
                const hdhome = q.hdhome - 1 === 0;
                getApp().globalData.hdhome = hdhome;
                window.sessionStorage.setItem('hdhome', hdhome);
            }
            // 投放第三方隐藏小房子以及yd其他模块
            if (q.hasOwnProperty('ydChannel')) {
                const ydChannel = q.ydChannel;
                getApp().globalData.ydChannel = q.ydChannel;
                window.sessionStorage.setItem(COOKIE_KEY.YDCHANNEL, ydChannel);
                window.sessionStorage.setItem('hdhome', true);
            }
            const ydChannel = window.sessionStorage.getItem(COOKIE_KEY.YDCHANNEL);
            if (ydChannel) {
                cookie(COOKIE_KEY.YDCHANNEL, ydChannel, {expires: 1 * 24, path: '/', domain: '.baidu.com'});
            } else {
                cookie(COOKIE_KEY.YDCHANNEL, '', {expires: -1, path: '/', domain: '.baidu.com'});
            }
            const isInApp = navigator.userAgent.toLowerCase().includes('bdhealthapp');
            const isBrowserApp = navigator.userAgent.toLowerCase().includes('bdhealthappbrowser');
            getApp().globalData.isInApp = isInApp || isBrowserApp;
            if (isInApp) {
                if (isBrowserApp) {
                    // Chrome支持根据UA模拟APP环境
                    getApp().globalData.system = {
                        ...getApp().globalData.system,
                        statusBarHeight: 36,
                        navigationBarHeight: 44
                    };
                }
                else {
                    let $api = getApp().$api;

                    // 保存原接口能力
                    // getApp().globalData._apis = {};

                    // APP Hybrid api 注入
                    $api = Object.assign($api, Hybrid.app.api);

                    // onLaunch 请求一次，确保进入所有页面系统信息已ready
                    getApp().globalData.system = $api.getSystemInfoSync();

                    // 首次进入App，同步H5与NA共享的数据，如定位、购物车
                    appToH5CacheSync();
                }
            }
            const ua = require('@searchfe/user-agent');
            if (ua.isWeixinApp()) {
                // 微信渠道设置默认分享信息
                const SHARE_CONFIG_WX = {
                    // 分享标题
                    title: '百度健康',
                    // 分享描述
                    content: '你身边的健康管家'
                };
                request({
                    url: conf.apiHost + '/med/weixin/jssdksign',
                    isNeedLogin: false,
                    isFirstScreen: false
                }).then(res => {
                    const titleText = document.getElementsByTagName('title')
                        && document.getElementsByTagName('title')[0]
                        && document.getElementsByTagName('title')[0].innerText;
                    const {title, shareUrl, content} = SHARE_CONFIG_WX;
                    const {timestamp, nonceStr, signature} = res.data || {};
                    share({
                        title: titleText || title,
                        url: shareUrl || window.location.href,
                        content
                    }, res.data ? {
                        wx: true,
                        debug: false,
                        timestamp,
                        nonceStr,
                        signature
                    } : {});
                });
            }
        }
        if (process.env.NODE_ENV === 'production' && process.env.MARS_ENV === 'h5') {
            Vue.config.errorHandler = function (err, vm, info) {
                sendErrorLog(err);
            };
        }
        // cps 分销 id
        if (q.popactFlowid) {
            getApp().$api.setStorage({
                key: 'popactFlowid',
                data: q.popactFlowid
            });
        }

        // OPPO合作页
        if (process.env.MARS_ENV === 'h5') {
            Coop.init(Object.assign({}, q));
        }

        // 通用ubc日志注册
        getApp().globalData.scene = info.scene;
        ubcInit({
            serverId: 13223,
            eventName: 'feedlog',
            ubcConf: {
                testMode: process.env.NODE_ENV === 'development'
            }
        });
        ubcInit({
            ubcConf: {
                testMode: process.env.NODE_ENV === 'development'
            }
        });
        // ubcInit({
        //     serverId: 13349,
        //     eventName: 'pagetiming'
        // });
    },
    onShow(info) {
    },
    onPageNotFound() {
        // 检查更新
        if (process.env.MARS_ENV === 'swan') {
            const updateManager = swan.getUpdateManager();
            updateManager.onUpdateReady(function (res) {
                swan.showModal({
                    title: '更新提示',
                    content: '已为您准备好新版本，是否重启应用？',
                    success(res) {
                        if (res.confirm) {
                            updateManager.applyUpdate();
                        }
                    }
                });
            });
        }
    },
    onError(err) {
        if (process.env.NODE_ENV === 'production' && process.env.MARS_ENV === 'swan') {
            sendErrorLog(err);
        }
    },
    beforeAppClose(e) {
        const page = getCloseDetainPage();
        const sys = getSystemInfo();
        const ovBrowserList = ['heytapbrowser', 'vivobrowser', 'mibrowser'];
        let isOvBrowser;
        if (sys && sys.host) {
            isOvBrowser = ovBrowserList.includes(sys.host);
        }
        if (isOvBrowser) {
            swan.exit();
        } else if (page) {
            e.preventDefault();
            page.$vue.detainDialogShow && page.$vue.detainDialogShow(swan.exit);
        }
        ubcSend({
            type: 'clk',
            value: 'navigateClose',
        });
    }
};
Page.after({
    methods: {
        onLoad(cxt) {
            // 独立分包，修改当前实例uid，并修改pages TODO: 修改框架
            if (independentPages && independentPages[0]) {
                let lastUid = 0;
                Object.keys(independentPages).forEach(key => {
                    if (Number(key) > lastUid) {
                        lastUid = Number(key);
                    }
                });

                if (!getApp().__pages__[0]) {
                    getApp().__pages__[0] = getCurrentPages()[getCurrentPages().length - 1];
                }
                const curPage = getApp().__pages__[0];
                if (curPage.uri !== 'pages/brand/home/index') {
                    Object.assign(getApp().__pages__, independentPages);
                    ++lastUid;
                    curPage.__uid__ = lastUid;
                    getApp().__pages__[lastUid] = curPage;
                    getApp().__pages__.uid = lastUid;
                    independentPages = null;
                }
            }

            let query = {};
            if (process.env.MARS_ENV === 'swan') {
                query = cxt.args.e || {};
            }
            else if (process.env.MARS_ENV === 'h5') {
                query = cxt.$route.query || {};
            }
            // rem 自适应页面
            addRemClass();
            const m = getApp().globalData && getApp().globalData.m || {};
            // 性能统计
            if (m.navigateStart) {
                sendPageLog({
                    [WEBB_KEY.PAGE_WHITE_SCREEN]: Date.now() - m.navigateStart
                });
            }
            // 调起起始时间
            if (query._invoke_t) {
                getApp().globalData.m.invokeStart = query._invoke_t;
            }
            // 刷新页面H5globalData会被清空 H5 和 swan 分开保存
            if (process.env.MARS_ENV === 'h5' && query.sf_ref) {
                window.sessionStorage.setItem('sf_ref', query.sf_ref);
            } else if (process.env.MARS_ENV === 'swan' && query.sf_ref) {
                getApp().globalData.sf_ref = query.sf_ref;
            }
            // ubc打点获取当前页面的路径
            try {
                const pages = getCurrentPages();
                const page = pages && pages.length ? pages[pages.length - 1] : {};
                const route = page.uri || '';
                UbcPage.setPage('onload_page', route);
                UbcPage.setPage('tmp_page', route);
            } catch (err) {};
        },
        onShow(ctx) {
            // ubc打点获取当前页面的路径
            try {
                const pages = getCurrentPages();
                const page = pages && pages.length ? pages[pages.length - 1] : {};
                const route = page.uri || '';
                UbcPage.setPage('onshow_page', route);
                UbcPage.setPage('tmp_page', route);
            } catch (err) {};
            if (process.env.MARS_ENV === 'h5') {
                const pages = getCurrentPages();
                const curPage = pages && pages.length ? pages[pages.length - 1] : {};
                document.title = curPage.options.title || '百度健康';
            }
            // rem 自适应页面
            addRemClass();
            const pages = getCurrentPages();
            const page = pages && pages.length && pages[pages.length - 1] || {};

            // 判断是否后退
            if (isBack()) {
                getApp().globalData.log.applid = getApp().globalData.log.referlid;
            }

            // 小程序设置标题
            let uri =  page.uri && page.uri.replace(/^\//, '').replace('-sub', '');
            try {
                Object.keys(basePages).indexOf(uri) > -1 && setPageInfo(basePages[uri]);
            } catch (e) {}

            // OPPO浏览器多页面应用( MPA )不支持后置 Page.onHide 回调函数, 使用钩子函数来做统计
            let trackInfoAfterHook = null;
            if (Coop.isInOppoWebView()) {
                trackInfoAfterHook = Coop.trackCoopInfo;
                Coop.trackPageInfo(); // 统计OPPO PV
            }
            // 统计各页面浏览时长( 前置函数 )
            pageUtil.trackInfoBefore(trackInfoAfterHook);
            // ubcTiming('pagetiming', 'start');
        },
        onReady() {
            // ubc打点获取当前页面的路径
            try {
                const pages = getCurrentPages();
                const page = pages && pages.length ? pages[pages.length - 1] : {};
                const route = page.uri || '';
                UbcPage.setPage('onready_page', route);
                UbcPage.setPage('tmp_page', route);
            } catch (err) {};
        },
        onHide(ctx) {
            // ubc打点获取当前页面的路径
            try {
                const pages = getCurrentPages();
                const page = pages && pages.length ? pages[pages.length - 1] : {};
                const route = page.uri || '';
                UbcPage.setPage('onhide_page', route);
            } catch (err) {};
            getApp().$api.hideToast();

            // 统计各页面浏览时长( 后置函数 )
            pageUtil.trackInfoAfter();
            // ubcTiming('pagetiming', 'end');
            // 清空图片缓存
            filterImgCache.clear();
        },
        onTabItemTap(ctx) {
            // 性能日志数据收集
            getApp().globalData.m.navigateStart = Date.now();
        }
    }
});
</script>
<style target="h5">
@import "https://med-fe.cdn.bcebos.com/med-iconfont/med-icon.1641265724811.css";
@import "~@baidu/med-ui/dist/swan/assets/css/med-ui.css";
@import "./css/animate.css";
@import "./css/med-h5.css";
@import "./css/parse.css";
</style>
<style target="swan">
@import "https://med-fe.cdn.bcebos.com/med-iconfont/med-icon.1641265724811.css";
@import "@baidu/med-ui/dist/swan/assets/css/med-ui.css";
@import "./css/parse.css";
</style>
