import { sys } from "cc";

export class ttZtSdk {
    private static SaveKey = "ttzt_ext"
    private static ReportURL = "https://api.zt.y73s.cn/api/v1/conversion"

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

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

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

        tt.login({
            force: true,
            success: (res: any) => {
                console.debug(`#### ttZtSdk #### login 调用成功code:${res.code} a_code:${res.anonymousCode}`);
                let options = tt.getLaunchOptionsSync();
                let queryStr = JSON.stringify(options.query)
                let appid = options.extra.appId || options.query.appId
                console.debug("#### ttZtSdk #### appid:", appid, "query:", queryStr);
                tt.request({
                    url: ttZtSdk.ReportURL,
                    data: {
                        code: res.code,
                        anonvmous_code: res.anonymousCode,
                        appid: appid, // 请求来源：appid
                        active_data: queryStr, // 激活相关数据 json字符串
                    },
                    header: { "content-type": "application/json" },
                    method: "POST",
                    success: (res: any) => {
                        console.log("#### ttZtSdk #### 数据上报成功", res.data)
                        if (res.data.code == 0) {
                            ttZtSdk.extend = {}
                            ttZtSdk.extend.openid = res.data.data.openid;
                            ttZtSdk.extend.clickid = res.data.data.clickid;
                            let extStr = JSON.stringify(ttZtSdk.extend)
                            console.log("#### ttZtSdk #### ext:", extStr)
                            sys.localStorage.setItem(this.SaveKey, extStr)
                        }
                    },
                    fail: (res: any) => {
                        console.log("#### ttZtSdk #### 数据上报失败", res.errMsg)
                    },
                })
            },
            fail: (res: any) => {
                console.debug(`#### ttZtSdk #### login调用失败`, res);
            },
        });
    }
}