/**
 * 私有接口
 */
/* globals GLOBAL_OBJECT */
import { callNative, callNativeSync, showSystemLog, emptyFn, getUid } from './util';
import {isInternalSmallApp} from '../nativeApi/util'
import parseQuery from '../lib/parse-query';
import makeShareQuery from '../lib/makeShareQuery';
import createGameCardButton from './cardBtn';
import createAdjustWebview from './adjustWebview';
import { compareVersion } from './util/commonFn'

const AccountLoginCallback = [];
const AccountLogoffCallback = [];

const effectiveParam = ['url', 'aid', 'cid', 'page', 'type', 'currentTime', 'duration'];

export function getAccountLoginCallback(){
    return AccountLoginCallback;
}

export function getAccountLogoffCallback(){
    return AccountLogoffCallback;
}

function tryAddQuery (obj, key) {
    // 如果obj为空，return。
    if (!(obj && obj[key])) return;
    try {
        const [baseUrl, query = ''] = obj[key].split('?');
        if (!/___timestamp=/.test(query)) {
            obj[key] = `${baseUrl}?___timestamp=${Date.now()}${query ? '&' + query : ''}`;
        }
    } catch (error) {
        showSystemLog && console.log(error);
    }
}

function setEnablePullDownRefresh (isEnable) {
    try {
        const pageVm = bl.getCurrentPages()[0];
        pageVm.$options.enablePullDownRefresh = isEnable;
    } catch (error) { console.log(error); }
}

const navigationRightButtonOnClick = {};
const configRightButtonClick = {};

let accessKey = null;

