//#import Util.js
//#import excel.js
//#import $owl_orgs:services/modelService.jsx
//#import $owl_mall_off:services/modelService.jsx
//#import $owl_product_images:services/modelService.jsx
//#import $owl_product_batch_export_org:services/modelService.jsx
//#import $owl_product_batch_import:services/modelService.jsx
//#import $owl_product_batch_updatecategory:services/modelService.jsx
//#import $owl_product_batch_update_tag:services/modelService.jsx
//#import $owl_sku_batch_update:services/modelService.jsx
//#import $owl_sku_batch_update_special_price:services/modelService.jsx
//#import $owl_org_category:services/modelService.jsx
//#import $owl_p_guarantee:services/modelService.jsx
//#import $owl_p_activity_tag:services/modelService.jsx
//#import $owl_mall_o:services/modelService.jsx
//#import $owl_return_order:services/modelService.jsx
//#import $owl_refund_order:services/modelService.jsx
//#import $owl_mall_order_package:services/modelService.jsx
//#import $owl_batch_add_reason_refundorder:services/modelService.jsx
//#import $owl_order_batch_export_org:services/modelService.jsx
//#import $owl_refundorder_batch_export_org:services/modelService.jsx
//#import $owl_delivery_price_template:services/modelService.jsx
//#import $owl_warehouse:services/modelService.jsx
//#import $owl_discount_ticket_type:services/modelService.jsx
//#import $owl_discount_ticket:services/modelService.jsx
//#import $owl_discount_ticket_type_count:services/modelService.jsx
//#import $owl_discount_ticket_type_give_count:services/modelService.jsx
//#import $owl_discount_ticket_give_log:services/modelService.jsx
//#import $owl_discount_ticket_log:services/modelService.jsx
//#import $owl_org_mobile_api_privilege:services/modelService.jsx
//#import $owl_mall_p:services/modelService.jsx
//#import $owl_mall_sku:services/modelService.jsx
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_mall_delivery_point:services/modelService.jsx
//#import $owl_full_discount:services/modelService.jsx
//#import $owl_full_number_discount:services/modelService.jsx
//#import $owl_page_project:services/modelService.jsx
//#import $owl_page_directory:services/modelService.jsx
//#import $owl_page:services/modelService.jsx
//#import $owl_mall_global_notice:services/modelService.jsx
//#import $owl_org_batch_repair_parentid:services/modelService.jsx
//#import $owlService:services/org/OrgUtil.jsx

