const KEY = "user_uid";
function uuid(len = 32, radix = 16) {
    const chars =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
    const uuid = [];
    let i;
    radix = radix || chars.length;

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
    } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | (Math.random() * 16);
                uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join("");
}
const generateUUID = () => {
    const uuidValue = localStorage.getItem(KEY);
    if (!uuidValue) {
        const uid = uuid();
        localStorage.setItem(KEY, uid);
        return uid;
    }
    return uuidValue;
};

const getUUID = () => {
    const uuid = localStorage.getItem(KEY);
    if (!uuid) {
        return generateUUID();
    }
    return uuid;
};

const bindDownloadEvent = (dataBack) => {
    const ios = is_ios || isMac;
    const android = is_android || isWindow;
    const downloadInfo = dataBack.downloadList.find(
        (item) => ((ios && item.type === 1) || (android && item.type === 0))
    );
    $("#downloadBtn").on("click", function () {
        copyFn();
        if (downloadInfo && downloadInfo.downloadUrl) {
            // plist文件需要加前缀
            if (downloadInfo.downloadUrl.endsWith(".plist")) {
                window.location.href = `itms-services://?action=download-manifest&url=${downloadInfo.downloadUrl}`;
                return;
            }
            window.location.href = downloadInfo.downloadUrl
            return;
        }
    });
}

function getCookie(key) {
    const res = document.cookie.split(";");
    for (let i = 0; i < res.length; i++) {
        const temp = res[i].split("=");
        if (temp[0].trim() === key) {
            return temp[1];
        }
    }
}

function isEmpty(str) {
    return str === null || str === undefined || str === '';
}

function nonEmpty(str) {
    return !isEmpty(str);
}

function copyFn() {
    const tenant = $("#tenant").val();
    const rcCode = getQueryVariable("rc");
    const recommendCode = rcCode || getCookie("rcCode") || window.location.host;
    const code = `[${tenant}]:${recommendCode}`;
    let oInput = document.createElement('input');
    oInput.value = code;
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand('Copy');
    oInput.remove();
}

function getDownloadUri(data) {
    // 苹果设备下载路径
    if (is_ios || isMac) {
        let retUrl;
        data.forEach((item) => {
            if (item.type === 1) {
                if (item.downloadUrl.endsWith(".plist")) {
                    retUrl = `itms-services://?action=download-manifest&url=${item.downloadUrl}`;
                }
                retUrl = item.downloadUrl;
            }
        });
        if(retUrl) {
            return retUrl;
        }
    }
    // 非苹果设备下载路径
    const androidData = data.find((item) => item.type === 0);
    return androidData ? androidData.downloadUrl : window.location.host;
}

function getHeader() {
    const timestamp = Date.now();
    const signParams = {
        "device-id": getUUID(), //deviceId
        "os-type": 1,
        timestamp,
        version: "1.0",
    };

    const urlStr = urlEncode(signParams).substr(1);
    Object.assign(signParams, {
        sign: md5(`${urlStr}global`),
        "app-type": 0,
        tenant: "kc107",
    });
    return signParams;
}

function openWeb(url) {
    url = url === undefined ? window.location.href : url;
    let schema = "http://";
    if (url.indexOf("http://") === 0) {
        schema = "http://";
        url = url.replace(schema, "");
    }
    if (url.indexOf("https://") === 0) {
        schema = "https://";
        url = url.replace(schema, "");
    }
    if (url.indexOf("/") > 0) {
        url = url.substring(0, url.indexOf("/"));
    }
    const rcCode = getQueryVariable("rc");
    const recommendCode = rcCode || getCookie("rcCode") || window.location.host;
    if (recommendCode !== undefined && recommendCode !== null && recommendCode !== "") {
        url = url.endsWith("/") ? url + "r/" + recommendCode : url + "/r/" + recommendCode;
    }
    window.open(schema + url);
}

function urlEncode(param, key, encode) {
    if (param == null) return "";
    let paramStr = "";
    const t = typeof param;
    if (t == "string" || t == "number" || t == "boolean") {
        paramStr += `&${key}=${
            encode == null || encode ? encodeURIComponent(param) : param
        }`;
    } else {
        for (const i in param) {
            const k =
                key == null ? i : key + (param instanceof Array ? `[${i}]` : `.${i}`);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
}

function getQueryVariable(variable) {
    let query = window.location.search.substring(1);
    let vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return "";
}

function random(n, m) {
    return Math.floor(Math.random() * (m - n + 1) + n);
}

const isServer = typeof window == "undefined";

const wind = isServer ? null : window;

const NAV = (() => {
    return isServer ? null : window.navigator;
})();

const UA = NAV ? NAV.userAgent.toLowerCase() : "";

const is_ipad = /ipad/i.test(UA) && !wind.MSStream;

const is_iphone = /iphone/i.test(UA) && !wind.MSStream;

const is_ipod = /ipod/i.test(UA) && !wind.MSStream;

const is_ios = /ipad|iphone|ipod/i.test(UA) && !wind.MSStream;

const is_android = /android/i.test(UA);

const is_ie = /(trident|microsoft)/i.test(NAV ? NAV.appName : "");

const isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(
    navigator.userAgent
);

const isIosMobile = isMobile && is_ios;

const isMac = /macintosh|mac os x/i.test(UA);

const isWindow = UA.indexOf("win32") >= 0 || UA.indexOf("wow32") >= 0 || UA.indexOf("win64") >= 0 || UA.indexOf("wow64") >= 0;