export default {
    navigationRightButtonOnClick,
    configRightButtonClick,
    getQuery () {
        return parseQuery(Service.location.href);
    },
    openSchema (options = {}) {
        let _sys = bl.getSystemInfoSync() || {
            platform: '',
            SDKVersion: ''
        };
        /*
        * 描述：兼容：iOS 线上 bl.internal.openSchema 失败
        * tapd：https://www.tapd.bilibili.co/55318386/prong/stories/view/1155318386002634430?url_cache_key=fef249dc4f7a4d662c5d4808453ff35d&action_entry_type=stories
        * */
        if (_sys.platform.toLowerCase() === 'ios' &&
            compareVersion(_sys.SDKVersion, '3.67.0') <= 0 &&
            compareVersion(_sys.SDKVersion, '3.64.0') >= 0 &&
            options) {
            if (options.schema &&
                typeof options.schema === 'string') {
                // 特殊处理 url 中的 # 关键字
                const urlArr = options.schema.split('#');
                const isHasBiz = urlArr[0].indexOf('bizId') === -1
                const isHasQuery = urlArr[0].indexOf('?') === -1;
                if (isHasBiz) {
                    options.schema = `${urlArr[0]}${isHasQuery? '?': '&'}bizId=${global.__biliCacheData.smallAppInfo.appid}${options.schema.indexOf('#') > -1 ? options.schema.substring(options.schema.indexOf('#')) : ''}`
                }
            }
        }
        callNative('internal.openSchema', options);
    },
    /**
     * 内部小程序专用
     * 检查登录态
     */
    isBiliLogin () {
        return callNativeSync('internal.isBiliLogin').data.data;
    },
    /**
     * 内部小程序用
     * 获取用户信息
     *
     * @param {Object} [options={}]
     * @param {Function} options.success 成功回调
     * @param {Function} options.fail 失败回调
     */
    getBiliUserInfo (options = {}) {
        callNative('internal.getBiliUserInfo', options);
    },
    /**
     * 登录
     *
     * @param {Object} options
     * @param {Function} options.success 成功回调
     * @param {Function} options.fail 失败回调
     */
    login (options = {}) {
        callNative('internal.login', options);
    },

    /**
     * 获取登录授权的 access_key
     *
     * @param {Object} options
     * @param {Boolean} [options.cacheFirst = true]
     */
    getAccessKey (options = {}) {
        const _sys = bl.getSystemInfoSync();
        if (compareVersion(_sys.SDKVersion, '3.63.0') >= 0) {
            return new Promise((resolve, reject) => {
                // 获取客户端数据
                const _result = callNativeSync('internal.getAccessKey') || {}
                if (_result.code === 0 &&
                    _result.data &&
                    typeof _result.data.data === 'string') {
                    resolve(_result.data.data);
                } else {
                    reject('bl.internal.getAccessKey fail');
                }
            })
        }

        const opts = Object.assign({
            cacheFirst: true
        }, options);

        if (accessKey !== null && !!opts.cacheFirst) {
            return Promise.resolve(accessKey);
        }

        return new Promise((resolve, reject) => {
            bl.request({
                url: 'https://miniapp.bilibili.com/api/miniapp/access_key',
                method: 'GET',
                success (resp) {
                    if (resp.data) {
                        if (resp.data.code === 0) {
                            accessKey = resp.data.data;

                            resolve(accessKey);
                        } else {
                            reject(resp.data.message || '获取 Access Key 失败');
                        }
                    } else {
                        reject(new Error('获取 Access Key 失败'));
                    }
                },
                fail (e) {
                    reject(e);
                }
            });
        });
    },

    /**
     * 清空缓存的 access_key
     */
    clearAccessKey () {
        accessKey = null;

        return true;
    },
    /**
     * 打开分享浮层
     *
     * @param {Object} options
     * @param {Function} [options.data.default]
     * @param {Function} [options.data.generic]
     * @param {Function} [options.data.dynamic]
     * @param {Function} [options.data.weixin]
     * @param {Function} [options.data.extra]
     * @param {Function} [options.success = emptyFn] 成功回调
     * @param {Function} [options.fail = emptyFn] 失败回调
     */
    share (options = {}) {
        if (options.data) {
            const conf = ['weixin', 'weixin_monment', 'qq', 'sina', 'q_zone', 'copy', 'default'];
            // tryAddQuery只是为了增加时间戳，处理动态链接的。zola说internal.share理论上不需要做，但是我不敢删，so，先放着。
            tryAddQuery(options.data.dynamic && options.data.dynamic.sketch, 'target_url');
            conf.forEach(item => {
                tryAddQuery(options.data[item], 'url');
            });
        }
        callNative('internal.share', options);
    },
    /**
     * 打开另一个小程序
     *
     * @param {object} options
     * @param {String} options.id 要打开的小程序 appId
     * @param {String} options.virtualId 要打开的小程序 virtualId
     * @param {String} options.url 打开的页面路径，如果为空则打开首页
     * @param {Object} options.extraData 需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据。
     */
    navigateToSmallApp (options = {}) {
        callNative('internal.navigateToSmallApp', options, { id: 'String' });
    },
    uploadImage (options = {}) {
        callNative('internal.uploadImage', options, { imgUrl: 'String' });
    },
    /**
     * 埋点
     */
    reportCommon (options) {
        return callNativeSync('internal.reportCommon', options).code === 0;
    },
    /**
     * 埋点
     */
    reportNeuron (options) {
        return callNativeSync('internal.reportNeuron', options).code === 0;
    },
    /**
     * 保存成临时目录
     *
     * @param {*} [options={}]
     */
    toTempFilePath (options = {}) {
        callNative('_inner.toTempFilePath', options, {}, 'toTempFilePath');
    },
    /**
     * addPullDownRefresh
     * 仅ios才有，对外暴露
     */
    addPullDownRefresh (options = {}) {
        setEnablePullDownRefresh(true);
        callNative('internal.addPullDownRefresh', options);
    },
    /**
     * enableBounce
     * 仅ios才有
     * @param {object} options
     * @param {String} options.enable 0:禁用 1:启用
     */
    enableBounce (options) {
        setEnablePullDownRefresh(!!options.enable);
        callNative('internal.enableBounce', options);
    },
    /**
     * enableScroll
     * 仅ios才有
     * @param {object} options
     * @param {String} options.enable 0:禁用 1:启用
     */
    enableScroll (options) {
        callNative('internal.enableScroll', options);
    },
    /**
     * enablePullDownRefresh
     * app.json配置优先级最高
     */
    enablePullDownRefresh (options = {}) {
        const isiOS = callNativeSync('getSystemInfoSync').data.platform === 'ios';
        setEnablePullDownRefresh(true);
        return isiOS ? callNativeSync('internal.enableBounce', { enable: 1 }) : callNativeSync('internal.enablePullDownRefresh', options);
    },
    /**
     * disablePullDownRefresh
     */
    disablePullDownRefresh (options = {}) {
        const isiOS = callNativeSync('getSystemInfoSync').data.platform === 'ios';
        setEnablePullDownRefresh(false);
        return isiOS ? callNativeSync('internal.enableBounce', { enable: 0 }) : callNativeSync('internal.disablePullDownRefresh', options);
    },
    /**
     * isEnablePullDownRefresh
     * 获取是否可下拉刷新的状态
     */
    isEnablePullDownRefresh () {
        try {
            const pageVm = bl.getCurrentPages()[0];
            const systemInfo = callNativeSync('getSystemInfoSync').data;
            if (systemInfo.SDKVersion >= '2.1.0') {
                const res = callNativeSync('internal.isEnablePullDownRefresh', { pageId: pageVm.$root.$page.id }).data.data;
                return systemInfo.platform === 'ios' ? res && callNativeSync('internal.isEnableBounce').data.data : res;
            } else {
                return pageVm.$options.enablePullDownRefresh;
            }
        } catch (error) { console.log(error); }
    },
    /**
     * openAppSettings
     */
    openAppSettings (options = {}) {
        return callNative('internal.openAppSettings', options, {}, 'internal.openAppSettings', {
            resultFn(result) {
                let errorInfo = ''
                if (Number(result.code) === 2000) {
                    errorInfo = `open failed`
                }
                return errorInfo;
            }
        });
    },
    /**
     * openAppURL
     * @param {String} options.url
     */
    openAppURL (options = {}) {
        return callNative('internal.openAppURL', options, { url: 'String' }, 'internal.openAppURL', {
            resultFn(result){
                let errorInfo = ''
                if (Number(result.code) === 2001 || Number(result.code) === 100) {
                    errorInfo = `open failed`
                }
                return errorInfo;
            }
        });
    },
    /**
     * isEnableBounce
     * ios only
     */
    isEnableBounce (options = {}) {
        return callNativeSync('internal.isEnableBounce', options).data.data;
    },
    /**
     * isEnableScroll
     * ios only
     */
    isEnableScroll (options = {}) {
        return callNativeSync('internal.isEnableScroll', options).data.data;
    },
    /**
     * 设置导航栏右边自定义按钮
     *
     * @param {Object} options
     * @param {String} options.type 按钮类型，icon/text
     * @param {Array} options.icon 当type=icon有效，icon路径，数组里可传1或2个，从左到右按钮index依次为0,1
     * @param {String} options.text 当type=text有效，文字内容
     * @param {String} options.color 当type=text有效，文字颜色
     * @param {Function} [options.onClick=emptyFn]  点击按钮的回调，参数index=0,1
     * @param {Function} [options.success=emptyFn]  成功回调
     * @param {Function} [options.fail=emptyFn]  失败回调
     */
    showNavigationRightButton ({
        type = 'icon',
        icon,
        text = '',
        color = '',
        onClick = emptyFn,
        success = emptyFn,
        fail = emptyFn
    }) {
        const pageId = global.__biliCacheData.getCurrentPageId();

        if (Service.componentsOptions[Service.location.href.replace(/\?.+$/, '')].hasNavigationBar) {
            navigationRightButtonOnClick[pageId] = onClick;
            // 兼容ios icon顺序反了的问题
            if (type === 'icon' && icon.length === 2) {
                const systemInfo = callNativeSync('getSystemInfoSync').data;

                if (systemInfo.platform === 'ios' && systemInfo.SDKVersion >= '2.3.0' && systemInfo.SDKVersion <= '2.9.0') {
                    icon.reverse();
                }
            }
            callNative('internal.showNavigationRightButton', {
                pageId,
                type,
                icon,
                text,
                color,
                success,
                fail
            });
        } else {
            fail({
                errMsg: 'not support when hasNavigationBar\'s value is false'
            });
        }
    },
    /**
     * 隐藏导航栏右边自定义按钮
     *
     * @param {Object} options
     * @param {Function} [options.success=emptyFn]  成功回调
     * @param {Function} [options.fail=emptyFn]  失败回调
     */
    hideNavigationRightButton (options = {}) {
        const pageId = global.__biliCacheData.getCurrentPageId();
        const pageVm = bl.getCurrentPages()[0];

        if (pageVm.$options.hasNavigationBar) {
            callNative('internal.hideNavigationRightButton', Object.assign({ pageId }, options));
        } else {
            options.fail && options.fail({
                errMsg: 'not support when hasNavigationBar\'s value is false'
            });
        }
    },
    /**
     * 展示导航栏后退按钮
     *
     * @param {Object} options
     * @param {Function} [options.success=emptyFn]  成功回调
     * @param {Function} [options.fail=emptyFn]  失败回调
     */
    showNavigationBackButton (options = {}) {
        const pageId = global.__biliCacheData.getCurrentPageId();
        const pageVm = bl.getCurrentPages()[0];

        if (pageVm.$options.hasNavigationBar) {
            callNative('internal.showNavigationBackButton', Object.assign({ pageId }, options));
        } else {
            options.fail && options.fail({
                errMsg: 'not support when hasNavigationBar\'s value is false'
            });
        }
    },
    /**
     * 隐藏导航栏后退按钮
     *
     * @param {Object} options
     * @param {Function} [options.success=emptyFn]  成功回调
     * @param {Function} [options.fail=emptyFn]  失败回调
     */
    hideNavigationBackButton (options = {}) {
        const pageId = global.__biliCacheData.getCurrentPageId();
        const pageVm = bl.getCurrentPages()[0];

        if (pageVm.$options.hasNavigationBar) {
            callNative('internal.hideNavigationBackButton', Object.assign({ pageId }, options));
        } else {
            options.fail && options.fail({
                errMsg: 'not support when hasNavigationBar\'s value is false'
            });
        }
    },
    exitMiniProgram () {
        callNative('internal.exitMiniProgram');
    },
    openThirdApp (options = {}) {
        let _sys = bl.getSystemInfoSync() || {
            platform: '',
            SDKVersion: ''
        };
        if (_sys.platform.toLowerCase() === 'android' &&
            compareVersion(_sys.SDKVersion, '3.67.0') <= 0 &&
            options) {
            if (options.httpURL) {
                const _tempUrl = options.httpURL;
                options.httpURL = '';
                const _tempFail = options.fail && typeof options.fail === 'function' ? (e)=>{
                    options.fail(Object.assign(e, {
                        errMsg: "internal.openThirdApp:fail"
                    }));
                } : ()=>{};
                const _tempSuccess = options.success && typeof options.success === 'function' ? (res)=>{
                    options.success(Object.assign(res, {
                        errMsg: "internal.openThirdApp:success"
                    }));
                } : ()=>{};
                if (options.schemaURL) {
                    options.fail = (res) => {
                        if (Number(res.code) === 2101) {
                            bl.internal.openSchema({
                                schema: `bilibili://smallapp/browser?__runtime=MINI&safe=true&url=${encodeURIComponent(_tempUrl)}`,
                                success: _tempSuccess,
                                fail: _tempFail
                            });
                        } else {
                            _tempFail(res);
                        }
                    };

                    callNative('internal.openThirdApp', options, {}, 'internal.openThirdApp', {
                        code: true
                    });
                } else {
                    bl.internal.openSchema({
                        schema: `bilibili://smallapp/browser?__runtime=MINI&safe=true&url=${encodeURIComponent(_tempUrl)}`,
                        success: _tempSuccess,
                        fail: _tempFail
                    });
                }
            } else {
                callNative('internal.openThirdApp', options);
            }
        } else {
            callNative('internal.openThirdApp', options);
        }
    },
    showModal (options) {
        callNative('internal.showModal', {
            title: '',
            content: '',
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定',
            trackParams: '',
            success: emptyFn,
            fail: emptyFn,
            complete: emptyFn,
            ...options
        }, {
            title: 'String',
            content: 'String',
            cancelText: 'String',
            confirmText: 'String',
            trackParams: 'String'
        });
    },
    // widget 半屏小程序用到
    sendMessage (options = {}) {
        const pageId = global.__biliCacheData.getCurrentPageId();
        callNative('internal.sendMessage', Object.assign(options, { pageId }));
    },
    switchTo (options = {}) {
        // 安卓版本下会对url转码，使用户取值不准确，故修复
        if (options.url) options.url = options.url.replace(/\?.+$/, (m) => {
            return makeShareQuery(m, false);
        });
        callNative('internal.switchTo', options);
    },
    // widget 半屏小程序用到
    closeApp (options = {}) {
        callNative('internal.closeApp', options);
    },
    // widget 半屏小程序用到
    closeContainer (options = {}) {
        callNative('internal.closeContainer', options);
    },
    // widget 半屏小程序用到
    canBack () {
        const pages = callNativeSync('internal.pages', {}).data;

        return pages.length > 1;
    },
    enableNavBackHook (enable = false) {
        return callNativeSync('internal.enableNavBackHook', {
            enable: enable ? 1 : 0
        }).code === 0;
    },
    enableSideSlide (enable = true) {
        const systemInfo = callNativeSync('getSystemInfoSync').data;

        if (systemInfo.platform === 'android') {
            return true;
        }

        return callNativeSync('internal.enableSideSlide', {
            enable: enable ? 1 : 0
        }).code === 0;
    },
    configNavigationRightButton ({
        buttons = '',
        onClick = emptyFn,
        success = emptyFn,
        fail = emptyFn
    } = {}) {
        const pageId = global.__biliCacheData.getCurrentPageId();
        const pageVm = bl.getCurrentPages()[0];

        if (pageVm.$options.hasNavigationBar) {
            if (buttons instanceof Array) {
                buttons.forEach(button => {
                    if (button.type === 'text' && !button.color) {
                        button.color = '';
                    }
                });
            }

            configRightButtonClick[pageId] = onClick;
            callNative('internal.configNavigationRightButton', {
                buttons,
                pageId,
                success,
                fail
            }, {
                buttons: 'Array'
            });
        } else {
            fail({
                errMsg: 'not support when hasNavigationBar\'s value is false'
            });
        }
    },
    // 资源包更新
    updatePackage (options = {}) {
        callNative('internal.updatePackage', options);
    },
    // 重启小程序
    reboot ({
        pagePath = '',
        query = '',
        success = emptyFn,
        fail = emptyFn
    } = {}) {
        const options = {
            pagePath,
            query: makeShareQuery(query, false).slice(1),
            success,
            fail
        };

        callNative('internal.reboot', options);
    },
    // 返回当前环境，build注入进去的都是小程序环境
    getRunningModeSync() {
        return 'smallApp'
    },
    // 获取磁盘剩余空间
    getDiskAvailableSpace(options = {}) {
        callNative('internal.getDiskAvailableSpace', options);
    },

    getDiskAvailableSpaceSync() {
        let res = callNativeSync('internal.getDiskAvailableSpaceSync');
        if (res && res.data) {
            return res.data.value;
        }
        throw res;
    },
    onAccountLogin(callback) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        if(typeof callback != 'function') {
            throw new Error('参数必须是function');
        }
        AccountLoginCallback.push(callback);
    },
    offAccountLogin(callback) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        if(typeof callback != 'function') {
            AccountLoginCallback.splice(0, AccountLoginCallback.length);
        } else {
            const index = AccountLoginCallback.indexOf(callback);
            if(index != -1) {
                AccountLoginCallback.splice(index, 1);
            }
        }
    },
    onAccountLogoff(callback) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        if(typeof callback != 'function') {
            throw new Error('参数必须是function');
        }
        AccountLogoffCallback.push(callback);
    },
    offAccountLogoff(callback) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        if(typeof callback != 'function') {
            AccountLogoffCallback.splice(0, AccountLogoffCallback.length);
        } else {
            const index = AccountLogoffCallback.indexOf(callback);
            if(index != -1) {
                AccountLogoffCallback.splice(index, 1);
            }
        }
    },
    getDeviceInfo(options = {}){
        callNative('internal.getDeviceInfo', options);
    },
    getDeviceInfoSync(){
        let res = callNativeSync('internal.getDeviceInfoSync');
        if (res && res.data) {
            return res.data;
        }
        throw res;
    },
    createGameCardButtonContext(id) {
        const res = callNativeSync('internal.createGameCardButtonContext', {id});
        if(res.code != 0) {
            throw new Error(JSON.stringify(res))
        } else {
            return createGameCardButton(id);
        }
    },
    createAdjustableWebViewContext(id) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        const res = callNativeSync('internal.createAdjustableWebViewContext', {id});
        if(res.code != 0) {
            throw new Error(JSON.stringify(res))
        } else {
            return createAdjustWebview(id);
        }
    },
    /**
     * 跳转至小程序
     *
     * @param {object} options
     * @param {String} options.userName 微信小程序原始id
     * @param {String} options.path 拉起微信小程序页面
     * @param {String} options.type 拉起微信小程序的类型，0 正式版 1 开发版 2 体验版
     * @param {Object} options.extra 额外信息
     */
    navigateToWeixinMiniProgram({
        userName = '',
        path = '',
        type = 1,
        response = emptyFn,
        success = emptyFn,
        fail = emptyFn
    } = {}) {
        const options = {
            userName,
            path,
            type,
            response,
            success,
            fail
        };
        callNative('internal.navigateToWeixinMiniProgram', options, { userName: 'String' }, 'internal.navigateToWeixinMiniProgram', {
            requestFn: function(ServiceId, callNativeOptions){
                callNativeOptions.responseId = ServiceId;
                if (typeof callNativeOptions.response === 'function') {
                    Service.callbacks.lastCallback = {};
                    Service.callbacks.lastCallback[ServiceId] = callNativeOptions.response;
                }
            }
        });
    },
    /**
     * 查询当前小程序是否支持唤醒微信跳转
     */
    canNavigateToWeixinMiniProgram() {
        return callNativeSync('internal.canNavigateToWeixinMiniProgram')["data"];
    },
    // 小程序增加添加到桌面能力
    addToDesktop(options = {}) {
        const errMsgMap = {
            1: '已在桌⾯存在 (仅 Android)',
            2: '添加成功 (仅 Android)',
            3: '已执⾏添加，状态未知',
            '-1': '调起失败 (仅 Android)',
            '-4': '添加失败 (仅 Android)',
            '-5': '参数填写错误'
        };

        if (options.url) {
            if (!(/^\//.test(options.url))) {
                options.url = `/${options.url}`;
            }
            if (/\?/.test(options.url)) {
                if (!(/\?$/.test(options.url))) {
                    options.url = `${options.url}&`
                }
            } else {
                options.url = `${options.url}?`
            }
        } else {
            options.url = '?';
        }

        options.url = `bilibili://smallapp/applet/${APPID}${options.url}_biliFrom=desk`;

        if (!options.image) {
            delete options.image;
        }

        if (!options.name) {
            delete options.name;
        }

        callNative('internal.addToDesktop', options, {}, 'internal.addToDesktop', {
            code: true,
            resultFn(res) {
                return errMsgMap[res.code];
            }
        });
    },
    sharedPlayerInfo ({
        sharedId = '',
        success = emptyFn,
        fail = emptyFn
    } = {}) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        const options = {
            sharedId,
            success,
            fail
        };


        const _success = function(res) {
            const result = {};
            res && effectiveParam.forEach((item) => {
                if(res[item] != undefined) {
                    result[item] = res[item];
                }
            })
            if(res.avid != undefined) {
                result.aid = res.avid;
            }
            const systemInfo = callNativeSync('getSystemInfoSync').data;
            // ios 返回的 type 值 为 videoSource
            if (systemInfo.platform === 'ios') {
                if(res.videoSource != undefined) {
                    result.type = res.videoSource;
                }
            }
            success(result);
        }
        options.success = _success;
        callNative('internal.sharedPlayerInfo', options);
    },
    sharedPlayerInfoSync(sharedId) {
        if(!isInternalSmallApp) {
            throw new Error('api not support')
        }
        const res = callNativeSync('internal.sharedPlayerInfoSync', {sharedId});
        if(res.code != 0) {
            throw new Error(JSON.stringify(res))
        } else {
            const result = {};
            const data = (res && res.data) || {};
            effectiveParam.forEach((item) => {
                if(data[item] != undefined) {
                    result[item] = data[item];
                }
            })
            if(data.avid != undefined) {
                result.aid = data.avid;
            }
            const systemInfo = callNativeSync('getSystemInfoSync').data;
            // ios 返回的 type 值 为 videoSource
            if (systemInfo.platform === 'ios') {
                if(data.videoSource != undefined) {
                    result.type = data.videoSource;
                }
            }
            return result;
        }
    },
    stopTransition({
        success = emptyFn,
        fail = emptyFn,
        complete = emptyFn
    } = {}){
        if(!isInternalSmallApp) {
            throw new Error('api not support');
        }
        const options = {
            success,
            fail,
            complete
        };
        const pageVm = bl.getCurrentPages()[0];
        const pageId = pageVm && pageVm.$root && pageVm.$root.$page && pageVm.$root.$page.id;
        options.pageId = pageId;
        callNative('internal.stopTransition', options);
    },
    // 查询视频详情页直播播放开关
    getBiliVideoConfig() {
        const res = callNativeSync('internal.getBiliVideoConfig');
        if(res.code !== 0) {
            throw new Error(res)
        } else {
            return res.data
        }
    },
    // 动态加载js能力
    loadScript(path= '') {
        let _sys = bl.getSystemInfoSync();
        let _output = {};
        let _loadScript = global.__biliCacheData.getObjectForNativeCanvas('requireModule');
        if (_sys.platform.toLowerCase() === 'android') {
            _output = _loadScript(path)
        } else {
            let module = {
                exports: {}
            };
            let _require = function(path) {
                _loadScript(path, module, module.exports, _require);
                return module.exports;
            }
            _output = _require(path);
        }
        return _output;
    },
    // 查询视频详情页直播播放开关
    readHugeFile(options = {
        filePath : '',
        success : ()=>{},
        fail : ()=>{},
        complete : ()=>{}
    }) {
        let _hugeFile =  global.__biliCacheData.getObjectForNativeCanvas('readHugeFile');
        if (_hugeFile) _hugeFile(options);
    },
    // 批量检测是否支持特定的分享渠道
    canIUseShareChannels(channels = []) {
        const res = callNativeSync('internal.canIUseShareChannels', {channels});
        if(res.code !== 0) {
            throw new Error(res)
        } else {
            return res.data
        }
    },
    // 获取运营商及当前⽹络访问状态。
    getCarrierInfo(object = {}) {
        callNative('internal.getCarrierInfo', object);
    },
    // 获取运营商及当前⽹络访问状态。
    getMobileNumberInfo(object = {}) {
        callNative('internal.getMobileNumberInfo', object);
    },
    // 获取⼿机号授权数据信息。
    getMobileAuthInfo(object = {}) {
        callNative('internal.getMobileAuthInfo', object);
    },
    // 查询视频详情页直播播放开关
    shareToChannel(object = {}) {
        let _sys = bl.getSystemInfoSync();
        if (_sys.platform.toLowerCase() === 'ios' && compareVersion(_sys.SDKVersion, '3.60.0') <= 0) {
            if (object &&
                object.data &&
                object.data.imageUrl &&
                typeof object.data.imageUrl === 'string' &&
                /^https?:\/\//.test(object.data.imageUrl)
            ) {
                const rnd = `_ts=${Date.now()}`;
                if (object.data.imageUrl.indexOf('?') > 0) {
                    object.data.imageUrl = object.data.imageUrl + '&' + rnd;
                } else {
                    object.data.imageUrl = object.data.imageUrl + '?' + rnd;
                }
            }
        }

        callNative('internal.shareToChannel', object);
    },
    // 主动结束播放器共享的 API (仅IOS)
    closeSharedPlayer(sharedId = '') {
        const _sys = bl.getSystemInfoSync() || {platform: ''};
        if (_sys.platform.toLowerCase() === 'ios') {
            callNative('internal.closeSharedPlayer', {
                sharedId: sharedId
            });
        }
    },
    // 获取浏览器的
    providerUserAgent(options = {
        success: emptyFn,
        fail: emptyFn
    }) {
        const successFn = typeof options.success === 'function' ? options.success : emptyFn;
        const failFn = typeof options.fail === 'function' ? options.fail : emptyFn;
        const callbackId = getUid();
        const callbackFn = function (res) {
            if (res && res.code === 0) {
                successFn({
                    userAgent: res.data,
                    errMsg: 'bl.internal.providerUserAgent ok'
                });
            } else {
                failFn({
                    errMsg: `bl.internal.providerUserAgent fail ${res.errMsg}`
                });
            }
        }
        Service.callbacks[callbackId] = callbackFn;
        Service.postMessage(JSON.stringify({
            event: 'providerUserAgent',
            type: 'fe-framework',
            callbackId
        }), global.__biliCacheData.getCurrentPageId())
    }
};
