//#import Util.js
//#import excel.js
//#import $owl_orgs:services/modelService.jsx
//#import $owl_mall_region:services/modelService.jsx
//#import $owl_org_modules:services/modelService.jsx
//#import $owl_delivery_price_template:services/modelService.jsx
//#import $owl_mall_category:services/modelService.jsx
//#import $owl_org_batch_import:services/modelService.jsx
//#import $owl_org_admin_groups:services/modelService.jsx
//#import $owl_org_admin_batch_import:services/modelService.jsx
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_roles:services/modelService.jsx
//#import $owlService:services/org/OrgUtil.jsx

var orgAdminGroupCache = {};
;(function main() {

    var jBatchImport = owl_org_batch_importService.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);

        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;

        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 totalCheckFail = 0;
        for (var j = 1; j < rows.length; j++) {
            try {
                total++;

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

                var orgId = getCellValue(cells, jTitleIndex, "组织Id");
                var orgName = getCellValue(cells, jTitleIndex, "组织名称");
                var groupName = getCellValue(cells, jTitleIndex, "分组名称");
                var mobile = getCellValue(cells, jTitleIndex, "用户手机");
                var loginId = getCellValue(cells, jTitleIndex, "登录Id");
                var roleId = getCellValue(cells, jTitleIndex, "角色Id");
                var roleName = getCellValue(cells, jTitleIndex, "角色名称");

                if (!orgId) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的组织Id为空");
                    continue;
                }
                if (!orgName) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的组织名称为空");
                    continue;
                }
                if (!groupName) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的分组名称为空");
                    continue;
                }
                if (!loginId && !mobile) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：登录Id和手机号不能同时为空");
                    continue;
                }

                if (!roleId) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：角色Id不能为空,cells=" + JSON.stringify(cells) + ",jTitleIndex=" + JSON.stringify(jTitleIndex));
                    continue;
                }

                var role = owl_rolesService.get(roleId);
                if(!role){
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：角色Id为" + roleId + "的角色不存在");
                    continue;
                }
                if(roleName !== role.name){
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：角色Id为" + roleId + "的角色名称为 " + role.name + ", 导入的名称为 " + roleName + " 不一致");
                    continue;
                }

                //检查权限
                var targetOrg = owl_orgsService.get(orgId);
                if (!targetOrg) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：ID为【" + orgId + "】的商家或组织机构不存在");
                    continue;
                }

                if (!OrgUtil.checkPrivilege(targetOrg, jBatchImport._orgId)) {
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + "校验未通过，原因是：当前组织无权在【" + jParentOrg.name + "】下操作绑定员工权限");
                    totalFailed++;
                    continue;
                }


                var admin = null;
                try{
                    admin = getUser(loginId,mobile);
                }
                catch(e){
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + e);
                    totalFailed++;
                    continue;
                }


                //根据名称获得管理员组

                var orgAdminGroup = null;

                try{
                    orgAdminGroup = getOrgAdminGroups(orgId, groupName);
                }
                catch(e){
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + e);
                    totalFailed++;
                    continue;
                }
                if(!orgAdminGroup){
                    orgAdminGroup = {
                        _orgId:orgId,
                        _orgIds:targetOrg._orgIds,
                        name:groupName,
                        staff:[{id:admin.id,realName:admin.realName,mobile:admin.mobile,loginId:admin.loginId}],
                        roles:[{id:roleId,name:roleName}]
                    }
                    orgAdminGroup = owl_org_admin_groupsService.add(orgAdminGroup);
                    var key = orgId+"_" + groupName;
                    orgAdminGroupCache[key] = orgAdminGroup;
                }
                else if(orgAdminGroup){
                    //检查roleId是否和orgAdminGroup的roles中是否存在
                    if(orgAdminGroup.roles){
                        var roles = orgAdminGroup.roles;
                        if(roles.length!==1 || roles[0].id!==roleId){
                            totalFailed++;
                            logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：管理员组的roleId和导入的roleId不一致。");
                            continue;
                        }
                        roles[0].name = roleName;

                    }
                    //检查staff种是否已经存在了对应的用户
                    var staff = orgAdminGroup.staff || [];
                    var found = false;
                    for(var i=0; i<staff.length; i++){
                        if(staff[i].id === admin.id){
                            found = true;

                        }
                    }
                    if(found){
                        totalFailed++;
                        logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：管理员在管理员组[" + orgAdminGroup.name + "]已经存在，管理员信信息如下，loginId:" + loginId + ", mobile:" + mobile);
                        continue;
                    }
                    else{
                        staff.push({id:admin.id,realName:admin.realName,mobile:admin.mobile,loginId:admin.loginId});
                    }
                    orgAdminGroup.staff = staff;
                    owl_org_admin_groupsService.update(orgAdminGroup);
                    orgAdminGroupCache[key] = orgAdminGroup;
                }

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

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

    } catch (e) {
        $.log("\norg_admin_batch_import....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_org_admin_batch_importService.update(jBatchImport);
    }
})();


function getOrgAdminGroups(orgId,name){

    var key = orgId+"_"+name;
    var jOrgAdminGroup = orgAdminGroupCache[key];
    if(jOrgAdminGroup){
        return owl_org_admin_groupsService.get(jOrgAdminGroup.id);
    }

    var searchArgs = {
         _orgId:orgId,
         name:name
     }
    var dataSource = null;
    var mfilters = null;
    var keyword = null;
    var pageSize = 1000;
    var from = 0;

    var sort = {
       owl_modifyTime:{order:"desc"}
    }



    var sr = owl_org_admin_groupsService.search(mfilters, searchArgs, keyword,from, pageSize, sort, dataSource );
    if(sr.state === 'ok'){
      if(sr.list.length>1){
          throw "管理员组名称重复,有"+sr.list.length+"个管理员组有相同的名字,请检查。组织Id："+orgId+"，名称："+name;
      }
      if(sr.list.length==1){
          orgAdminGroupCache[key] = sr.list[0];
          return owl_org_admin_groupsService.get(sr.list[0].id);
      }
      return null;
    }
    throw "错误：查询管理员组失败。组织Id："+orgId+"，名称："+name;
}

function getUser(loginId,mobile){
    var admin = owl_mall_uService.getUniqueObj('loginId',loginId);
    if(admin && mobile && admin.mobile!==mobile){
       throw "错误：手机号不一致。登录Id："+loginId+"，手机号："+mobile;
    }
    if(admin){
        return admin;
    }

    admin = owl_mall_uService.getUniqueObj('mobile',mobile);
    if(admin && loginId && admin.loginId!==loginId){
       throw "错误：手机号不一致。登录Id："+loginId+"，手机号："+mobile;
    }
    return admin;




}

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) {
        return "";
    }
    for (var i = 0; i < cells.length; i++) {
        var jCell = cells[i];
        if (jCell.columnIndex == index) {
            if (jCell.value) {
                return jCell.value;
            }
        }
    }
    return "";
}