;(function () {

    var jBatchImport = owl_org_batch_repair_parentidService.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 productIdList = [];
        var lineNumName = "行";
        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;
        for (var i = 1; i < rows.length; i++) {
            var row = rows[i];
            var cells = row.cells;

            try {
                total++;

                var merchantId = getCellValue(cells, 0);
                var merchantName = getCellValue(cells, 1);
                var oriParentId = getCellValue(cells, 2);
                var oriParentName = getCellValue(cells, 3);
                var newParentId = getCellValue(cells, 4);
                var newParentName = getCellValue(cells, 5);

                if (merchantId.indexOf("owl_orgs_") < 0) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：关键的组织ID【" + merchantId + "】格式不合法");
                    totalFailed++;
                    return;
                }
                if (newParentId.indexOf("owl_orgs_") < 0) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：关键的新父组织ID【" + newParentId + "】格式不合法");
                    totalFailed++;
                    return;
                }

                var jMerchant = owl_orgsService.get(merchantId);
                if (!jMerchant) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：ID为【" + merchantId + "】的组织不存在");
                    totalFailed++;
                    return;
                }
                var jParentOrg = owl_orgsService.get(newParentId);
                if (!jParentOrg) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：ID为【" + newParentId + "】的父组织不存在");
                    totalFailed++;
                    return;
                }
                if (jMerchant.orgType != "org") {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：ID为【" + newParentId + "】机构不属于组织机构类型");
                    totalFailed++;
                    return;
                }
                if (jMerchant.parent_id == jParentOrg.id) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：组织【" + merchantId + "】的所属父组织已经是【" + newParentId + "】，无需调整。");
                    // totalFailed++;
                    // return;
                } else {
                    var parentPathIds = OrgUtil.getSaveOrgIds(jParentOrg.id);
                    $.log("org_batch_repair_parentid.jsx...doRepairOrg...【compare1】...orgId=" + merchantId + "...parentPathIds1=" + JSON.stringify(parentPathIds));
                    var fullPathIds = [];
                    if (parentPathIds) {
                        fullPathIds = fullPathIds.concat(parentPathIds);
                        fullPathIds.push(merchantId);
                    } else {
                        fullPathIds = [merchantId];
                    }
                    $.log("org_batch_repair_parentid.jsx...doRepairOrg...【compare2】...orgId=" + merchantId + "...parentPathIds2=" + JSON.stringify(parentPathIds));
                    $.log("org_batch_repair_parentid.jsx...doRepairOrg...【compare3】...orgId=" + merchantId + "...fullPathIds=" + JSON.stringify(fullPathIds));

                    var parentPathNames = [];
                    var fullPathName = "";

                    if (jParentOrg.parentPathNames) {
                        parentPathNames = jParentOrg.parentPathNames.push(jParentOrg.name);
                    } else {
                        parentPathNames = [jParentOrg.name];
                    }
                    if (jParentOrg.fullPathName) {
                        fullPathName = jParentOrg.fullPathName + jMerchant.name;
                    } else {
                        fullPathName = jMerchant.name;
                    }

                    jMerchant.parent_id = jParentOrg.id;
                    jMerchant.parent_name = jParentOrg.name;
                    jMerchant._orgId = jParentOrg.id;
                    jMerchant._orgIds = parentPathIds;
                    jMerchant.parentPathIds = parentPathIds;
                    jMerchant.parentPathNames = parentPathNames;
                    jMerchant.fullPathIds = fullPathIds;
                    jMerchant.fullPathName = fullPathName;
                    owl_orgsService.update(jMerchant);

                    totalSuccess++;
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "商家调整成功。");
                }

                $.log("org_batch_repair_parentid.jsx...repair...##begin##...orgId=" + merchantId);

                var merchantResult = doRepairMerchant(merchantId);
                logMsg = appendLog(logMsg, "商家=" + merchantResult.totalUpdated);
                logMsg = appendLogInline(logMsg, "商品=" + merchantResult.total_product);
                logMsg = appendLogInline(logMsg, "SKU=" + merchantResult.total_sku);
                logMsg = appendLogInline(logMsg, "特价=" + merchantResult.total_mall_off);
                logMsg = appendLogInline(logMsg, "商品图片组=" + merchantResult.total_product_images);
                logMsg = appendLogInline(logMsg, "商品导出=" + merchantResult.total_product_batch_export_org);
                logMsg = appendLogInline(logMsg, "商品批量导入=" + merchantResult.total_product_batch_import);
                logMsg = appendLogInline(logMsg, "商品批量修改分类=" + merchantResult.total_product_batch_updatecategory);
                logMsg = appendLogInline(logMsg, "批量修改商品标签=" + merchantResult.total_product_batch_update_tag);
                logMsg = appendLogInline(logMsg, "SKU批量修改=" + merchantResult.total_sku_batch_update);
                logMsg = appendLogInline(logMsg, "SKU批量修改特价=" + merchantResult.total_sku_batch_update_special_price);
                logMsg = appendLogInline(logMsg, "店铺分类=" + merchantResult.total_org_category);
                logMsg = appendLogInline(logMsg, "商品保障=" + merchantResult.total_p_guarantee);
                logMsg = appendLogInline(logMsg, "商品活动标签=" + merchantResult.total_p_activity_tag);
                logMsg = appendLogInline(logMsg, "订单=" + merchantResult.total_mall_o);
                logMsg = appendLogInline(logMsg, "退货单=" + merchantResult.total_return_order);
                logMsg = appendLogInline(logMsg, "退款单=" + merchantResult.total_refund_order);
                logMsg = appendLogInline(logMsg, "包裹单=" + merchantResult.total_mall_order_package);
                logMsg = appendLogInline(logMsg, "批量生成其他原因退款单=" + merchantResult.total_batch_add_reason_refundorder);
                logMsg = appendLogInline(logMsg, "订单导出=" + merchantResult.total_order_batch_export_org);
                logMsg = appendLogInline(logMsg, "退款单导出=" + merchantResult.total_refundorder_batch_export_org);
                logMsg = appendLogInline(logMsg, "订单运费模板=" + merchantResult.total_delivery_price_template);
                logMsg = appendLogInline(logMsg, "仓库管理=" + merchantResult.total_warehouse);
                logMsg = appendLogInline(logMsg, "券活动=" + merchantResult.total_discount_ticket_type);
                logMsg = appendLogInline(logMsg, "优惠券=" + merchantResult.total_discount_ticket);
                logMsg = appendLogInline(logMsg, "券活动数量=" + merchantResult.total_discount_ticket_type_count);
                logMsg = appendLogInline(logMsg, "用户领券数量=" + merchantResult.total_discount_ticket_type_give_count);
                logMsg = appendLogInline(logMsg, "领券记录=" + merchantResult.total_discount_ticket_give_log);
                logMsg = appendLogInline(logMsg, "优惠券日志=" + merchantResult.total_discount_ticket_log);
                logMsg = appendLogInline(logMsg, "自提点=" + merchantResult.total_mall_delivery_point);
                logMsg = appendLogInline(logMsg, "满减规则=" + merchantResult.total_full_discount);
                logMsg = appendLogInline(logMsg, "N件N折=" + merchantResult.total_full_number_discount);
                logMsg = appendLogInline(logMsg, "页面数=" + merchantResult.total_page);
                logMsg = appendLogInline(logMsg, "页面目录=" + merchantResult.total_page_directory);
                logMsg = appendLogInline(logMsg, "页面项目=" + merchantResult.total_page_project);
                logMsg = appendLogInline(logMsg, "全局公告=" + merchantResult.total_mall_global_notice);
                logMsg = appendLogInline(logMsg, "API权限=" + merchantResult.total_org_mobile_api_privilege);

                $.log("org_batch_repair_parentid.jsx...repair...##end##...orgId=" + merchantId);
            } catch (e) {
                totalFailed++;
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + " 操作失败，失败原因：" + e);
            }
        }

    } catch (e) {
        $.log("org_batch_repair_parentid....batchUpdate.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_batch_repair_parentidService.update(jBatchImport);
    }

})();

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

