
export const globalData: {
    "element"?: {
        "isCreditsTypeOpen": boolean,
        "myCreditsLong": number,
        "freeLimit": number,
        "success": false,
        "myCredits": string,
        "needCredits": string,
        "freeEmpty": true,
        "needCreditsLong": number,
        "status": number
    },
    rule?: string,
    orderId?: string,
    submitToken?: string,
    lottery?: {

    }
} = {

}

export function ajaxElement(): Promise<{ success: boolean, data?: any }> {
    return new Promise((r) => {
        window['$'].ajax({
            url: "/hdtool/recon/ajaxElement", //请求地址
            type: "GET",//"POST",   //请求方式
            cache: false,
            data: {
                duibaId: window['CFG'].hdToolId,
                activityId: window['CFG'].actId,
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                if (!res.success) {
                    showToast(res.desc || "网络异常，请稍后再试")
                } else {
                    globalData.element = res.data.element;
                    globalData.rule = res.data.rule;
                }
                r(res)
            },
            error: function (status) {
                showToast("网络异常，请稍后再试")
                r({ success: false })
            },
        })
    })
}
//开始游戏，接口可能有变
export function doJoin(): Promise<{ success: boolean, data?: any }> {
    return new Promise(async (r) => {
        //获取token
        var token = await getTokenHdtoll();
        if (!token) {//如果没有token
            showToast("token获取失败")
            r({ success: false })
            return
        }
        window['$'].ajax({
            url: "/hdtool/recon/doJoin",
            type: "GET",//"POST",   //请求方式
            cache: false,
            data: {
                token,
                activityId: window['CFG'].actId,
                activityType: "hdtool",
                consumerId: window['CFG'].consumerId
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                if (!res.success) {
                    showToast(res.desc || "网络异常，请稍后再试")
                } else {
                    globalData.orderId = res.data
                }
                r(res)
            },
            error: function (status) {
                showToast("网络异常，请稍后再试")
                r({ success: false })
            },
        })
    })
}
//轮询
export function getNgameStartStatus(orderId = globalData.orderId): Promise<any> {
    let count = 0;
    return new Promise((resolve) => {
        (async function ask(r) {
            const data = await getN(orderId);
            if (data.code == "0000000000") {
                //@ts-ignore
                globalData.submitToken = data.data.submitToken
                r(data);
            } else {
                //超过10次的话，提示下
                if (++count >= 10) {
                    showToast("获取开始游戏信息失败\n请稍后重试")
                    r({ success: false })
                    return
                }
                setTimeout(() => { ask(r) }, 500)
            }
        })(resolve)
    })
}

function getN(orderId): Promise<{ success: boolean, data?: any, code?: string }> {
    return new Promise((r) => {
        window['$'].ajax({
            url: "/hdtool/recon/ngame/getNgameStartStatus",
            type: "GET",//"POST",   //请求方式
            cache: false,
            data: {
                orderId,
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                r(res)
            },
            error: function (status) {
                r({ success: false })
            },
        })
    })
}

/**
 * 
 * @param orderId doJoin里的数据
 * @param score 分数可能传1
 * @param submitToken 开始状态轮询数据里的
 */
export function submit(
    orderId: string = globalData.orderId,
    score: number = 1,
    submitToken: string = globalData.submitToken
): Promise<{ success: boolean, data?: any }> {
    let gameData = "[]";
    let sign = window['duiba_md5'](orderId + '' + score + '' + gameData + '' + submitToken);
    // let sgin = duiba_md5(orderId + '' + score + '' + gameData + '' + submitToken);
    let dynamicData = JSON.stringify(`{t2:${new Date().getTime()}}`);
    const param: any = {
        orderId,
        score,
        gameData,
        sign,//新的加密接口用这个
        dynamicData
    };

    return new Promise((r) => {
        window["$"].ajax({
            url: "/hdtool/refactor/ngame/submit",
            type: "POST",   //请求方式
            cache: false,
            data: null, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            headers: { "Hdtool-Content": encrypt(param) },
            success: function (res) {
                if (!res.success) showToast(res.desc || "网络异常，请稍后再试")
                r(res)
            },
            error: function (status) {
                showToast("网络异常，正在重试中")
                r({ success: false })
            },
        })
    })
}

