//#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 $owlService:services/org/OrgUtil.jsx

;(function () {

    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 parentId = getCellValue(cells, jTitleIndex, "上级ID");
                var parentName = getCellValue(cells, jTitleIndex, "上级名称");
                var orgTypeName = getCellValue(cells, jTitleIndex, "组织类型");
                var merTypeName = getCellValue(cells, jTitleIndex, "商家类型");
                var name = getCellValue(cells, jTitleIndex, "商家名称");
                var name_en = getCellValue(cells, jTitleIndex, "英文名称");
                var regionName = getCellValue(cells, jTitleIndex, "所在地区");
                var contact = getCellValue(cells, jTitleIndex, "联系人");
                var mobile = getCellValue(cells, jTitleIndex, "联系手机");
                var phone = getCellValue(cells, jTitleIndex, "座机");
                var email = getCellValue(cells, jTitleIndex, "邮箱");
                var storeAddress = getCellValue(cells, jTitleIndex, "店铺地址", "门店地址");
                var address = getCellValue(cells, jTitleIndex, "退货地址");
                var businessTime = getCellValue(cells, jTitleIndex, "开业时间");
                var openTime = getCellValue(cells, jTitleIndex, "营业时间");
                var shopAddress = getCellValue(cells, jTitleIndex, "店铺网址");
                var siteId = getCellValue(cells, jTitleIndex, "站点Id");
                var homePageId = getCellValue(cells, jTitleIndex, "移动端首页Id");
                var pcHomePageId = getCellValue(cells, jTitleIndex, "PC端首页Id");
                var kefuUrl = getCellValue(cells, jTitleIndex, "客服链接");
                var memo = getCellValue(cells, jTitleIndex, "备注");
                var deliveryMemo = getCellValue(cells, jTitleIndex, "配送备注");
                var deliveryModeName = getCellValue(cells, jTitleIndex, "配送方式");
                var moduleIds = getCellValue(cells, jTitleIndex, "权限组织类型ID");
                var deliveryPriceTemplates = getCellValue(cells, jTitleIndex, "默认运费模板ID");
                var platformCategories = getCellValue(cells, jTitleIndex, "经营范围");
                var tag = getCellValue(cells, jTitleIndex, "商家标签");

                if (!parentId) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的上级ID为空");
                    continue;
                }
                if (!orgTypeName) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的组织类型为空");
                    continue;
                }
                if (orgTypeName == "商家" && !merTypeName) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的商家类型为空");
                    continue;
                }
                if (!name) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：关键的商家名称为空");
                    continue;
                }
                var jParentOrg = owl_orgsService.get(parentId);
                if (!jParentOrg) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：ID为【" + parentId + "】的商家或组织机构不存在");
                    continue;
                }

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

                var orgType = getOrgTypeName(orgTypeName);
                if (!orgType) {
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + "校验未通过，原因是：组织类型【" + orgTypeName + "】不存在");
                    totalFailed++;
                    continue;
                }
                var merType = "";
                if (merTypeName) {
                    merType = getMerTypeName(merTypeName);
                    if (!merType) {
                        logMsg = appendLog(logMsg, "第[" + j + "]行 " + "校验未通过，原因是：商家类型【" + merTypeName + "】不存在");
                        totalFailed++;
                        continue;
                    }
                }

                var jOrg = getOrgByName(name);
                if (jOrg) {
                    logMsg = appendLog(logMsg, "第[" + j + "]行 " + "校验未通过，原因是：相同名称【" + name + "】的商家已经存在，对应的商家ID为【" + jOrg.id + "】");
                    totalFailed++;
                    continue;
                }

                var jRegion = null;
                if (regionName) {
                    jRegion = getRegionByFullPathName(regionName);
                    if (!jRegion) {
                        totalFailed++;
                        logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：地区【" + regionName + "】不存在，正确的格式为【湖北省武汉市汉阳区】");
                        continue;
                    }
                }

                var deliveryMode = "";
                if (deliveryModeName) {
                    deliveryMode = getDeliveryModeName(deliveryModeName);
                    if (!deliveryMode) {
                        logMsg = appendLog(logMsg, "第[" + j + "]行 " + "校验未通过，原因是：配送方式【" + deliveryModeName + "】不合法，格式只能是【快递/自提/快递和自提/同上级】中的一个");
                        totalFailed++;
                        continue;
                    }
                }

                var moduleIdList = [];
                if (moduleIds) {
                    var modules = moduleIds.split(";");
                    for (var m = 0; m < modules.length; m++) {
                        var mid = modules[m];
                        if(!mid) {
                            continue;
                        }
                        var jModule = owl_org_modulesService.get(mid);
                        if (!jModule) {
                            totalFailed++;
                            logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：权限组织类型ID【" + mid + "】不存在");
                            return;
                        }
                        moduleIdList.push({id: jModule.id, name: jModule.name});
                    }
                }

                var delivery_price_template = [];
                if (deliveryPriceTemplates) {
                    var templates = deliveryPriceTemplates.split(";");
                    for (var n = 0; n < templates.length; n++) {
                        var tid = templates[n];
                        if(!tid) {
                            continue;
                        }
                        var jTemplate = owl_delivery_price_templateService.get(tid);
                        if (!jTemplate) {
                            totalFailed++;
                            logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：默认运费模板ID【" + tid + "】不存在");
                            return;
                        }
                        delivery_price_template.push({
                            id: jTemplate.id,
                            name: jTemplate.name,
                            description: jTemplate.description
                        });
                    }
                }

                var platform_category = [];
                if (platformCategories) {
                    var categories = platformCategories.split(";");
                    for (var c = 0; c < categories.length; c++) {
                        var categoryFullName = categories[c];
                        if(!categoryFullName) {
                            continue;
                        }
                        categoryFullName = categoryFullName.replace(/\n/g, "");

                        var jCategory = getPlatformCategoryByFullPathName(categoryFullName);
                        if (!jCategory) {
                            totalFailed++;
                            logMsg = appendLog(logMsg, "第[" + j + "]行 校验未通过，原因是：平台商品分类【" + categoryFullName + "】不存在，正确的格式为【全部商品|进口食品】");
                            return;
                        }
                        platform_category.push({
                            id: jCategory.id,
                            name: jCategory.name,
                            fullPathName: jCategory.fullPathName
                        });
                    }
                }

                var contactInfo = {};
                contactInfo.contact = contact;
                contactInfo.mobile = mobile;
                contactInfo.phone = phone;
                contactInfo.email = email;
                contactInfo.storeAddress = storeAddress;
                contactInfo.address = address;
                contactInfo.businessTime = businessTime;
                contactInfo.openTime = openTime;
                contactInfo.shopAddress = shopAddress;
                contactInfo.siteId = siteId;
                contactInfo.homePageId = homePageId;
                contactInfo.pcHomePageId = pcHomePageId;

                var qiyu_info = {};
                qiyu_info.kefuUrl = kefuUrl;

                jOrg = {};
                jOrg.orgType = orgType;
                jOrg.merType = merType;
                jOrg._orgId = jParentOrg.id;
                jOrg._orgIds = OrgUtil.getSaveOrgIds(jParentOrg.id);
                jOrg.parent_id = jParentOrg.id;
                jOrg.parent_name = jParentOrg.name;
                jOrg.name = name;
                jOrg.name_en = name_en;
                jOrg.contactInfo = contactInfo;
                jOrg.qiyu_info = qiyu_info;
                jOrg.memo = memo;
                jOrg.deliveryMemo = deliveryMemo;
                jOrg.deliveryMode = deliveryMode;
                jOrg.tag = tag;
                if (jRegion) {
                    jOrg.regionId = jRegion.id;
                    jOrg.regionPath = jRegion.region_path;
                }
                if (moduleIdList.length > 0) {
                    jOrg.org_modules = moduleIdList;
                }
                if (delivery_price_template.length > 0) {
                    jOrg.delivery_price_template = delivery_price_template;
                }
                if (platform_category.length > 0) {
                    jOrg.platform_category = platform_category;
                }

                jOrg = owl_orgsService.add(jOrg);
                logMsg = appendLog(logMsg, "第[" + j + "]行 " + "导入成功，新的商家ID=" + jOrg.id);
                totalSuccess++;
            } catch (e) {
                totalFailed++;
                totalCheckFail++;
                logMsg = appendLog(logMsg, "第[" + j + "]行 操作失败，失败原因：" + e);
            }
        }

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

    } catch (e) {
        $.log("\norg_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_batch_importService.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) {
        if(extName) {
            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 setUpdateValue(jProduct, key, updateValue) {
    if (updateValue) {
        jProduct[key] = updateValue;
    }
}

function getRegionByFullPathName(fullPathName) {
    var searchArgs = {
        "region_path": fullPathName
    }
    var searchResult = owl_mall_regionService.search(null, searchArgs, "", 0, 1, null);
    if (searchResult.state == 'ok') {
        var list = searchResult.list;
        if (list.length > 0) {
            return list[0];
        }
    }
    return null;
}

function getPlatformCategoryByFullPathName(fullPathName) {
    var searchArgs = {
        "fullPathName": fullPathName
    }
    var searchResult = owl_mall_categoryService.search(null, searchArgs, "", 0, 1, null);
    if (searchResult.state == 'ok') {
        var list = searchResult.list;
        if (list.length > 0) {
            return list[0];
        }
    }
    return null;
}

function getOrgByName(name) {
    var searchArgs = {
        "name": name
    }
    var searchResult = owl_orgsService.search(null, searchArgs, "", 0, 1, null);
    if (searchResult.state == 'ok') {
        var list = searchResult.list;
        if (list.length > 0) {
            return list[0];
        }
    }
    return null;
}

function getOrgTypeName(orgTypeName) {
    if (orgTypeName == "组织机构") {
        return "org";
    } else if (orgTypeName == "商家") {
        return "merchant";
    }
    return "";
}

function getMerTypeName(merTypeName) {
    if (merTypeName == "普通商家") {
        return "com";
    } else if (merTypeName == "集采商家") {
        return "gp";
    } else if (merTypeName == "跨境直邮") {
        return "crossDirectMail";
    } else if (merTypeName == "跨境保税") {
        return "crossBonded";
    }
    return "";
}

function getDeliveryModeName(deliveryModeName) {
    if (deliveryModeName == "快递") {
        return "0";
    } else if (deliveryModeName == "自提") {
        return "1";
    } else if (deliveryModeName == "快递和自提") {
        return "2";
    } else if (deliveryModeName == "同上级") {
        return "3";
    }
    return "";
}

