//#import Util.js
//#import excel.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_org_entity:services/modelService.jsx
//#import $owl_org_user:services/modelService.jsx
//#import $owl_orguser_batch_update:services/modelService.jsx
//#import $owlService:services/org/OrgUtil.jsx

;(function () {

    var jBatchImport = owl_orguser_batch_updateService.get(batchId);

    var logMsg = "";
    var total = 0;
    var totalSuccess = 0;
    var totalFailed = 0;
    var beginTime = (new Date()).getTime();
    try {
        var orgId = jBatchImport._orgId;
        logMsg = appendLog(logMsg, "商家ID=" + orgId);
        if (orgId != "0") {
            logMsg = appendLog(logMsg, "操作终止，原因是：该功能只支持在平台后台操作");
            return;
        }

        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 sheet = jData.sheets[0];
        var rows = sheet.rows;
        if (rows.length > 50000) {
            logMsg = appendLog(logMsg, "操作终止，原因是：Excel的行数超过最大50000的限制了，请删除无用的空行");
            return;
        }

        var firstRow = rows[0];
        var firstRowCells = firstRow.cells;
        var maxCell = firstRowCells.length;
        if (maxCell > 100) {
            maxCell = 100;
        }

        var jTitleIndex = {};
        for (var i = 0; i < maxCell; i++) {
            var jCell = firstRowCells[i];
            if (jCell.value) {
                jTitleIndex[jCell.value] = jCell.columnIndex;
            }
        }

        logMsg = appendLog(logMsg, "数据正确性校验开始。");
        var checkResult = checkExcelData(rows, jTitleIndex);
        if (checkResult) {
            logMsg = appendLog(logMsg, checkResult);
            return;
        }
        logMsg = appendLog(logMsg, "数据正确性校验结束。");

        logMsg = appendLog(logMsg, "数据批量导入开始。");
        var orgEntityList = getAllOrgEntityList();

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

                var row = rows[j];
                var cells = row.cells;

                var orgUserId = getCellValue(cells, jTitleIndex, "ID");
                var stateName = getCellValue(cells, jTitleIndex, "状态");
                var orgCode = getCellValue(cells, jTitleIndex, "机构编码", "所属机构编码");
                var orgName = getCellValue(cells, jTitleIndex, "机构名称", "所属机构名称");
                var department = getCellValue(cells, jTitleIndex, "部门名称", "所属部门");
                var userName = getCellValue(cells, jTitleIndex, "姓名");
                var userNo = getCellValue(cells, jTitleIndex, "员工号", "员工编号");
                var mobile = getCellValue(cells, jTitleIndex, "手机号", "移动电话");

                if (!orgUserId) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "行[" + j + "] 关键的ID为空");
                    continue;
                }
                if (orgUserId.indexOf("owl_org_user_") < 0) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "行[" + j + "] ID不合法");
                    continue;
                }
                if (!userName && !userNo && !userNo && !mobile && !orgName && !stateName) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "行[" + j + "] 没有要修改的信息");
                    continue;
                }
                // if (!userName) {
                //     totalFailed++;
                //     logMsg = appendLog(logMsg, "行[" + j + "] 关键的姓名为空");
                //     continue;
                // }
                // if (!userNo) {
                //     totalFailed++;
                //     logMsg = appendLog(logMsg, "行[" + j + "] 关键的员工号为空");
                //     continue;
                // }
                // if (!mobile) {
                //     totalFailed++;
                //     logMsg = appendLog(logMsg, "行[" + j + "] 关键的手机号为空");
                //     continue;
                // }

                // var jOrgUser = getOrgUserByMobile(mobile);
                // if (jOrgUser) {
                //     totalFailed++;
                //     logMsg = appendLog(logMsg, "行[" + j + "] 手机号码【" + mobile + "】对应的员工已经存在");
                //     continue;
                // }

                var state = "";
                if(stateName) {
                    if(stateName == "正常") {
                        state = "0"
                    } else if(stateName == "冻结") {
                        state = "1"
                    } else {
                        totalFailed++;
                        logMsg = appendLog(logMsg, "行[" + j + "] 状态只能是【正常或冻结】");
                        continue;
                    }
                }

                var jOrgUser = owl_org_userService.get(orgUserId);
                if (!jOrgUser) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "行[" + j + "] 员工【" + orgUserId + "】不存在");
                    continue;
                }

                var jTempOrgUser = getOrgUserByUserNo(userNo);
                if (jTempOrgUser && jTempOrgUser.id != orgUserId) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "行[" + j + "] 员工编码【" + userNo + "】对应的员工已经存在");
                    continue;
                }

                var isUpdated = false;
                if (orgName) {
                    var jOrgEntity = getOrgEntityByName(orgEntityList, orgName);
                    if (!jOrgEntity) {
                        totalFailed++;
                        logMsg = appendLog(logMsg, "行[" + j + "] 单位名称【" + orgName + "】对应的中台实体不存在");
                        continue;
                    }
                    if (jOrgUser.org_entity_id != jOrgEntity.id || jOrgUser.branchcode != jOrgEntity.branchcode || jOrgUser.org_entity_name != jOrgEntity.name) {
                        jOrgUser.org_entity_id = jOrgEntity.id;
                        jOrgUser.branchcode = jOrgEntity.branchcode;
                        jOrgUser.org_entity_name = jOrgEntity.name;
                        isUpdated = true;
                    }
                }

                if (department) {
                    if (jOrgUser.department != department) {
                        jOrgUser.department = department;
                        isUpdated = true;
                    }
                }
                if (userName) {
                    if (jOrgUser.user_name != userName) {
                        jOrgUser.user_name = userName;
                        isUpdated = true;
                    }
                }
                if (userNo) {
                    if (jOrgUser.user_no != userNo) {
                        jOrgUser.user_no = userNo;
                        isUpdated = true;
                    }
                }
                if (mobile) {
                    if (jOrgUser.mobile != mobile) {
                        jOrgUser.mobile = mobile;
                        isUpdated = true;
                    }
                }
                if(state) {
                    if (jOrgUser.state != state) {
                        jOrgUser.state = state;
                        isUpdated = true;
                    }
                }

                if (isUpdated) {
                    owl_org_userService.update(jOrgUser);
                    logMsg = appendLog(logMsg, "行[" + j + "] " + "修改成功");
                    totalSuccess++;
                } else {
                    logMsg = appendLog(logMsg, "行[" + j + "] " + "没有做任何修改");
                    totalFailed++;
                }

            } catch (e) {
                totalFailed++;
                totalCheckFail++;
                logMsg = appendLog(logMsg, "行[" + j + "] 操作失败，失败原因：" + e);
            }
        }

        logMsg = appendLog(logMsg, "数据批量导入结束。");

    } catch (e) {
        $.log("orguser_batch_update....batchImport.jsx....error=" + e);
        logMsg = appendLog(logMsg, "操作出现异常，异常信息为：" + e);
    } finally {
        var endTime = (new Date()).getTime();
        var logInfo = "总耗时=" + (endTime - beginTime) + "毫秒";
        logInfo += "。总行数=" + total;
        logInfo += "，共成功修改数量=" + totalSuccess;
        logInfo += "，未修改总数量=" + totalFailed;

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

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

})();

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

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