function appendLogInline(logInfo, s) {
    if (logInfo) {
        return logInfo + "，" + 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 doRepairMerchant(orgId) {
    var searchArgs = {};
    searchArgs._orgId = orgId;//这里注意不能是_orgIds，否则会出现重复修复的操作
    $.log("org_batch_repair_parentid.jsx...doRepairMerchant...orgId=" + orgId + "....searchArgs=" + JSON.stringify(searchArgs));

    var pageLimit = 500;
    var totalRecords = owl_orgsService.count(null, searchArgs, null);
    var totalPages = (totalRecords + pageLimit - 1) / pageLimit;
    $.log("org_batch_repair_parentid.jsx....orgId=" + orgId + "...totalPages=" + totalPages + "...totalRecords=" + totalRecords);

    if (totalRecords > 10000) {
        var jResult = {};
        jResult.code = "0";
        jResult.msg = "总数超过了10000";
        return jResult;
    }

    var total = 0;
    var totalNull = 0;
    var totalNullParent = 0;
    var totalOk = 0;
    var totalUpdated = 0;
    var totalIdError = 0;

    var total_product = 0;
    var total_sku = 0;
    var total_mall_o = 0;
    var total_return_order = 0;
    var total_refund_order = 0;
    var total_mall_order_package = 0;
    var total_mall_delivery_point = 0;
    var total_full_discount = 0;
    var total_full_number_discount = 0;
    var total_page = 0;
    var total_page_directory = 0;
    var total_page_project = 0;
    var total_mall_global_notice = 0;

    var total_mall_off = 0;
    var total_product_images = 0;
    var total_product_batch_export_org = 0;
    var total_product_batch_import = 0;
    var total_product_batch_updatecategory = 0;
    var total_product_batch_update_tag = 0;
    var total_sku_batch_update = 0;
    var total_sku_batch_update_special_price = 0;
    var total_org_category = 0;
    var total_p_guarantee = 0;
    var total_p_activity_tag = 0;
    var total_batch_add_reason_refundorder = 0;
    var total_order_batch_export_org = 0;
    var total_refundorder_batch_export_org = 0;
    var total_delivery_price_template = 0;
    var total_warehouse = 0;
    var total_discount_ticket_type = 0;
    var total_discount_ticket = 0;
    var total_discount_ticket_type_count = 0;
    var total_discount_ticket_type_give_count = 0;
    var total_discount_ticket_give_log = 0;
    var total_discount_ticket_log = 0;
    var total_org_mobile_api_privilege = 0;

    for (var k = 1; k <= totalPages; k++) {
        var start = (k - 1) * pageLimit;
        $.log("org_batch_repair_parentid.jsx...doRepairMerchant...orgId=" + orgId + "...start=" + start);

        var recordList = searchMerchant(searchArgs, start, pageLimit);
        var size = recordList.length;
        if (size > 0) {
            for (var i = 0; i < size; i++) {
                var jMerchant = recordList[i];
                total++;

                if (jMerchant.id == orgId) {
                    //如果是机构自己，就不要继续了
                    continue;
                }
                if (jMerchant.enableState == "N") {
                    //冻结的商家，暂时先不做修复
                    continue;
                }

                if (jMerchant.id == "owl_orgs__m_3190001_o") {
                    //只先修复这个商家
                    continue;
                }

                jMerchant = owl_orgsService.get(jMerchant.id);
                try {
                    var merchantId = jMerchant.id;
                    if (jMerchant.id.indexOf("owl_orgs_") < 0) {
                        totalIdError++;
                        $.log("org_batch_repair_parentid.jsx...doRepairMerchant...id error.....merchantId=" + jMerchant.id);
                        continue;
                    }

                    var jParentOrg = owl_orgsService.get(jMerchant.parent_id);
                    if (!jParentOrg) {
                        totalNullParent++;
                        $.log("org_batch_repair_parentid.jsx...doRepairMerchant...jParentOrg is null.....merchantId=" + jMerchant.id + "...jMerchant.parent_id=" + jMerchant.parent_id);
                        continue;
                    }

                    var parentPathIds = OrgUtil.getSaveOrgIds(jParentOrg.id);
                    $.log("org_batch_repair_parentid.jsx...doRepairMerchant...【compare1】...merchantId=" + merchantId + "...parentPathIds1=" + JSON.stringify(parentPathIds));
                    var fullPathIds = [];
                    if (parentPathIds) {
                        fullPathIds = fullPathIds.concat(parentPathIds);
                        fullPathIds.push(merchantId);
                    } else {
                        fullPathIds = [merchantId];
                    }
                    $.log("org_batch_repair_parentid.jsx...doRepairMerchant...【compare1】...merchantId=" + merchantId + "...parentPathIds2=" + JSON.stringify(parentPathIds));

                    $.log("org_batch_repair_parentid.jsx...doRepairMerchant...【compare2】...merchantId=" + jMerchant.id + "...fullPathIds=" + JSON.stringify(fullPathIds) + "...jMerchant._orgIds=" + JSON.stringify(jMerchant._orgIds));
                    if (!isCompleteSame(jMerchant._orgIds, fullPathIds)) {
                        var parentPathNames = [];
                        var fullPathName = "";
                        if (jParentOrg.parentPathNames) {
                            parentPathNames = jParentOrg.parentPathNames.push(jParentOrg.name);
                        } else {
                            parentPathNames = [jParentOrg.name];
                        }

                        if (jParentOrg.fullPathName) {
                            fullPathName = jParentOrg.fullPathName + jMerchant.name;
                        } else {
                            fullPathName = jMerchant.name;
                        }

                        jMerchant.parent_id = jParentOrg.id;
                        jMerchant.parent_name = jParentOrg.name;
                        jMerchant._orgId = jParentOrg.id;
                        jMerchant._orgIds = fullPathIds;
                        jMerchant.parentPathIds = parentPathIds;
                        jMerchant.parentPathNames = parentPathNames;
                        jMerchant.fullPathIds = fullPathIds;
                        jMerchant.fullPathName = fullPathName;
                        owl_orgsService.update(jMerchant);
                        totalUpdated++;
                        $.log("org_batch_repair_parentid.jsx...doRepairMerchant...merchant repaired...merchantId=" + jMerchant.id);
                    } else {
                        totalOk++;
                        $.log("org_batch_repair_parentid.jsx...doRepairMerchant...is ok.....merchantId=" + jMerchant.id);
                    }


                    $.log("org_batch_repair_parentid.jsx...begin...orgId=" + orgId + "...merchantId=" + merchantId + "...orgIds=" + JSON.stringify(jMerchant.fullPathIds));
                    //修复商品和sku
                    var productResult = doRepairProduct(jMerchant.id, jMerchant.fullPathIds);
                    $.log("org_batch_repair_parentid.jsx...doRepairProduct...orgId=" + jMerchant.id + "...productResult=" + JSON.stringify(productResult));
                    total_product += productResult.totalUpdated;
                    total_sku += productResult.totalSkuRepaired;

                    //修复特价
                    var mall_offResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_offService, "mall_off");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=mall_off...orgId=" + jMerchant.id + "...mall_offResult=" + JSON.stringify(mall_offResult));
                    total_mall_off += mall_offResult.totalUpdated;

                    //修复商品图片组
                    var product_imagesResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_product_imagesService, "product_images");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=product_images...orgId=" + jMerchant.id + "...product_imagesResult=" + JSON.stringify(product_imagesResult));
                    total_product_images += product_imagesResult.totalUpdated;

                    //修复商品导出
                    var product_batch_export_orgResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_product_batch_export_orgService, "product_batch_export_org");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=product_batch_export_org...orgId=" + jMerchant.id + "...product_batch_export_orgResult=" + JSON.stringify(product_batch_export_orgResult));
                    total_product_batch_export_org += product_batch_export_orgResult.totalUpdated;

                    //商品批量导入
                    var product_batch_importResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_product_batch_importService, "product_batch_import");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=product_batch_import...orgId=" + jMerchant.id + "...product_batch_importResult=" + JSON.stringify(product_batch_importResult));
                    total_product_batch_import += product_batch_importResult.totalUpdated;

                    //商品批量修改分类
                    var product_batch_updatecategoryResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_product_batch_updatecategoryService, "product_batch_updatecategory");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=product_batch_updatecategory...orgId=" + jMerchant.id + "...product_batch_updatecategoryResult=" + JSON.stringify(product_batch_updatecategoryResult));
                    total_product_batch_updatecategory += product_batch_updatecategoryResult.totalUpdated;

                    //批量修改商品标签
                    var product_batch_update_tagResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_product_batch_update_tagService, "product_batch_update_tag");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=product_batch_update_tag...orgId=" + jMerchant.id + "...product_batch_update_tagResult=" + JSON.stringify(product_batch_update_tagResult));
                    total_product_batch_update_tag += product_batch_update_tagResult.totalUpdated;

                    //SKU批量修改
                    var sku_batch_updateResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_sku_batch_updateService, "sku_batch_update");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=sku_batch_update...orgId=" + jMerchant.id + "...sku_batch_updateResult=" + JSON.stringify(sku_batch_updateResult));
                    total_sku_batch_update += sku_batch_updateResult.totalUpdated;

                    //SKU批量修改特价
                    var sku_batch_update_special_priceResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_sku_batch_update_special_priceService, "sku_batch_update_special_price");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=sku_batch_update_special_price...orgId=" + jMerchant.id + "...sku_batch_update_special_priceResult=" + JSON.stringify(sku_batch_update_special_priceResult));
                    total_sku_batch_update_special_price += sku_batch_update_special_priceResult.totalUpdated;

                    //店铺分类
                    var org_categoryResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_org_categoryService, "org_category");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=org_category...orgId=" + jMerchant.id + "...org_categoryResult=" + JSON.stringify(org_categoryResult));
                    total_org_category += org_categoryResult.totalUpdated;

                    //商品保障
                    var p_guaranteeResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_p_guaranteeService, "p_guarantee");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=p_guarantee...orgId=" + jMerchant.id + "...p_guaranteeResult=" + JSON.stringify(p_guaranteeResult));
                    total_p_guarantee += p_guaranteeResult.totalUpdated;

                    //商品活动标签
                    var p_activity_tagResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_p_activity_tagService, "p_activity_tag");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=p_activity_tag...orgId=" + jMerchant.id + "...p_activity_tagResult=" + JSON.stringify(p_activity_tagResult));
                    total_p_activity_tag += p_activity_tagResult.totalUpdated;

                    //修复订单
                    var orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_oService, "mall_o");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=mall_o...orgId=" + jMerchant.id + "...orderResult=" + JSON.stringify(orderResult));
                    total_mall_o += orderResult.totalUpdated;

                    //修复退货单
                    var return_orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_return_orderService, "return_order");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=return_order...orgId=" + jMerchant.id + "...return_orderResult=" + JSON.stringify(return_orderResult));
                    total_return_order += return_orderResult.totalUpdated;

                    //修复退款单
                    var refund_orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_refund_orderService, "refund_order");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=refund_order...orgId=" + jMerchant.id + "...refund_orderResult=" + JSON.stringify(refund_orderResult));
                    total_refund_order += refund_orderResult.totalUpdated;

                    //修复包裹单
                    var mall_order_packageResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_order_packageService, "mall_order_package");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=mall_order_package...orgId=" + jMerchant.id + "...mall_order_packageResult=" + JSON.stringify(mall_order_packageResult));
                    total_mall_order_package += mall_order_packageResult.totalUpdated;

                    //批量生成其他原因退款单
                    var batch_add_reason_refundorderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_batch_add_reason_refundorderService, "batch_add_reason_refundorder");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=batch_add_reason_refundorder...orgId=" + jMerchant.id + "...batch_add_reason_refundorderResult=" + JSON.stringify(batch_add_reason_refundorderResult));
                    total_batch_add_reason_refundorder += batch_add_reason_refundorderResult.totalUpdated;

                    //订单导出
                    var order_batch_export_orgResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_order_batch_export_orgService, "order_batch_export_org");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=order_batch_export_org...orgId=" + jMerchant.id + "...order_batch_export_orgResult=" + JSON.stringify(order_batch_export_orgResult));
                    total_order_batch_export_org += order_batch_export_orgResult.totalUpdated;

                    //退款单导出
                    var refundorder_batch_export_orgResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_refundorder_batch_export_orgService, "refundorder_batch_export_org");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=refundorder_batch_export_org...orgId=" + jMerchant.id + "...refundorder_batch_export_orgResult=" + JSON.stringify(refundorder_batch_export_orgResult));
                    total_refundorder_batch_export_org += refundorder_batch_export_orgResult.totalUpdated;

                    //订单运费模板
                    var delivery_price_templateResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_delivery_price_templateService, "delivery_price_template");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=delivery_price_template...orgId=" + jMerchant.id + "...delivery_price_templateResult=" + JSON.stringify(delivery_price_templateResult));
                    total_delivery_price_template += delivery_price_templateResult.totalUpdated;

                    //仓库管理
                    var warehouseResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_warehouseService, "warehouse");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=warehouse...orgId=" + jMerchant.id + "...warehouseResult=" + JSON.stringify(warehouseResult));
                    total_warehouse += warehouseResult.totalUpdated;

                    //券活动
                    var discount_ticket_typeResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticket_typeService, "discount_ticket_type");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket_type...orgId=" + jMerchant.id + "...discount_ticket_typeResult=" + JSON.stringify(discount_ticket_typeResult));
                    total_discount_ticket_type += discount_ticket_typeResult.totalUpdated;

                    //优惠券
                    var discount_ticketResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticketService, "discount_ticket");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket...orgId=" + jMerchant.id + "...discount_ticketResult=" + JSON.stringify(discount_ticketResult));
                    total_discount_ticket += discount_ticketResult.totalUpdated;

                    //券活动数量
                    var discount_ticket_type_countResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticket_type_countService, "discount_ticket_type_count");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket_type_count...orgId=" + jMerchant.id + "...discount_ticket_type_countResult=" + JSON.stringify(discount_ticket_type_countResult));
                    total_discount_ticket_type_count += discount_ticket_type_countResult.totalUpdated;

                    //用户领券数量
                    var discount_ticket_type_give_countResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticket_type_give_countService, "discount_ticket_type_give_count");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket_type_give_count...orgId=" + jMerchant.id + "...discount_ticket_type_give_countResult=" + JSON.stringify(discount_ticket_type_give_countResult));
                    total_discount_ticket_type_give_count += discount_ticket_type_give_countResult.totalUpdated;

                    //领券记录
                    var discount_ticket_give_logResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticket_give_logService, "discount_ticket_give_log");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket_give_log...orgId=" + jMerchant.id + "...discount_ticket_give_logResult=" + JSON.stringify(discount_ticket_give_logResult));
                    total_discount_ticket_give_log += discount_ticket_give_logResult.totalUpdated;

                    //优惠券日志
                    var discount_ticket_logResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_discount_ticket_logService, "discount_ticket_log");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=discount_ticket_log...orgId=" + jMerchant.id + "...discount_ticket_logResult=" + JSON.stringify(discount_ticket_logResult));
                    total_discount_ticket_log += discount_ticket_logResult.totalUpdated;

                    //修复自提点
                    var deliveryPointResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_delivery_pointService, "mall_delivery_point");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=mall_delivery_point...orgId=" + jMerchant.id + "...deliveryPointResult=" + JSON.stringify(deliveryPointResult));
                    total_mall_delivery_point += deliveryPointResult.totalUpdated;

                    //修复满减规则
                    var fullDiscountResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_full_discountService, "full_discount");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=full_discount...orgId=" + jMerchant.id + "...fullDiscountResult=" + JSON.stringify(fullDiscountResult));
                    total_full_discount += fullDiscountResult.totalUpdated;

                    //修复N件N折
                    var full_number_discountResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_full_number_discountService, "full_number_discount");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=full_number_discount...orgId=" + jMerchant.id + "...full_number_discountResult=" + JSON.stringify(full_number_discountResult));
                    total_full_number_discount += full_number_discountResult.totalUpdated;

                    //修复页面
                    var pageResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_pageService, "page");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=page...orgId=" + jMerchant.id + "...pageResult=" + JSON.stringify(pageResult));
                    total_page += pageResult.totalUpdated;

                    //修复页面目录
                    var page_directoryResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_page_directoryService, "page_directory");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=page_directory...orgId=" + jMerchant.id + "...page_directoryResult=" + JSON.stringify(page_directoryResult));
                    total_page_directory += page_directoryResult.totalUpdated;

                    //修复页面项目
                    var page_projectResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_page_projectService, "page_project");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=page_project...orgId=" + jMerchant.id + "...page_projectResult=" + JSON.stringify(page_projectResult));
                    total_page_project += page_projectResult.totalUpdated;

                    //修复全局公告
                    var globalNoticeResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_global_noticeService, "mall_global_notice");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=mall_global_notice...orgId=" + jMerchant.id + "...globalNoticeResult=" + JSON.stringify(globalNoticeResult));
                    total_mall_global_notice += globalNoticeResult.totalUpdated;

                    //API权限
                    var org_mobile_api_privilegeResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_org_mobile_api_privilegeService, "org_mobile_api_privilege");
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=org_mobile_api_privilege...orgId=" + jMerchant.id + "...org_mobile_api_privilegeResult=" + JSON.stringify(org_mobile_api_privilegeResult));
                    total_org_mobile_api_privilege += org_mobile_api_privilegeResult.totalUpdated;

                    $.log("org_batch_repair_parentid.jsx...end...orgId=" + orgId + "...merchantId=" + merchantId + "...orgIds=" + JSON.stringify(jMerchant.fullPathIds));
                } catch (e) {
                    $.log("org_batch_repair_parentid.jsx...doRepairMerchant...orgId=" + orgId + "...error=" + e + "...merchantId=" + jMerchant.id);
                }
            }
        }
    }

    var jResult = {};
    jResult.code = "0";
    jResult.total = total;
    jResult.totalOk = totalOk;
    jResult.totalNull = totalNull;
    jResult.totalNullParent = totalNullParent;
    jResult.totalUpdated = totalUpdated;
    jResult.totalIdError = totalIdError;

    jResult.total_product = total_product;
    jResult.total_sku = total_product;
    jResult.total_mall_o = total_mall_o;
    jResult.total_return_order = total_return_order;
    jResult.total_refund_order = total_refund_order;
    jResult.total_mall_order_package = total_mall_order_package;
    jResult.total_mall_delivery_point = total_mall_delivery_point;
    jResult.total_full_discount = total_full_discount;
    jResult.total_full_number_discount = total_full_number_discount;
    jResult.total_page = total_page;
    jResult.total_page_directory = total_page_directory;
    jResult.total_page_project = total_page_project;
    jResult.total_mall_global_notice = total_mall_global_notice;
    jResult.total_mall_off = total_mall_off;
    jResult.total_product_images = total_product_images;
    jResult.total_product_batch_export_org = total_product_batch_export_org;
    jResult.total_product_batch_import = total_product_batch_import;
    jResult.total_product_batch_updatecategory = total_product_batch_updatecategory;
    jResult.total_product_batch_update_tag = total_product_batch_update_tag;
    jResult.total_sku_batch_update = total_sku_batch_update;
    jResult.total_sku_batch_update_special_price = total_sku_batch_update_special_price;
    jResult.total_org_category = total_org_category;
    jResult.total_p_guarantee = total_p_guarantee;
    jResult.total_p_activity_tag = total_p_activity_tag;
    jResult.total_batch_add_reason_refundorder = total_batch_add_reason_refundorder;
    jResult.total_order_batch_export_org = total_order_batch_export_org;
    jResult.total_refundorder_batch_export_org = total_refundorder_batch_export_org;
    jResult.total_delivery_price_template = total_delivery_price_template;
    jResult.total_warehouse = total_warehouse;
    jResult.total_discount_ticket_type = total_discount_ticket_type;
    jResult.total_discount_ticket = total_discount_ticket;
    jResult.total_discount_ticket_type_count = total_discount_ticket_type_count;
    jResult.total_discount_ticket_type_give_count = total_discount_ticket_type_give_count;
    jResult.total_discount_ticket_give_log = total_discount_ticket_give_log;
    jResult.total_discount_ticket_log = total_discount_ticket_log;
    jResult.total_org_mobile_api_privilege = total_org_mobile_api_privilege;
    return jResult;
}

