import { sys } from "cc";

export enum REPORT_EVENT {
    ENTER_GAME = '进入游戏',
    LOAD_COMPLETE = '加载完成',

    ENTER_LEVEL = '进入关卡',
    LEVEL_PASS = '关卡通过',
    LEVEL_FAIL = '关卡失败',
    LEVEL_REST = '重置关卡',

    CLICK_LEAVE = '点击直接开走按钮',
    CLICK_ADD_CELL = '点击加两个格按钮',
    CLICK_CLEAR_CELL = '点击清理格子按钮',

    START_ADD_CELL_AD = '拉起加两个格广告',
    START_LEAVE_AD = '拉起直接开走广告',
    START_CLEAR_CELL_AD = '拉起清空格子广告',

    END_ADD_CELL_AD = '看完加两个格广告',
    END_LEAVE_AD = '看完直接开走广告',
    END_CLEAR_CELL_AD = '看完清空格子广告',

    OPEN_RECOVERY = '打开复活窗口',
    CLICK_RECOVERY = '点击复活按钮',
    OPEN_REWARD = '点击限时福利',
    CLICK_SIDEBAR = '点击从侧边栏进入',

    OPEN_CHANGE_SKIN = '打开换肤窗口',
    CLICK_CHANGE_SKIN = '点击换肤按钮',
}

export class DataSdk {
    private static SaveKey = "ttzt_ext"
    private static ReportURL = "https://dataapi.uwotao.com/api/v1/game/report"

    private static extend: { [k: string]: any } = {};
    public static get openid() { return this.extend && this.extend.openid }


    public static initReport(openid?: string) {
        if (typeof window.tt === 'undefined' || !tt) {
            console.log("#### DataSdk #### 非字节平台不初始化")
            return;
        }
        console.log("#### DataSdk #### 初始化")
        // 加载历史记录
        let savedata = sys.localStorage.getItem(this.SaveKey);
        console.log("#### DataSdk #### 读取旧数据", savedata)
        if (savedata) {
            this.extend = JSON.parse(savedata)
        }

        // 如果已经激活, 不重复上报
        if (DataSdk.openid) {
            console.log("#### DataSdk #### 激活已经上报，不重复上报, openid:", DataSdk.openid)
            return;
        }

        let options = tt.getLaunchOptionsSync();
        let queryStr = JSON.stringify(options.query)
        let appid = options.extra.appId || options.query.appId
        console.debug("#### DataSdk #### appid:", appid, "query:", queryStr);
        if (openid) {
            DataSdk.extend = {}
            DataSdk.extend.openid = openid;
        }
    }


    public static reportEvent(event: REPORT_EVENT, param: any='') {
        try {
            tt.request({
                url: DataSdk.ReportURL,
                data: {
                    openid: DataSdk.openid,
                    eventName: event,
                    msg: `${param}`
                },
                header: { "content-type": "application/json" },
                method: "POST",
                success: (res: any) => {
                    console.log("#### DataSdk #### 数据上报成功", res.data)
                },
                fail: (res: any) => {
                    console.log("#### DataSdk #### 数据上报失败", res.errMsg)
                },
            })
        } catch (error) {
            console.log("#### DataSdk #### 数据上报请求错误")
        }
       
    }
}