/**
 * 移动端尝试打开 app
 */
const qs = require('yoho-qs');
const cookie = require('yoho-cookie');
const dialog = require('js/plugin/dialog');

const u = navigator.userAgent;
const isFromYOHO = /m\.yohobuy\.com/i.test(document.referrer);
const isApp = /yoho/i.test(u) ||
        !!window.yohoInterface ||
        /app_version=/i.test(location.search) ||
        /openrefer=/i.test(location.search);

const isiOS = /(iPhone|iPad|iPod|iOS)/i.test(u); // ios终端
const isAndroid = /Android/i.test(u); // android终端
const isWechatDevtool = /wechatdevtools/i.test(u); // 微信开发者工具

// const iOSVersion = parseInt((u.match(/OS (\d+)_(\d+)_?(\d+)?/i) || [])[1], 10); // iOS 版本

const nodownload = document.getElementById('no-download'); // 页面不需要下载
const urlBlacklist = ['m.yohobuy.com/brands', 'm.yohobuy.com/passport'];
const blackCheck = urlBlacklist.some(function(url) {
    return new RegExp(url, 'i').test(location.href);
});

/**
 * 从referrer中获取信息,设定mktcode
 */
const channelMap = {
    'baidu.com': 100000000000055,
    'so.com': 100000000000049,
    'sogou.com': 100000000000053,
    'bing.com': 100000000000057,
    'm.sm.cn': 100000000000059,
    'google.com': 100000000000061
};

const getMktcBySeo = function() {
    let mktc,
        rf = document.referrer;

    for (let domain in channelMap) {
        if (rf.indexOf(domain) > -1) {
            mktc = channelMap[domain];
            break;
        }
    }
    return mktc;
};

const getMktc = () => {
    return qs.mkt_code || qs.union_type || cookie.get('unionTypeYas') || getMktcBySeo() || '100000000000349';
};

const canOpenApp = () => {
    if (isWechatDevtool || isApp || isFromYOHO || nodownload || qs.nodownload || qs.no_openapp || blackCheck) {
        return false;
    }
    return isAndroid || isiOS || qs.openapp;
};

const getAppPath = () => {
    let appPath = document.getElementById('main-wrap').dataset.apppath || 'yohobuy://yohobuy.com/goapp?openby:yohobuy={"action":"go.home","params":{"gender":"1","channel":"2"}}';
    let ct = getMktc();
    let clientId = cookie.get('_yasvd');

    if (ct) {
        appPath = appPath.replace('goapp?', 'goapp?ct=' + ct + '&');
    }

    if (clientId) {
        appPath = appPath.replace('goapp?', 'goapp?client_id=' + clientId + '&');
    }

    return appPath;
};


window._getMktCode = getMktc;

const getIOSVersion = () => {
    const verion = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);

    return verion ? parseInt(verion[1], 10) : 0;
};
const ua = navigator.userAgent;
const isOriginalChrome = /chrome\/[\d.]+ Mobile Safari\/[\d.]+/i.test(ua) &&
    isAndroid &&
    ua.indexOf('Version') < 0;


const getFallUrl = (schemeUrl) => {
    let clientId = cookie.get('_yasvd');
    let unionTypeYas = cookie.get('unionTypeYas');
    const appPath = (schemeUrl || '').replace('yohobuy://yohobuy.com/goapp?', '') || 'openby:yohobuy={"action":"go.home","params":{"gender":"1","channel":"2"}}';

    return `https://union.yoho.cn/union/app-downloads.html?union_type=${unionTypeYas}&client_id=${clientId}&${appPath}`;
};

const checkOpenFall = (url, callFunc, noFall) => {
    let time = Date.now();

    callFunc();

    const fallUrl = getFallUrl(url);

    if (noFall) {
        return;
    }
    window.setTimeout(function() {
        if (Date.now() - time < 1200) {
            window.location.href = fallUrl;
        }
    }, 1000);
};

const callIframe = (url, noFall) => {
    checkOpenFall(url, () => {
        const ifr = document.createElement('iframe');

        ifr.src = url;
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
    }, noFall);
};

const callUrl = (url, noFall) => {
    checkOpenFall(url, () => {
        window.location.href = url;
    }, noFall);
};

const callA = (url, noFall) => {
    checkOpenFall(url, () => {
        const ca = document.createElement('a');

        ca.setAttribute('href', url);
        ca.style.display = 'none';
        document.body.appendChild(ca);

        ca.click();
    }, noFall);
};


export const toAppPage = (appUrl, noFall) => {
    if (isOriginalChrome) {
        callA(appUrl, noFall);
    } else if (isiOS) {
        if (getIOSVersion() < 9) {
            callIframe(appUrl, noFall);
        } else {
            callUrl(appUrl, noFall);
        }
    } else {
        callIframe(appUrl, noFall);
    }
};

export const toAppPageDialog = (options) => {
    dialog.showDialog({
        dialogText: options.title,
        hasFooter: {
            rightBtnText: '打开Yoho!Buy有货APP'
        }
    }, function() {
        toAppPage(options.appUrl);
    }, null, true);
};


export const openApp = () => {
    if (canOpenApp()) {
        setTimeout(function() {
            if (window._hmt && window._hmt.push) {
                window._hmt.push(['_trackEvent',
                    'H5唤起APP',
                    isiOS ? 'Apple' : 'Android',
                    document.title,
                    location.href]);
            }
        }, 1000);

        setTimeout(function() {
            let appPath = getAppPath();

            toAppPage(appPath, true);
        }, 2000);
    }
};

openApp();