import { sys } from "cc";
import { Framework } from "../../framework/Framework";
import { StringUtil } from "../../framework/util/StringUtil";
import { TimeUtil } from "../../framework/util/TimeUtil";
import { Sha1 } from "./Sha1";
export enum ClueType {
    active = 0,                 //激活
    active_register,            //注册
    active_pay,                 //付费
    next_day_open = 6,          //次留
    game_addiction = 25,        //关键行为
}

class Clue {

    private _clue_token: string = "";
    private _ad_id: string = "";
    private _creative_id: string = "";
    private _req_id: string = "";
    private _advertiser_id: string = "";
    open_id: string = "";

    init() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            // @ts-ignore
            let obj = wx.getLaunchOptionsSync();
            let str = "path:/pages/index.html?clue_token=首都华盛顿国会大厦解开了&ad_id=啊啊啊啊啊&creative_id=啵啵啵宝宝&req_id=阿斯顿法国代购&advertiser_id=丰厚的发";
            let sign1 = "clue_token=";
            let sign2 = "&ad_id=";
            this._clue_token = str.slice(str.indexOf(sign1) + sign1.length, str.indexOf(sign2));

            sign1 = "ad_id=";
            sign2 = "&creative_id";
            this._ad_id = str.slice(str.indexOf(sign1) + sign1.length, str.indexOf(sign2));

            sign1 = "creative_id=";
            sign2 = "&req_id";
            this._creative_id = str.slice(str.indexOf(sign1) + sign1.length, str.indexOf(sign2));

            sign1 = "req_id=";
            sign2 = "&advertiser_id";
            this._req_id = str.slice(str.indexOf(sign1) + sign1.length, str.indexOf(sign2));

            sign1 = "advertiser_id=";
            this._advertiser_id = str.slice(str.indexOf(sign1) + sign1.length, str.length);

            this.send(ClueType.active);
            let register_time = Framework.storage.get("register_time", 0);
            if (register_time != 0) {
                let cur_time = TimeUtil.getTimeEx(0);
                if (TimeUtil.getDayInterval(cur_time, register_time) == 1) {
                    this.send(ClueType.next_day_open);
                    Framework.storage.get("register_time", cur_time);
                }
            }
        }
    }

    //签名
    private _sign(token: string, timestamp: number, nonce: string) {
        let strList = [token, timestamp, nonce];
        strList.sort();
        let buffer = "";
        strList.forEach(str => { buffer += str; })
        return (new Sha1(buffer)).hex_sha1();
    }

    //报告
    send(type: ClueType, props: Object = null) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            let time = TimeUtil.getTimeEx(0);
            let random = StringUtil.getUUID(64);
            let data = {
                "clue_token": this._clue_token,
                "union_id": "",
                "open_id": this.open_id,
                "event_type": type.toString(),
                "props": props || {},
            };
            let url = StringUtil.format("https://xxx.com/xxx?timestamp={0}&nonce={1}&signature={2}", time, random, this._sign(this._clue_token, time, random));
            this._post(url, data, (code: number, resp: any | null) => {
                if (code == 1 && resp) {
                    console.log("上报成功");
                }
            });
        }
    }

    private _post(url: string, data: object | string, callback: (statusCode: number, resp: any | null) => any) {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 2000;
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
                let resp = null;
                try {
                    if (xhr.responseText != "") {
                        resp = JSON.parse(xhr.responseText);
                    }
                } catch (e) {
                }
                callback && callback(1, resp);
            }
        };
        xhr.onerror = () => {
            callback && callback(0, null);
        };
        xhr.ontimeout = () => {
            callback && callback(0, null);
        };
        let text = typeof (data) == "string" ? data : JSON.stringify(data);
        xhr.send(text);
        return xhr;
    }
}

export let AppClue = new Clue();