var sdkVersion = 13, isSleep = !1, fileManager = tt.getFileSystemManager(), options = arequire("./effendi_config");

function init() {
    initBaseInfo(), initConfigInfo(), initListener(), loggerInfo(options), gameStart(), 
    startThread();
}

function setOpenId(e) {
    options.openId = e, tt.setStorageSync("effendi_openid", e);
}

function gameStart() {
    var e = {
        type: 1
    };
    options.queryParams && options.queryParams.effendiShareId ? e.shareId = options.queryParams.effendiShareId : e.shareId = "", 
    checkParams(e), addItem(e);
}

function pageOpen() {
    options.pageCount++;
    var e = {
        type: 2
    };
    checkParams(e), addItem(e);
}

function pageClose() {
    var e = {
        type: 3
    };
    checkParams(e), addItem(e);
}

function sendEvent(e, t) {
    var n = {
        type: 4
    };
    n.event = e, n.eventParam = t, checkParams(n), addItem(n);
}

function sendStage(e, t, n) {
    var o = {
        type: 6
    };
    o.pageId = e, o.event = t, o.eventParam = n, checkParams(o), addItem(o);
}

function sendLevel(e, t, n) {
    var o = {
        type: 7
    };
    o.levelId = e, o.event = t, o.eventParam = n, checkParams(o), addItem(o);
}

function sendPay(e, t, n, o) {
    var i = {
        type: 8
    };
    i.pageId = e, i.levelId = t, i.event = n, i.eventParam = o, checkParams(i), addItem(i);
}

function onShareAppMessage(e) {
    tt.onShareAppMessage(function(t) {
        if (!e) throw "回调函数不可以为空";
        var n = e(t);
        if (!n.shareType) throw "shareType 不可以为空";
        var o = wxuuid();
        n.query ? n.query = n.query + "&effendiShareId=" + o : n.query = "effendiShareId=" + o, 
        loggerInfo(n);
        var i = {
            type: 9
        };
        return i.shareId = o, i.shareType = n.shareType, checkParams(i), addItem(i), n;
    });
}

function sendPage(e, t) {
    e && (options.prePageId = e), t && (options.currentPageId = t);
    var n = {
        type: 10
    };
    n.prePageId = options.prePageId, n.pageId = options.currentPageId, n.event = "", 
    n.eventParam = {}, checkParams(n), addItem(n);
}

function sendHeatHeart(e) {
    var t = {
        type: 5
    };
    1 == e ? (options.serialNumber++, t.serialNumber = options.serialNumber) : t.serialNumber = 2 == e ? -1 : -2, 
    t.pageId = options.currentPageId, checkParams(t), addItem(t);
}

function sendDuration(e) {
    try {
        var t = {
            type: 11
        };
        t.duration = e, checkParams(t), addItem(t), uploadDemo();
    } catch (e) {}
}

var currentUserId = "";

function getUserId() {
    if (currentUserId) return currentUserId;
    if (options.useOpen) currentUserId = options.openId ? options.openId : tt.getStorageSync("effendi_openid"); else {
        var e = tt.getStorageSync("effendi_userid");
        e || (e = readUserIdFromFile()) && tt.setStorageSync("effendi_userid", e), e || (e = wxuuid(), 
        tt.setStorageSync("effendi_userid", e), writeUserToIdFile(e)), currentUserId = e, 
        readUserIdFromFile() || writeUserToIdFile(currentUserId);
    }
    return currentUserId;
}

var localUserId = "";

function getLocalUserId() {
    if (localUserId) return localUserId;
    var e = tt.getStorageSync("effendi_userid");
    return e || (e = readUserIdFromFile()) && tt.setStorageSync("effendi_userid", e), 
    e || (e = wxuuid(), tt.setStorageSync("effendi_userid", e), writeUserToIdFile(e)), 
    localUserId = e, readUserIdFromFile() || writeUserToIdFile(localUserId), localUserId;
}

