//#import Util.js
//#import DateUtil.js
//#import excel.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_mall_u_category:services/modelService.jsx
//#import $owl_user_batch_update_category:services/modelService.jsx

;(function () {

    var jBatchImport = owl_user_batch_update_categoryService.get(batchId);

    var logMsg = "";
    var total = 0;
    var totalAdd = 0;
    var totalRemove = 0;
    var totalSkip = 0;
    var totalError = 0;
    var beginTime = (new Date()).getTime();
    try {

        var jFile = jBatchImport.file;
        if (!jFile || jFile.length == 0 || !jFile[0].url) {
            logMsg = appendLog(logMsg, "缺少Excel文件");
            return;
        }
        var filePath = jFile[0].url;

        var jData = Excel.parse(filePath);
        if (!jData) {
            logMsg = appendLog(logMsg, "读取Excel文件失败");
            return;
        }
        if (!jData.sheets || jData.sheets.length == 0) {
            logMsg = appendLog(logMsg, "Excel中的sheet为空");
            return;
        }

        var actionType = jBatchImport.actionType;
        var toUserGroupId = jBatchImport.categoryId;

        var jUserCategory = owl_mall_u_categoryService.get(toUserGroupId);
        if (!jUserCategory) {
            logMsg = appendLog(logMsg, "目标会员组不存在");
            return;
        }

        var sheet = jData.sheets[0];
        var rows = sheet.rows;

        for (var j = 1; j < rows.length; j++) {
            try {
                total++;

                var row = rows[j];
                var cells = row.cells;
                var uid = getCellValue(cells, 0);
                var groupBeginTime = getCellValue(cells, 1);
                var groupEndTime = getCellValue(cells, 2);

                if (uid == "") {
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + "导入终止，原因是：关键的userId为空");
                    totalSkip++;
                    continue;
                }

                var jUser = owl_mall_uService.get(uid);
                if (!jUser) {
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + "导入终止，原因是：ID为【" + uid + "】的用户不存在");
                    totalSkip++;
                    continue;
                }
                uid = jUser.id;

                if (actionType == "add") {
                    var longGroupBeginTime = "";
                    if (groupBeginTime) {
                        longGroupBeginTime = DateUtil.getLongTime(groupBeginTime)
                    }
                    var longGroupEndTime = "";
                    if (groupEndTime) {
                        longGroupEndTime = DateUtil.getLongTime(groupEndTime);
                    }

                    //todo:判断用户是否已经在这个组里面

                    addUserToGroup(jUser, jUserCategory, longGroupBeginTime, longGroupEndTime);
                    owl_mall_uService.update(jUser);
                    totalAdd++;

                    logInfo = "第" + (j + 1) + "行 添加到会员组【" + toUserGroupId + "】成功";
                    logMsg = appendLog(logMsg, logInfo);
                } else if (actionType == "remove") {
                    var isUpdated = removeUserGroup(jUser, jUserCategory);
                    if (isUpdated) {
                        owl_mall_uService.update(jUser);
                    }
                    totalRemove++;

                    logInfo = "第" + (j + 1) + "行 从目标会员组【" + toUserGroupId + "】中删除成功";
                    logMsg = appendLog(logMsg, logInfo);
                } else {
                    totalSkip++;
                }

            } catch (e) {
                totalError++;
                logMsg = appendLog(logMsg, "第[" + j + "]行 导入失败，失败原因：" + e);
            }
        }

    } catch (e) {
        $.log("\nuser_batch_update_category....doUpdateUserTask.jsx....error=" + e);
        logMsg = appendLog(logMsg, "导入出现异常，异常信息为：" + e);
    } finally {
        var endTime = (new Date()).getTime();
        var logInfo = "总耗时=" + (endTime - beginTime) + "毫秒";
        logInfo += "。总处理数量=" + total;
        logInfo += "，成功添加到目标会员组总数量=" + totalAdd;
        logInfo += "，从目标会员组中删除总数量=" + totalRemove;
        logInfo += "，忽略跳过总数量=" + totalSkip;
        logInfo += "，修改出现异常总数量=" + totalError;

        logMsg = appendLog(logMsg, "");
        logMsg = appendLog(logMsg, logInfo);

        jBatchImport.msg = logMsg;
        owl_user_batch_update_categoryService.update(jBatchImport);
    }

})();

function appendLog(logInfo, s) {
    if (logInfo) {
        return logInfo += "\n" + s;
    }
    return s;
}

function getCellValue(cells, index) {
    for (var i = 0; i < cells.length; i++) {
        var jCell = cells[i];
        if (jCell.columnIndex == index) {
            if (jCell.value) {
                return jCell.value;
            }
        }
    }
    return "";
}

function addUserToGroup(jUser, jUserCategory, beginTime, endTime) {
    var user_categories = jUser.user_categories;
    if (!user_categories) {
        user_categories = [];
        jUser.user_categories = user_categories;
    }

    var jCategory = {
        "id": jUserCategory.id,
        "name": jUserCategory.name
    };
    if (beginTime) {
        jCategory.beginTime = beginTime;
    }
    if (endTime) {
        jCategory.endTime = endTime;
    }
    user_categories.push(jCategory);
}


function removeUserGroup(jUser, jUserCategory) {
    var user_categories = jUser.user_categories;
    if (user_categories && user_categories.length > 0) {
        var newList = [];
        var isUpdated = false;
        for (var i = 0; i < user_categories.length; i++) {
            var jCat = user_categories[i];
            if (jCat.id == jUserCategory.id) {
                isUpdated = true;
                continue;
            }
            newList.push(jCat);
        }
        if (isUpdated) {
            jUser.user_categories = newList;
            return true;
        }
    }
    return false;
}