function doRepairCommon(orgId, orgIds, commonService, typeName) {
    var searchArgs = {};
    searchArgs._orgId = orgId;
    $.log("org_batch_repair_parentid.jsx...doRepairCommon=" + typeName + "...orgId=" + orgId + "....searchArgs=" + JSON.stringify(searchArgs));

    var pageLimit = 500;
    var totalRecords = commonService.count(null, searchArgs, null);
    var totalPages = (totalRecords + pageLimit - 1) / pageLimit;
    $.log("org_batch_repair_parentid.jsx....orgId=" + orgId + "...totalPages=" + totalPages + "...totalRecords=" + totalRecords);

    if (totalRecords > 50000) {
        var jResult = {};
        jResult.code = "0";
        jResult.msg = "总数超过了50000";
        return jResult;
    }

    var total = 0;
    var totalNull = 0;
    var totalUpdated = 0;
    var totalIdError = 0;

    for (var k = 1; k <= totalPages; k++) {
        var start = (k - 1) * pageLimit;
        $.log("org_batch_repair_parentid.jsx...doRepairCommon=" + typeName + "...orgId=" + orgId + "...start=" + start);

        var recordList = searchCommon(commonService, searchArgs, start, pageLimit);
        var size = recordList.length;
        if (size > 0) {
            for (var i = 0; i < size; i++) {
                var jOrder = recordList[i];
                total++;

                try {
                    if (jOrder.id.indexOf("owl_" + typeName + "_") < 0) {
                        totalIdError++;
                        $.log("org_batch_repair_parentid.jsx...doRepairCommon=" + typeName + "...id error.....pid=" + jOrder.id);
                        continue;
                    }

                    var orderOrgIds = jOrder._orgIds;
                    if (!orderOrgIds || !isCompleteSame(orgIds, orderOrgIds)) {
                        jOrder = commonService.get(jOrder.id);
                        if (!jOrder || jOrder.del == "T") {
                            totalNull++;
                            continue;
                        }
                        var orderOrgIds = jOrder._orgIds;
                        if (!orderOrgIds || !isCompleteSame(orgIds, orderOrgIds)) {
                            jOrder._orgIds = orgIds;
                            commonService.update(jOrder);
                            totalUpdated++;
                            $.log("org_batch_repair_parentid.jsx...doRepairCommon=" + typeName + " repaired...id=" + jOrder.id + "...objOrgIds=" + JSON.stringify(orderOrgIds));
                        }
                    }
                } catch (e) {
                    $.log("org_batch_repair_parentid.jsx...doRepairCommon=" + typeName + "...orgId=" + orgId + "...error=" + e + "...pid=" + jOrder.id);
                }
            }
        }
    }

    var jResult = {};
    jResult.code = "0";
    jResult.total = total;
    jResult.totalNull = totalNull;
    jResult.totalUpdated = totalUpdated;
    jResult.totalIdError = totalIdError;
    return jResult;
}