function checkExcelData(rows, jTitleIndex) {
    var mobileMap = {};
    var userNoMap = {};
    for (var j = 1; j < rows.length; j++) {
        var row = rows[j];
        var cells = row.cells;

        var userNo = getCellValue(cells, jTitleIndex, "员工编号", "系统编号");
        var mobile = getCellValue(cells, jTitleIndex, "移动电话", "手机号");
        if (!userNo || !mobile) {
            continue;
        }

        userNo = userNo + "";
        mobile = mobile + "";
        var mobileFlag = mobileMap[mobile];
        if (mobileFlag) {
            return "行[" + j + "] 校验不通过，原因是：手机号码【" + mobile + "】和第[" + mobileFlag + "]行存在重复";
        }
        var userNoFlag = userNoMap[userNo];
        if (userNoFlag) {
            return "行[" + j + "] 校验不通过，原因是：员工编码【" + userNo + "】和第[" + userNoFlag + "]行存在重复";
        }
        mobileMap[mobile] = j;
        userNoMap[userNo] = j;
    }
    return "";
}

function getOrgUserByMobile(mobile) {
    var searchArgs = {
        "mobile": mobile
    }
    var searchResult = owl_org_userService.search(null, searchArgs, "", 0, 1, null);
    if (searchResult.state == 'ok') {
        var listData = searchResult.list;
        var total = searchResult.total.value;
        if (listData && listData.length > 0) {
            return listData[0];
        }
    }
    return null;
}

function getOrgUserByUserNo(userNo) {
    var searchArgs = {
        "user_no": userNo
    }
    var searchResult = owl_org_userService.search(null, searchArgs, "", 0, 1, null);
    if (searchResult.state == 'ok') {
        var listData = searchResult.list;
        var total = searchResult.total.value;
        if (listData && listData.length > 0) {
            return listData[0];
        }
    }
    return null;
}

function getAllOrgEntityList() {
    var searchArgs = {}
    var searchResult = owl_org_entityService.search(null, searchArgs, "", 0, 1000, null);
    if (searchResult.state == 'ok') {
        var listData = searchResult.list;
        return listData;
    }
    return [];
}

function getOrgEntityByName(orgEntityList, name) {
    for (var i = 0; i < orgEntityList.length; i++) {
        var jEntity = orgEntityList[i];
        if (jEntity.name == name) {
            return jEntity;
        }
    }
    return null;
}