let plugin = requirePlugin('loginPlugin');

(function () {
    if (console.jdLoginLog) return;
    let normalLog = console.log;

    console.jdLoginLog = (...args) => {
        args.unshift('-------登录插件-------');
        normalLog && normalLog(...args);
    };
})();

const utils = {
    redirectPage(url) {
        uni.redirectTo({
            url
        });
    },

    redirectToH5({ page, wvroute }) {
        let url = plugin.formH5Url({
            page: decodeURIComponent(page),
            wvroute
        });
        utils.redirectPage(url);
    },

    navigateToH5({ page, wvroute }) {
        let url = plugin.formH5Url({
            page: decodeURIComponent(page),
            wvroute
        });
        uni.navigateTo({
            url
        });
    },

    setLoginParamsStorage(obj = {}) {
        plugin.setLoginStorageSync(utils.getLoginConfig(obj));
    },

    /*
  首页存缓存逻辑（兼容不适用loginConfig直接存缓存）：
  同名参数优先级：url 中参数 > loginConfig > 缓存中
  */
    getLoginConfig(obj = {}) {
        //兼容缓存中有returnPage， 传递的参数中无，塞缓存时会用缓存中的值，导致不匹配
        const handleUndefinedType = (o = {}) => {
            let { pageType = 'redirectTo' } = o;
            o.pageType = pageType;
            return o;
        };

        let storageConfig = plugin.getLoginParams();
        let config = handleUndefinedType(utils.getDefaultConfig());
        let loginParams = { ...storageConfig, ...config };

        if (plugin.isObject(obj)) {
            loginParams = { ...loginParams, ...handleUndefinedType(obj) };
        } else {
            console.jdLoginLog('登录参数必须为对象');
        }

        return loginParams;
    },

    getDefaultConfig() {
        let lgConfig;

        try {
            lgConfig = require('./config.js');
        } catch (err) {
            lgConfig = {};
        }

        return lgConfig.config || {};
    },

    handleJump(p = {}) {
        let { goback, pluginUrl, riskUrl } = p;

        if (goback) {
            utils.goBack();
            return;
        }

        if (pluginUrl) {
            utils.redirectPage(pluginUrl);
            return;
        }

        riskUrl &&
            utils.redirectToH5({
                page: riskUrl
            });
    },

    goBack() {
        let params = plugin.getLoginParams(),
            { returnPage, pageType } = params;

        if (pageType == 'navigateBack') {
            uni[pageType]();
            return;
        }

        if (!returnPage) {
            uni.showToast({
                title: '没有returnPage，无法跳转',
                icon: 'none'
            });
            return;
        }

        if (pageType !== 'h5') {
            returnPage = decodeURIComponent(returnPage);

            if (pageType && pageType != 'rediretTo') {
                uni[pageType]({
                    url: returnPage
                });
            } else {
                utils.redirectPage(returnPage);
            }

            return;
        } else {
            utils.redirectToH5({
                page: returnPage
            });
            return;
        }
    },

    h5Init(options) {
        let p = plugin.getLoginParams();
        if (plugin.isEmptyObj(p)) utils.setLoginParamsStorage(options);
    },

    setCustomNavigation() {
        let { navigationBarColor, navigationBarTitle } = plugin.getLoginParams();
        plugin.isObject(navigationBarColor) && uni.setNavigationBarColor(navigationBarColor);
        plugin.isObject(navigationBarTitle) && uni.setNavigationBarTitle(navigationBarTitle);
    },

    requestWithLoginStatus(obj = {}) {
        obj.header = obj.header || {};
        let [GUID = '', KEY = '', TOKEN = '', PIN = ''] = plugin.getJdListStorage(['guid', 'pt_key', 'pt_token', 'pt_pin']),
            _cookie = `guid=${GUID}; pt_pin=${encodeURIComponent(PIN)}; pt_key=${KEY}; pt_token=${TOKEN}`,
            { cookie } = obj.header;
        obj.header.cookie = cookie ? `${cookie};${_cookie}` : _cookie;
        uni.request(obj);
    },

    silentauthlogin(options, goToLogin, callback) {
        uni.login({
            success(res = {}) {
                let { code } = res;

                if (code) {
                    utils.setLoginParamsStorage(options);
                    plugin
                        .silentauthlogin({ ...options, code }, goToLogin)
                        .then((res) => {
                            callback &&
                                callback({
                                    isSuccess: res.err_code == 0
                                });

                            if (goToLogin && res.err_code == 0) {
                                utils.handleJump(res);
                            }
                        })
                        .catch((res) => {
                            callback &&
                                callback({
                                    isSuccess: false
                                });
                            console.jdLoginLog('请重试一次');
                        });
                } else {
                    callback &&
                        callback({
                            isSuccess: false
                        });
                    console.jdLoginLog('wx.login 获取code失败');
                }
            },

            fail() {
                callback &&
                    callback({
                        isSuccess: false
                    });
            }
        });
    }
};
export default utils;