function doRepairProduct(orgId, orgIds) {
    var searchArgs = {};
    searchArgs._orgId = orgId;
    $.log("org_batch_repair_parentid.jsx...doRepairProduct...orgId=" + orgId + "....searchArgs=" + JSON.stringify(searchArgs));

    var pageLimit = 500;
    var totalRecords = owl_mall_pService.count(null, searchArgs, null);
    var totalPages = (totalRecords + pageLimit - 1) / pageLimit;
    $.log("org_batch_repair_parentid.jsx....orgId=" + orgId + "...totalPages=" + totalPages + "...totalRecords=" + totalRecords);

    if (totalRecords > 50000) {
        var jResult = {};
        jResult.code = "0";
        jResult.msg = "总数超过了50000";
        return jResult;
    }

    var total = 0;
    var totalNull = 0;
    var totalUpdated = 0;
    var totalIdError = 0;
    var totalSkuRepaired = 0;

    for (var k = 1; k <= totalPages; k++) {
        var start = (k - 1) * pageLimit;
        $.log("org_batch_repair_parentid.jsx...doRepairProduct...orgId=" + orgId + "...start=" + start);

        var recordList = searchProducts(searchArgs, start, pageLimit);
        var size = recordList.length;
        if (size > 0) {
            for (var i = 0; i < size; i++) {
                var jProduct = recordList[i];
                total++;

                try {
                    if (jProduct.id.indexOf("owl_mall_p_") < 0) {
                        totalIdError++;
                        $.log("org_batch_repair_parentid.jsx...doRepairProduct...id error.....pid=" + jProduct.id);
                        continue;
                    }

                    var productOrgIds = jProduct._orgIds;
                    if (!productOrgIds || !isCompleteSame(orgIds, productOrgIds)) {
                        jProduct = owl_mall_pService.get(jProduct.id);
                        if (!jProduct || jProduct.del == "T") {
                            totalNull++;
                            continue;
                        }
                        var productOrgIds = jProduct._orgIds;
                        if (!productOrgIds || !isCompleteSame(orgIds, productOrgIds)) {
                            jProduct._orgIds = orgIds;
                            owl_mall_pService.update(jProduct);
                            totalUpdated++;
                            $.log("org_batch_repair_parentid.jsx...doRepairProduct...product repaired...pid=" + jProduct.id + "...productOrgIds=" + JSON.stringify(productOrgIds));
                        }
                    }

                    var skuRepaired = repairSkuList(orgIds, jProduct);
                    totalSkuRepaired += skuRepaired;
                } catch (e) {
                    $.log("org_batch_repair_parentid.jsx...doRepairProduct...orgId=" + orgId + "...error=" + e + "...pid=" + jProduct.id);
                }
            }
        }
    }

    var jResult = {};
    jResult.code = "0";
    jResult.total = total;
    jResult.totalNull = totalNull;
    jResult.totalUpdated = totalUpdated;
    jResult.totalIdError = totalIdError;
    jResult.totalSkuRepaired = totalSkuRepaired;
    return jResult;
}

