import { sys } from "cc";
import { DataSdk } from "./datasdk";

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(openid?: string) {
        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;
        }

        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);
        if (openid) {
            this.reportActive$({
                appid: appid, // 请求来源：appid
                openid: openid,
                active_data: queryStr, // 激活相关数据 json字符串
            });
        } else {
            tt.login({
                force: true,
                success: (res: any) => {
                    console.debug(`#### TTZtSdk #### login 调用成功code:${res.code} a_code:${res.anonymousCode}`);
                    this.reportActive$({
                        appid: appid, // 请求来源：appid
                        code: res.code,
                        anonvmous_code: res.anonymousCode,
                        active_data: queryStr, // 激活相关数据 json字符串
                    });
                },
                fail: (res: any) => {
                    console.debug(`#### TTZtSdk #### login调用失败`, res);
                },
            });
        }
    }

    private static reportActive$(param: any) {
        tt.request({
            url: TTZtSdk.ReportURL,
            data: param,
            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)
                    DataSdk.initReport(res.data.data.openid)
                }
            },
            fail: (res: any) => {
                console.log("#### TTZtSdk #### 数据上报失败", res.errMsg)
            },
        })
    }
}