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

function setOpenId(e) {
    options.openId = e, qq.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 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 r = {
        type: 8
    };
    r.pageId = e, r.levelId = n, r.event = t, r.eventParam = o, checkParams(r), addItem(r);
}

function onShareAppMessage(e) {
    qq.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 r = {
            type: 9
        };
        return r.shareId = o, r.shareType = t.shareType, checkParams(r), addItem(r), 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);
}

initBaseInfo(), initConfigInfo(), initListener(), loggerInfo(options), gameStart();

var currentUserId = "";

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

var localUserId = "";

function getLocalUserId() {
    if (localUserId) return localUserId;
    var e = qq.getStorageSync("effendi_userid");
    return e || (e = readUserIdFromFile()) && qq.setStorageSync("effendi_userid", e), 
    e || (e = wxuuid(), qq.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 = qq.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 = qq.getLaunchOptionsSync();
    options.sourceId = t.scene, options.queryParams = t.query, qq.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() {
    qq.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(), 
            qq.setStorageSync("diffTime", options.diffTime)) : options.diffTime = qq.getStorageSync("diffTime");
        },
        fail: function fail(e) {
            options.diffTime = qq.getStorageSync("diffTime");
        }
    });
}

function initListener() {
    try {
        qq.onShow && qq.onShow(function() {
            isSleep = !1, options.pageCount > 0 && sendHeatHeart(2);
        }), qq.onHide && (isSleep = !0, qq.onHide(function() {
            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 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) {
    qq.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 = [], r = [], i = 0; i < e.files.length; i++) {
                try {
                    var a = e.files[i];
                    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 = "", 
                    r.push(d);
                } catch (e) {}
            }
            r.sort(function(e, n) {
                return e.clientTimestamp - n.clientTimestamp;
            }), loggerInfo(r), loggerReqeust({
                itemArray: r,
                success: function success(e) {
                    for (var t = 0; t < o.length; t++) {
                        var r = o[t], i = options.currentDir + r;
                        try {
                            fileManager.unlinkSync(i);
                        } catch (e) {
                            fileManager.unlink({
                                filePath: i
                            });
                        }
                    }
                    n(e);
                },
                fail: function fail() {
                    if (o.length >= 200) for (var e = 0; e < o.length; e++) {
                        var n = o[e], r = options.currentDir + n;
                        fileManager.unlinkSync(r);
                    }
                    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;
        }
    }
}

for (var uploadHandlerArray = [], i = 0; i < 5; i++) {
    uploadHandlerArray[i] = setTimeout(function(e) {
        sendHeatHeart(1), uploadDemo(), clearTimeout(uploadHandlerArray[e]);
    }, 1e3 * (i + 1), i);
}

var timeTask = setInterval(function() {
    isSleep || (sendHeatHeart(1), uploadDemo());
}, 1e4);

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