var sdkVersion = 14, isSleep = !1, fileManager = wx.getFileSystemManager(), options = arequire("./effendi_config"), callbackOnShow = null, callbackOnHide = null;

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

function setOpenId(e) {
    options.openId = e, wx.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 sendPage(e, n) {
    e && (options.prePageId = e), n && (options.currentPageId = n);
    var t = {
        type: 10
    };
    t.prePageId = options.prePageId, t.pageId = options.currentPageId, t.event = "", 
    t.eventParam = {}, checkParams(t), addItem(t);
}

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

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

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

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

function onShow(e) {
    callbackOnShow = e;
}

function onHide(e) {
    callbackOnHide = e;
}

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

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

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

var currentUserId = "";

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

var localUserId = "";

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

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

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

function initConfigInfo() {
    wx.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(), 
            wx.setStorageSync("diffTime", options.diffTime)) : options.diffTime = wx.getStorageSync("diffTime");
        },
        fail: function fail(e) {
            options.diffTime = wx.getStorageSync("diffTime");
        }
    });
}

function initListener() {
    try {
        var e = new Date().getTime();
        wx.onShow && wx.onShow(function() {
            if (callbackOnShow) try {
                callbackOnShow();
            } catch (e) {}
            isSleep = !1, e = new Date().getTime(), options.pageCount > 0 && sendHeatHeart(2);
        }), wx.onHide && wx.onHide(function() {
            if (callbackOnHide) try {
                callbackOnHide();
            } catch (e) {}
            isSleep = !0;
            var n = new Date().getTime(), t = n - e;
            e > 0 && n > 0 && t > 0 && t < 864e5 && sendDuration(t), 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 n = options.currentDir + getFileName();
        fileManager.writeFileSync(n, JSON.stringify(e), "utf-8");
    } catch (e) {}
}

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 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() + "-", n = [], t = 0; t < 18; t++) {
        n[t] = "0123456789abcdef".substr(Math.floor(16 * Math.random()), 1);
    }
    return e + n.join("");
}

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

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

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

function sendData(e) {
    return new Promise(function(n, t) {
        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, n) {
                return e.clientTimestamp - n.clientTimestamp;
            }), loggerInfo(i), loggerReqeust({
                itemArray: i,
                success: function success(e) {
                    for (var t = 0; t < o.length; t++) {
                        var i = o[t], r = options.currentDir + i;
                        try {
                            fileManager.unlinkSync(r);
                        } catch (e) {
                            fileManager.unlink({
                                filePath: r
                            });
                        }
                    }
                    n(e);
                },
                fail: function fail() {
                    if (o.length >= 200) for (var e = 0; e < o.length; e++) {
                        var n = o[e], i = options.currentDir + n;
                        fileManager.unlinkSync(i);
                    }
                    t("send error");
                }
            });
        } else t("no files");
    });
}

var isDoing = !1;

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

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

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