function writeUserToIdFile(e) {
    try {
        fileManager.writeFileSync(options.effendiDir + "/effendi_user.data", e, "utf-8"), 
        loggerInfo("write userId:" + e);
    } catch (e) {}
}

function readUserIdFromFile() {
    var e = "";
    try {
        loggerInfo("read userId:" + (e = fileManager.readFileSync(options.effendiDir + "/effendi_user.data", "utf-8")));
    } catch (e) {}
    return e;
}

function loggerInfo(e) {
    options.useLogger && console.log(e);
}

function initBaseInfo() {
    if (options.baseURL || (options.baseURL = ""), !options.currentDir) {//https://openapi.jiegames.com
        var e = tt.env.USER_DATA_PATH + "/effendi", t = e + "/logs/";
        try {
            fileManager.mkdirSync(e, !0);
        } catch (e) {}
        try {
            fileManager.mkdirSync(t, !0);
        } catch (e) {}
        options.effendiDir = e, options.currentDir = t;
    }
    options.sessionId = wxuuid(), options.pageCount = 0, options.prePageId = "root", 
    options.currentPageId = "root", options.serialNumber = 0;
    var n = tt.getLaunchOptionsSync();
    options.sourceId = n.scene, options.queryParams = n.query, tt.getSystemInfo({
        success: function success(e) {
            options.manufacture = e.brand, options.model = e.model;
            var t = e.system;
            -1 != t.indexOf("iOS") ? (options.osType = 1, options.osCode = t) : -1 != t.indexOf("Android") ? (options.osType = 0, 
            options.osCode = t) : (options.osType = 2, options.osCode = t), options.isDeviceInfoReady = !0;
        }
    });
}

function initConfigInfo() {
    tt.request({
        url: options.baseURL + "/logger/getCurrentServerTimestamp",
        header: {
            "content-type": "application/json"
        },
        data: {
            gameId: options.game_id,
            channelId: options.channel_id
        },
        method: "GET",
        success: function success(e) {
            200 == e.data.code ? (options.diffTime = Number(e.data.serverTimestamp) - new Date().getTime(), 
            tt.setStorageSync("diffTime", options.diffTime)) : options.diffTime = tt.getStorageSync("diffTime");
        },
        fail: function fail(e) {
            options.diffTime = tt.getStorageSync("diffTime");
        }
    });
}

function initListener() {
    try {
        var e = new Date().getTime();
        tt.onShow && tt.onShow(function() {
            isSleep = !1, e = new Date().getTime(), options.pageCount > 0 && sendHeatHeart(2);
        }), tt.onHide && tt.onHide(function() {
            isSleep = !0;
            var t = new Date().getTime(), n = t - e;
            e > 0 && t > 0 && n > 0 && n < 864e5 && sendDuration(n), options.pageCount++;
        });
    } catch (e) {
        loggerInfo(e);
    }
}

function addItem(e) {
    try {
        e.sdkVersion = sdkVersion, e.gameId = options.game_id, e.channelId = options.channel_id, 
        e.requestId = wxuuid(), e.sessionId = options.sessionId + "_" + options.pageCount, 
        options.diffTime ? e.clientTimestamp = new Date().getTime() + Number(options.diffTime) : e.localTime = new Date().getTime();
        var t = options.currentDir + getFileName();
        fileManager.writeFileSync(t, JSON.stringify(e), "utf-8");
    } catch (e) {}
}

function getFileName() {
    var e = Math.floor(1e3 * Math.random());
    return "log_" + new Date().getTime() + "_" + e + ".log";
}

function checkParams(e) {
    if (!options.game_id) throw "游戏ID 不可以为空";
    if (!options.channel_id) throw "渠道ID 不可以为空";
    if (!e.type) throw "type 不可以为空";
    if (4 == e.type || 6 == e.type || 7 == e.type || 8 == e.type) {
        if (!e.event) throw "event 不可以为空";
        if (!e.eventParam) throw "eventParam 不可以为空";
    }
    if ((6 == e.type || 8 == e.type) && !e.pageId) throw "stageId 不可以为空";
    if ((7 == e.type || 8 == e.type) && !e.levelId) throw "levelId 不可以为空";
}