function searchCommon(commonService, searchArgs, from, pageSize) {
    var sr = commonService.search(null, searchArgs, null, from, pageSize, [{"owl_createTime": {order: "desc"}}]);
    if (sr.state == 'ok') {
        return sr.list;
    }
    return [];
}

function searchProducts(searchArgs, from, pageSize) {
    var sr = owl_mall_pService.search(null, searchArgs, null, from, pageSize, [{"owl_createTime": {order: "desc"}}]);
    if (sr.state == 'ok') {
        return sr.list;
    }
    return [];
}

function searchMerchant(searchArgs, from, pageSize) {
    var sr = owl_orgsService.search(null, searchArgs, null, from, pageSize, [{"owl_createTime": {order: "desc"}}]);
    if (sr.state == 'ok') {
        return sr.list;
    }
    return [];
}

function getSkuList(jProduct) {
    var searchArgs = {
        "product_id": jProduct.id
    }
    var skuResult = owl_mall_skuService.search(null, searchArgs, "", 0, 1000, [{"owl_createTime": {order: "desc"}}]);
    if (skuResult.state == 'ok') {
        return skuResult.list;
    }
    return [];
}

function repairSkuList(orgIds, jProduct) {
    var skuList = getSkuList(jProduct);
    var totalRepaired = 0;
    for (var k = 0; k < skuList.length; k++) {
        var jSku = skuList[k];
        if (jSku.product_id != jProduct.id) {
            continue;
        }
        if (jSku._orgId != jProduct._orgId) {
            continue;
        }

        var skuOrgIds = jSku._orgIds;
        if (skuOrgIds) {
            if (isCompleteSame(orgIds, skuOrgIds)) {
                continue;
            }
        }

        jSku = owl_mall_skuService.get(jSku.id);
        if (!jSku || jSku.del == "T") {
            continue;
        }

        var skuOrgIds = jSku._orgIds;
        if (skuOrgIds) {
            if (isCompleteSame(orgIds, skuOrgIds)) {
                continue;
            }
        }

        if (!getSkuSellPrice(jSku, jProduct)) {
            jSku.publish_state = "0";
        }

        jSku._orgIds = orgIds;
        owl_mall_skuService.update(jSku);
        totalRepaired++;

        $.log("org_batch_repair_parentid.jsx...repairSkuList...sku repaired...pid=" + jProduct.id + "...skuId=" + jSku.id + "...skuOrgIds=" + JSON.stringify(skuOrgIds));
    }
    return totalRepaired;
}

function getSkuSellPrice(jSku, jProduct) {
    if (jSku) {
        if (jSku.price_info && jSku.price_info.sell_price) {
            return jSku.price_info.sell_price;
        }
    }
    if (jProduct) {
        if (jProduct && jProduct.price_info && jProduct.price_info.sell_price) {
            return jProduct.price_info.sell_price;
        }
    }
    return "";
}

function isCompleteSame(list1, list2) {
    list1 = toNewList(list1);
    list2 = toNewList(list2);
    if (list1.length != list2.length) {
        return false;
    }

    for (var i = 0; i < list1.length; i++) {
        if (!isExist(list2, list1[i])) {
            return false;
        }
    }
    for (var i = 0; i < list2.length; i++) {
        if (!isExist(list1, list2[i])) {
            return false;
        }
    }
    return true;
}

function isExist(list, id) {
    for (var i = 0; i < list.length; i++) {
        if (list[i] == "0") {
            continue;
        }
        if (list[i] == id) {
            return true;
        }
    }
    return false;
}

function toNewList(list) {
    var newList = [];
    for (var i = 0; i < list.length; i++) {
        if (list[i] == "0") {
            continue;
        }
        newList.push(list[i]);
    }
    return newList;
}

