
const API_Default_Host = "https://lottery.superdesk.cn/pingan_h5/pingan_webapi";

type QuestionItem = {
    id: number,
    type: number,
    question: string,
    options: string[]
}
export class NetManager {
    private static instance = new NetManager();

    private constructor() { }

    static getInst(): NetManager {
        return NetManager.instance;
    }

    private apiServerHost: string = API_Default_Host;
    private appToken: string = ""
    private activityID: number = 0
    private session: string = "";

    private userId: string = "";

    public status: number = 0;
    public prize: number = 0;
    public recordTime: string = ""
    public labelTips: string = ""
    public activityName: string = ""
    public lotteryItems: string[] = [];
    public lotteryPrize: string[] = [];
    public questions: QuestionItem[] = [];
    public preloadImg: Map<string, cc.SpriteFrame> = new Map();

    public initNet(callback: Function) {
        let params = this.URLParse()
        // this.appToken = params['appToken']
        this.appToken = params['token']
        this.activityID = params['activityID']
        if (CC_DEV) {

            this.appToken = this.appToken == null ? "U0tUSzQ2b0tWRVM2bDkyTm1pL1lubENoZUZWTGZwQjlNaUI2SEJTOTZYclRQcUlRb3A5eU9zd2VKMVNJeDlISlI0NmRmM29zalFFOGRrbTJmanhIekE9PQ==" : this.appToken
            this.activityID = this.activityID == null ? 15 : this.activityID
        }

        if (window["WEB_API"]) {
            this.apiServerHost = window["WEB_API"]
        }

        this.sendHttpPostRequest("/getUserInfo.php", { appToken: this.appToken, activityID: this.activityID }, (data) => {
            if (data.code == 200) {
                this.userId = data.data.user_id
                this.session = data.data.token;
                this.questions = data.data.questions
                this.status = data.data.status
                this.prize = data.data.prize
                this.lotteryItems = data.data.lotteryItems
                this.lotteryPrize = data.data.lotteryPrize
                this.labelTips = data.data.tips
                this.activityName = data.data.activityName
                this.recordTime = data.data.update_time

                let preloadData = []
                preloadData.push(["bg", data.data.bg_img])
                preloadData.push(["title", data.data.title_img])

                for (let key in data.data.lotteryImgs) {
                    preloadData.push(["item" + key, data.data.lotteryImgs[key]])
                }

                this.preloadRemoteImg(preloadData, callback)
            }
            else if (data.msg) {
                alert(data.msg)
            }
        });
    }

    private preloadRemoteImg(preloadData, cb) {
        let finishCnt = 0
        let total = preloadData.length
        for (let i = 0; i < preloadData.length; ++i) {
            let key = preloadData[i][0]
            let url = preloadData[i][1]
            if (url == null || url.length == 0) {
                continue
            }
            cc.assetManager.loadRemote(url, (err, texture: cc.Texture2D) => {
                if (!err) {
                    this.preloadImg[key] = new cc.SpriteFrame(texture)
                }
                finishCnt++

                if (finishCnt == total) {
                    cb && cb()
                }
            })
        }
    }

    /**
     * 提交答题结果
     * @param rightCount 
     * @param callback 
     */
    public submitAnswer(answers: object, callback: Function) {
        this.sendHttpPostRequest("/submitAnswer.php",
            {
                userId: this.userId,
                activityID: this.activityID,
                answers: JSON.stringify(answers),
            },
            (data) => {
                callback && callback(data);
            });
    }

    public rollItem(callback: Function) {
        this.sendHttpPostRequest("/getLottery.php", { activityID: this.activityID }, (data) => {
            if (data && data.code == 200) {
                callback && callback(data.data.id, data.data.name);
            }
            else {
                callback && callback(-1);
            }
        });
    }

    private sendHttpPostRequest(apiPath, data, callback: Function = null) {
        let xhr: XMLHttpRequest = new XMLHttpRequest()
        xhr.timeout = 10000;
        let requestURL = this.apiServerHost + apiPath;
        data.token = this.session;
        xhr.open("POST", requestURL, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

        cc.log("http post:" + JSON.stringify(data));
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                let jsonData = null;
                cc.log("http recv:" + xhr.responseText);
                try {
                    jsonData = JSON.parse(xhr.responseText);
                } catch (e) {
                    cc.log("err:" + e);
                }
                callback && callback(jsonData);
            }
        };

        let str = "";
        for (var k in data) {
            if (str != "?") {
                str += "&";
            }
            str += k + "=" + data[k];
        }
        xhr.send(str);
    }

    private URLParse() {
        let params = {};
        if (window.location == null) {
            return params;
        }

        let name = "";
        let value = "";
        let paramString = window.location.href;
        let num = paramString.indexOf("?");
        paramString = paramString.substr(num + 1);

        let arr = paramString.split("&");
        for (let i = 0; i < arr.length; ++i) {
            num = arr[i].indexOf("=");
            if (num > 0) {
                name = arr[i].substring(0, num);
                value = arr[i].substr(num + 1);
                params[name] = decodeURIComponent(value);
            }
        }

        return params;
    }
}