

//////////补给站用到的接口集成

import { ajax, jsonp } from "../../module/web/ajax"
import { showToast } from "../../module/ctrls"
import { duiba_md5 } from "../../module/tools/security"

//部分情况需要，比如duiba_md5，需跳转下载的
// <script crossorigin="anonymous" src="//yun.duiba.com.cn/db_games/libs/zepto_security_downloadApp.min.js"></script>
/**
 * 获取基本信息
 */
export function ajaxElement(): Promise<{ success: boolean, data?: any }> {
    return new Promise((r) => {
        ajax({
            url: "/hdtool/recon/ajaxElement", //请求地址
            type: "GET",//"POST",   //请求方式
            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 || "网络异常，请稍后再试")
                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 getTokenHdtool();
        if (!token) {//如果没有token
            showToast("token获取失败")
            r({ success: false })
            return
        }
        ajax({
            url: "/hdtool/recon/doJoin",
            type: "GET",//"POST",   //请求方式
            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 || "网络异常，请稍后再试")
                r(res)
            },
            error: function (status) {
                showToast("网络异常，请稍后再试")
                r({ success: false })
            },
        })
    })
}
/**
 * 开始游戏轮询
 * @param orderId doJoin返回的数据中的data字段
 */
export function getNgameStartStatus(orderId): Promise<any> {
    let count = 0;
    return new Promise((resolve) => {
        (async function ask(r) {
            const data = await getN(orderId);
            if (data.code == "0000000000") {
                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) => {
        ajax({
            url: "/hdtool/recon/ngame/getNgameStartStatus",
            type: "GET",//"POST",   //请求方式
            data: {
                orderId,
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                r(res)
            },
            error: function (status) {
                r({ success: false })
            },
        })
    })
}

/**
 * 
 * @param orderId doJoin里的数据data字段
 * @param score 分数可能传1
 * @param submitToken 轮询数据里的data.submitToken
 */
export function submit(orderId: string, score: number, submitToken: string): Promise<{ success: boolean, data?: any }> {
    let gameData = "[]";
    // let sgin = 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,
        sgin,
        dynamicData
    };
    return new Promise((r) => {
        ajax({
            url: "/hdtool/recon/ngame/ngameSubmit",
            type: "POST",   //请求方式
            data: param, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                if (!res.success) showToast(res.desc || "网络异常，请稍后再试")
                r(res)
            },
            error: function (status) {
                showToast("网络异常，正在重试中")
                r({ success: false })
            },
        })
    })
}

/**
 * 获取奖品信息，这里面的data.element用于更新ajaxElement，要轮询
 * @param orderId doJoin里的数据data字段
 */
export function getOrderStatus(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") {
                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) => {
        ajax({
            url: "/hdtool/recon/getOrderStatus", //请求地址
            type: "GET",//"POST",   //请求方式
            data: {
                orderId
            }, //请求参数
            dataType: "json",     // 返回值类型的设定,暂时只有json
            async: true,   //是否异步
            // headers: headers,
            success: function (res) {
                r(res)
            },
            error: function (status) {
                r({ success: false })
            },
        })
    })
}
/**
 * 补给站获取token
 */
function getTokenHdtool(): Promise<string> {
    return new Promise((r) => {
        if (window.location.port == "8080") {//本地开发
            r("token")
        } else {
            if (!window['getDuibaToken']) {
                r(null);
            } else {
                window['getDuibaToken']((tokenObj) => {
                    r(tokenObj.token);
                }, (key, messageObj) => {
                    r(null);
                });
            }
        }
    })
}
/**
 * 获取我的奖品链接，老活动工具 window.location.href = getRecordUrl('00');
 * @param type 
 * @param ids 
 */
export function getRecordUrl(type: '00', 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;
}

/**
 * 补给站埋点
 * @param type 
 * @param area 
 */
export function sendLogBuji(type: 'exposure' | 'click', area: number) {
    var appId = window["CFG"].appId;
    var oaId = window["CFG"].oaId;
    var dpm = appId + '.' + 263 + '.' + area + '.' + 1;//怎么拼按具体需求
    var dcm = 202 + '.' + oaId + '.0.0';//怎么拼按具体需求
    let params: any = {
        dpm,
        dcm,
        appId,
        consumerId: window["CFG"].consumerId,
        domain: '//embedlog.duiba.com.cn'
    };
    let isExposure = (type == "exposure");
    if (isExposure) {
        jsonp('//embedlog.duiba.com.cn/exposure/standard', params);
    } else {
        jsonp('/log/click', params);
    }
}


//补给站老活动会用到
window["CFG"] = {
    actId: '143212468677481',
    oaId: '143212468677481',
    unitName: '猫币',
    btnUnitName: '猫币',
    doJoin: '/hdtool/doJoin?dpm=1.3.1.0&activityId=143212468677481',
    quireOrder: '/hdtool/getOrderStatus',
    styleConfig: '/hdtool/getHdtoolConfig',
    getElement: '/hdtool/ajaxElement',
    getPrizeDetail: '/hdtool/prizeDetail',
    ajaxThroughInfo: '/hdtool/ajaxThroughInfo',
    throughSubmit: '/hdtool/throughSubmit',
    gameGetOrder: '/hdtool/getOrderInfo',//游戏获取订单信息接口
    gameSubmit: '/hdtool/gameSubmit',//游戏结果提交接口
    doSubmit: '/hdtool/submit',
    adslotId: '',
    consumerId: '1',
    isNotLoginUser: false,
    uid: '1',
    hdType: 'duiba',
    hdToolId: '43743',
    appType: 'credits',
    subType: 'lotteryMachine',
    directSendCoupon: 'false',
    ajaxAction: '',
    recommendQueue: '/recommend/getRecommend',
    recommendSkin: '/recommend/getRecommendSkin',
    isShowDetail: true,
    preview: false,
    from: '',
    login: '//activity.m.duiba.com.cn/hdtool/login?dpm=1.3.3.0',
    flowRedirectUrl: '',
    flowRedirectTuiaUrl: '',
    isOpenRecommend: false,
    getCreditsLink: 'mxsa://magicshop/cointask?uid=1&dbnewopen',
    appId: '1',
    recordUrl: '//activity.m.duiba.com.cn/crecord/record?dbnewopen&dpm=1.3.2.0',
    shareDesc: '分享分享文案文案',
    entranceDesc: '测试领奖，也可到我的奖品领奖哦！！！',
    isSHowMeat: true,
    needCouponModal: true,  // 给前端用，判断是否需要使用配置的优惠券弹窗
    needRecommendModal: true,  // 给前端用，判断是否需要公用推荐位弹窗
    asyncFiles: [],         // 给前端用，异步加载的文件
    shareAndroidLinkActivity: 'http://www.baidu.com',
    shareIosLinkActivity: 'http://www.iqiyi.com'
};
