//#import Util.js
//#import excel.js
//#import $owl_orgs: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_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_update_parentid:services/modelService.jsx
//#import $owlService:services/org/OrgUtil.jsx

;(function () {

    var jBatchImport = owl_org_batch_update_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.parent_id == jParentOrg.id) {
                    logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "操作终止，原因是：组织【" + merchantId + "】的所属父组织已经是【" + newParentId + "】，无需调整");
                    // totalFailed++;
                    // return;
                } else {
                    var parentPathIds = OrgUtil.getSaveOrgIds(jParentOrg.id);
                    $.log("org_batch_update_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_update_parentid.jsx...doRepairOrg...【compare2】...orgId=" + merchantId + "...parentPathIds2=" + JSON.stringify(parentPathIds));
                    $.log("org_batch_update_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_update_parentid.jsx...begin...orgId=" + orgId + "...orgIds=" + JSON.stringify(jMerchant.fullPathIds));
                //修复商品和sku
                var productResult = doRepairProduct(jMerchant.id, jMerchant.fullPathIds);
                $.log("org_batch_update_parentid.jsx...doRepairProduct...orgId=" + jMerchant.id + "...productResult=" + JSON.stringify(productResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复商品数=" + productResult.totalUpdated + "...共修复sku数=" + productResult.totalSkuRepaired);
                //修复订单
                var orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_oService, "mall_o");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=mall_o...orgId=" + jMerchant.id + "...orderResult=" + JSON.stringify(orderResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复订单数=" + orderResult.totalUpdated);
                //修复退货单
                var return_orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_return_orderService, "return_order");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=return_order...orgId=" + jMerchant.id + "...return_orderResult=" + JSON.stringify(return_orderResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复退货单数=" + return_orderResult.totalUpdated);
                //修复退款单
                var refund_orderResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_refund_orderService, "refund_order");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=refund_order...orgId=" + jMerchant.id + "...refund_orderResult=" + JSON.stringify(refund_orderResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复退款单数=" + refund_orderResult.totalUpdated);
                //修复包裹单
                var mall_order_packageResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_order_packageService, "mall_order_package");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=mall_order_package...orgId=" + jMerchant.id + "...mall_order_packageResult=" + JSON.stringify(mall_order_packageResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复包裹单数=" + mall_order_packageResult.totalUpdated);
                //修复自提点
                var deliveryPointResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_delivery_pointService, "mall_delivery_point");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=mall_delivery_point...orgId=" + jMerchant.id + "...deliveryPointResult=" + JSON.stringify(deliveryPointResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复自提点数=" + deliveryPointResult.totalUpdated);
                //修复满减规则
                var fullDiscountResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_full_discountService, "full_discount");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=full_discount...orgId=" + jMerchant.id + "...fullDiscountResult=" + JSON.stringify(fullDiscountResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复满减规则数=" + fullDiscountResult.totalUpdated);
                //修复N件N折
                var full_number_discountResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_full_number_discountService, "full_number_discount");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=full_number_discount...orgId=" + jMerchant.id + "...full_number_discountResult=" + JSON.stringify(full_number_discountResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复N件N折数=" + full_number_discountResult.totalUpdated);
                //修复页面
                var pageResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_pageService, "page");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=page...orgId=" + jMerchant.id + "...pageResult=" + JSON.stringify(pageResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复页面数=" + pageResult.totalUpdated);
                //修复页面目录
                var page_directoryResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_page_directoryService, "page_directory");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=page_directory...orgId=" + jMerchant.id + "...page_directoryResult=" + JSON.stringify(page_directoryResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复页面目录数=" + page_directoryResult.totalUpdated);
                //修复页面项目
                var page_projectResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_page_projectService, "page_project");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=page_project...orgId=" + jMerchant.id + "...page_projectResult=" + JSON.stringify(page_projectResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复页面项目数=" + page_projectResult.totalUpdated);
                //修复全局公告
                var globalNoticeResult = doRepairCommon(jMerchant.id, jMerchant.fullPathIds, owl_mall_global_noticeService, "mall_global_notice");
                $.log("org_batch_update_parentid.jsx...doRepairCommon=mall_global_notice...orgId=" + jMerchant.id + "...globalNoticeResult=" + JSON.stringify(globalNoticeResult));
                logMsg = appendLog(logMsg, "第[" + i + "]" + lineNumName + "共修复全局公告数=" + globalNoticeResult.totalUpdated);

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

    } catch (e) {
        $.log("org_batch_update_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_update_parentidService.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 doRepairCommon(orgId, orgIds, commonService, typeName) {
    var searchArgs = {};
    searchArgs._orgId = orgId;
    $.log("org_batch_update_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_update_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_update_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_update_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_update_parentid.jsx...doRepairCommon=" + typeName + " repaired...id=" + jOrder.id + "...objOrgIds=" + JSON.stringify(orderOrgIds));
                        }
                    }
                } catch (e) {
                    $.log("org_batch_update_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_update_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_update_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_update_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_update_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_update_parentid.jsx...doRepairProduct...product repaired...pid=" + jProduct.id + "...productOrgIds=" + JSON.stringify(productOrgIds));
                        }
                    }

                    var skuRepaired = repairSkuList(orgIds, jProduct);
                    totalSkuRepaired += skuRepaired;
                } catch (e) {
                    $.log("org_batch_update_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 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_update_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;
}

