import { INetData } from "../libs/tc/index";
import { NetManager } from "../libs/tw/index";

const projectxString = "projectx/";
let projectId: string;
export function getProjectId(): string {
    if (projectId) return projectId;

    let windowUrl = window.location.href;
    let splitArr = windowUrl.split(projectxString);
    if (splitArr.length != 2) {

        return projectId = "projectId"
    }

    let start = windowUrl.indexOf(projectxString) + projectxString.length;
    let end = splitArr[1].indexOf("/");
    return projectId = windowUrl.substr(start, end);
}

const NetUrl = {
    //首页接口
    home: "/projectx/{projectId}/join_1/getHomeInfo.do",
    //参与游戏
    doJoin: "/projectx/{projectId}/join_1/join.do",
    //抽奖
    submit: "/projectx/{projectId}/join_2/join.do",
    //奖品信息
    prizeInfo: "/projectx/{projectId}/prize.query",
}

const urlReplaceConfig = {
    "{projectId}": getProjectId()
}

export function urlReplace() {
    for (let i of Object.keys(NetUrl)) {
        for (let j of Object.keys(urlReplaceConfig)) {
            NetUrl[i] = NetUrl[i].replace(new RegExp(j, "g"), urlReplaceConfig[j]);
        }
    }
}

/**
 * 首页接口
 * @param callback 
 */
export function sendHome(callback: Function) {
    const net: INetData = {
        name: "sendHome",
        uri: NetUrl.home,
        type: 'get',
        dataType: 'json',
        param: {},
        callback: callback,
        hideMsg: true
    };
    NetManager.ins.send(net);
}

/**
 * 参与游戏
 * @param callback 
 */
export function sendDoJoin(callback: Function) {
    const net: INetData = {
        name: "sendDoJoin",
        uri: NetUrl.doJoin,
        type: 'get',
        dataType: 'json',
        param: {},
        callback: callback,
        hideMsg: true
    };
    NetManager.ins.send(net);
}
/**
 * 抽奖
 * @param callback 
 */
export function sendSubmit(callback: Function) {
    var timestamp = Date.now();
    const net: INetData = {
        name: "sendSubmit",
        uri: NetUrl.submit,
        type: 'get',
        dataType: 'json',
        param: {
            timestamp: timestamp,
            token: window["duiba_md5"](timestamp.toString() + "dui-ccbspring")
        },
        callback: callback,
        hideMsg: true
    };
    NetManager.ins.send(net);
}

/**
 * 获取奖品信息
 * @param callback 
 * @param ids 
 */
export function getPrizeInfo(callback: Function, ids: string) {
    const net: INetData = {
        name: "getPrizeInfo",
        uri: NetUrl.prizeInfo,
        type: 'get',
        dataType: 'json',
        param: {
            ids
        },
        callback: callback,
        hideMsg: true
    };
    NetManager.ins.send(net);
}