function wxuuid() {
    for (var e = "af-" + new Date().getTime() + "-", t = [], n = 0; n < 18; n++) {
        t[n] = "0123456789abcdef".substr(Math.floor(16 * Math.random()), 1);
    }
    return e + t.join("");
}

function loggerReqeust(e) {
    tt.request({
        url: options.baseURL + "/logger/uploadGameInfoInner",
        data: e.itemArray,
        header: {
            "content-type": "application/json"
        },
        method: "POST",
        success: function success(t) {
            200 == t.data.code ? e && e.success && e.success(t.data) : e && e.fail && e.fail();
        },
        fail: function fail(t) {
            e && e.fail && e.fail();
        }
    });
}

function checkNeedParams() {
    return new Promise(function(e, t) {
        getUserId() ? options.isDeviceInfoReady ? options.diffTime ? e("检查参数通过") : t("服务器间隔时间未准备好") : t("设备信息未准备好") : t("userId 或者openid 为空");
    });
}

function readFiles() {
    return new Promise(function(e, t) {
        fileManager.readdir({
            dirPath: options.currentDir,
            success: function success(t) {
                e(t);
            },
            fail: function fail(e) {
                t("read file error");
            }
        });
    });
}

function sendData(e) {
    return new Promise(function(t, n) {
        if (0 != e.files.length) {
            for (var o = [], i = [], r = 0; r < e.files.length; r++) {
                try {
                    var a = e.files[r];
                    o.push(a);
                    var s = fileManager.readFileSync(options.currentDir + a, "utf-8"), d = JSON.parse(s);
                    d.userId = getUserId(), d.sourceId = options.sourceId, d.manufacture = options.manufacture, 
                    d.model = options.model, d.osType = options.osType, d.osCode = options.osCode, d.clientTimestamp || (d.clientTimestamp = Number(d.localTime) + Number(options.diffTime), 
                    delete d.localTime), options.useOpen ? d.openId = getLocalUserId() : d.openId = "", 
                    i.push(d);
                } catch (e) {}
            }
            i.sort(function(e, t) {
                return e.clientTimestamp - t.clientTimestamp;
            }), loggerInfo(i), loggerReqeust({
                itemArray: i,
                success: function success(e) {
                    for (var n = 0; n < o.length; n++) {
                        var i = o[n], r = options.currentDir + i;
                        try {
                            fileManager.unlinkSync(r);
                        } catch (e) {
                            fileManager.unlink({
                                filePath: r
                            });
                        }
                    }
                    t(e);
                },
                fail: function fail() {
                    if (o.length >= 200) for (var e = 0; e < o.length; e++) {
                        var t = o[e], i = options.currentDir + t;
                        fileManager.unlinkSync(i);
                    }
                    n("send error");
                }
            });
        } else n("no files");
    });
}

var isDoing = !1;

function uploadDemo() {
    if (!isDoing) {
        isDoing = !0;
        try {
            var e = [ checkNeedParams, readFiles, sendData ], t = Promise.resolve();
            e.forEach(function(e) {
                t = t.then(e);
            }), t.then(function(e) {
                isDoing = !1, loggerInfo(e);
            }).catch(function(e) {
                isDoing = !1, loggerInfo(e);
            });
        } catch (e) {
            isDoing = !1;
        }
    }
}

function startThread() {
    for (var e = [], t = 0; t < 5; t++) {
        e[t] = setTimeout(function(t) {
            sendHeatHeart(1), uploadDemo(), clearTimeout(e[t]);
        }, 1e3 * (t + 1), t);
    }
    setInterval(function() {
        isSleep || (sendHeatHeart(1), uploadDemo());
    }, 1e4);
}

gmodule.exports = {
    init: init,
    setOpenId: setOpenId,
    sendEvent: sendEvent,
    sendStage: sendStage,
    sendLevel: sendLevel,
    sendPay: sendPay,
    onShareAppMessage: onShareAppMessage,
    sendPage: sendPage
};