//获取奖品信息，这里面的data.element用于更新ajaxElement，要轮询
export function getOrderStatus(orderId = globalData.orderId): Promise<{ success: boolean, data?: any }> {
    let count = 0;
    return new Promise((resolve) => {
        (async function ask(r) {
            const data = await getO(orderId);
            if (data.code == "0000000000") {
                globalData.element = data.data.element;
                globalData.lottery = data.data.lottery;
                r(data);
            } else {
                //超过10次的话，提示下
                if (++count >= 10) {
                    showToast("获取开始游戏信息失败\n请稍后重试")
                    r({ success: false })
                    return
                }
                setTimeout(() => { ask(r) }, 500)
            }
        })(resolve)
    })
}

function getO(orderId): Promise<{ success: boolean, data?: any, code?: string }> {
    return new Promise((r) => {
        window["$"].ajax({
            url: "/hdtool/recon/getOrderStatus", //请求地址
            type: "GET",//"POST",   //请求方式
            cache: false,
            data: {
                orderId
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                r(res)
            },
            error: function (status) {
                r({ success: false })
            },
        })
    })
}

function getTokenHdtoll(): Promise<string> {
    return new Promise((r) => {
        if (window.location.port == "8080") {
            r("111")
        } else {
            if (!window['getDuibaToken']) {
                r(null);
            } else {
                window['getDuibaToken']((tokenObj) => {
                    r(tokenObj.token);
                }, (key, messageObj) => {
                    r(null);
                });
            }
        }
    })
}



//加密
function encrypt(data) {
    //排序键值
    // let keysSorted = Object.keys(data).sort(function (a, b) { return data[b] - data[a] })
    // var str = "";   //aaa=a&bbb=b&cc=c；
    // for (let i = 0; i < keysSorted.length; i++) {
    //     if (str) str += "&";
    //     str += keysSorted[i] + "=" + data[keysSorted[i]];
    // }
    // JSON.stringify(data)
    var kk = (+window['CFG'].consumerId).toString(32)
    kk = kk.substring(0, 16);
    //补0；
    var len = kk.length;
    while (len < 16) {
        kk = kk + "0";
        len++;
    }

    var ii = (+window['CFG'].consumerId).toString(16)
    ii = ii.substring(0, 16);
    //补0；
    var len = ii.length;
    while (len < 16) {
        ii = ii + "0";
        len++;
    }

    var CryptoJS = window["CryptoJS"];
    var key = CryptoJS.enc.Utf8.parse(kk);
    var iv = CryptoJS.enc.Utf8.parse(ii);
    return CryptoJS.AES.encrypt(/*str*/JSON.stringify(data), key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    }).toString();
}


export function showToast(msg) {
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText = "width:60%; min-width:150px; background:#000; opacity:0.5; height:40px; color:#fff; line-height:40px; text-align:center; border-radius:5px; position:fixed; top:40%; left:20%; z-index:999999; font-weight:bold;";
    document.body.appendChild(m);
    setTimeout(function () {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function () { document.body.removeChild(m) }, d * 1000);
    }, 1000);
} 
// window.location.href = getRecordUrl('00');
//到时处理，封装到Hdtool
export function getRecordUrl(type, ids?) {
    let recordUrl;
    let oaId;

    oaId = window["CFG"].oaId;
    recordUrl = window["CFG"].recordUrl;

    if (!ids) {
        ids = [oaId];
    }

    let i = 0;
    const len = ids.length;
    for (i; i < len; i++) {
        if (window.location.href.indexOf("?") == -1) {
            recordUrl += '?origins=' + ids[i] + type;
        } else {
            recordUrl += '&origins=' + ids[i] + type;
        }

    }
    return recordUrl;
}