//#import Util.js
//#import excel.js
//#import $owl_orgs:services/modelService.jsx
//#import $owl_mall_category:services/modelService.jsx
//#import $owl_mall_region:services/modelService.jsx
//#import $owl_org_batch_update:services/modelService.jsx
//#import $owl_delivery_price_template:services/modelService.jsx
//#import $owl_org_modules:services/modelService.jsx
//#import $owlService:services/common/ImageUtil.jsx

;(function () {

    var jBatchImport = owl_org_batch_updateService.get(batchId);

    var logMsg = "";
    var total = 0;
    var totalSuccess = 0;
    var totalFailed = 0;
    var beginTime = (new Date()).getTime();
    try {
        var orgId = jBatchImport._orgId;
        logMsg = appendLog(logMsg, "商家ID=" + orgId);

        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 merchantId = getCellValue(cells, jTitleIndex, "商家ID");
                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 moduleIds = getCellValue(cells, jTitleIndex, "权限组织类型ID");
                var deliveryPriceTemplates = getCellValue(cells, jTitleIndex, "默认运费模板ID");
                var platformCategories = getCellValue(cells, jTitleIndex, "经营范围");
                var tag = getCellValue(cells, jTitleIndex, "商家标签");
                var orgCode = getCellValue(cells, jTitleIndex, "统一组织机构代码");
                var registrationNumber = getCellValue(cells, jTitleIndex, "工商登记号");
                var registrationAddress = getCellValue(cells, jTitleIndex, "注册地址");
                var businessRange = getCellValue(cells, jTitleIndex, "营业范围");
                var showLicImage = getCellValue(cells, jTitleIndex, "营业执照");
                var licBeginDate = getCellValue(cells, jTitleIndex, "营业执照有效期开始时间");
                var licEndDate = getCellValue(cells, jTitleIndex, "营业执照有效期结束时间");

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

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

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

                var qiyu_info = jOrg.qiyu_info;
                if(!qiyu_info) {
                    qiyu_info = {};
                    jOrg.qiyu_info = qiyu_info;
                }

                var isUpdated = false;
                if (name) {
                    if (jOrg.name != name) {
                        jOrg.name = name;
                        isUpdated = true;
                    }
                }
                if (name_en) {
                    if (jOrg.name_en != name_en) {
                        jOrg.name_en = name_en;
                        isUpdated = true;
                    }
                }
                if (contact) {
                    if (contactInfo.contact != contact) {
                        contactInfo.contact = contact;
                        isUpdated = true;
                    }
                }
                if (mobile) {
                    if (contactInfo.mobile != mobile) {
                        contactInfo.mobile = mobile;
                        isUpdated = true;
                    }
                }
                if (phone) {
                    if (contactInfo.phone != phone) {
                        contactInfo.phone = phone;
                        isUpdated = true;
                    }
                }
                if (email) {
                    if (contactInfo.email != email) {
                        contactInfo.email = email;
                        isUpdated = true;
                    }
                }
                if (storeAddress) {
                    if (contactInfo.storeAddress != storeAddress) {
                        contactInfo.storeAddress = storeAddress;
                        isUpdated = true;
                    }
                }
                if (address) {
                    if (contactInfo.address != address) {
                        contactInfo.address = address;
                        isUpdated = true;
                    }
                }
                if (businessTime) {
                    if (contactInfo.businessTime != businessTime) {
                        contactInfo.businessTime = businessTime;
                        isUpdated = true;
                    }
                }
                if (openTime) {
                    if (contactInfo.openTime != openTime) {
                        contactInfo.openTime = openTime;
                        isUpdated = true;
                    }
                }
                if (shopAddress) {
                    if (contactInfo.shopAddress != shopAddress) {
                        contactInfo.shopAddress = shopAddress;
                        isUpdated = true;
                    }
                }
                if (siteId) {
                    if (contactInfo.siteId != siteId) {
                        contactInfo.siteId = siteId;
                        isUpdated = true;
                    }
                }
                if (homePageId) {
                    if (contactInfo.homePageId != homePageId) {
                        contactInfo.homePageId = homePageId;
                        isUpdated = true;
                    }
                }
                if (pcHomePageId) {
                    if (contactInfo.pcHomePageId != pcHomePageId) {
                        contactInfo.pcHomePageId = pcHomePageId;
                        isUpdated = true;
                    }
                }
                if (kefuUrl) {
                    if (qiyu_info.kefuUrl != kefuUrl) {
                        qiyu_info.kefuUrl = kefuUrl;
                        isUpdated = true;
                    }
                }
                if (memo) {
                    if (jOrg.memo != memo) {
                        jOrg.memo = memo;
                        isUpdated = true;
                    }
                }
                if (deliveryMemo) {
                    if (jOrg.deliveryMemo != deliveryMemo) {
                        jOrg.deliveryMemo = deliveryMemo;
                        isUpdated = true;
                    }
                }
                if (tag) {
                    if (jOrg.tag != tag) {
                        jOrg.tag = tag;
                        isUpdated = true;
                    }
                }
                if (jRegion) {
                    jOrg.regionId = jRegion.id;
                    jOrg.regionPath = jRegion.region_path;
                    isUpdated = true;
                }
                if (moduleIdList.length > 0) {
                    jOrg.org_modules = moduleIdList;
                    isUpdated = true;
                }
                if (delivery_price_template.length > 0) {
                    jOrg.delivery_price_template = delivery_price_template;
                    isUpdated = true;
                }
                if (platform_category.length > 0) {
                    jOrg.platform_category = platform_category;
                    isUpdated = true;
                }
                if (orgCode) {
                    jOrg.orgCode = orgCode;
                    isUpdated = true;
                }
                if (registrationNumber) {
                    jOrg.registrationNumber = registrationNumber;
                    isUpdated = true;
                }
                if (registrationAddress) {
                    jOrg.registrationAddress = registrationAddress;
                    isUpdated = true;
                }
                if (businessRange) {
                    jOrg.businessRange = businessRange;
                    isUpdated = true;
                }
                if (showLicImage) {
                    var images = [];
                    images.push(ImageUtil.getIcon(showLicImage));
                    jOrg.licImage = images;
                    jOrg.showLicImage = images;
                    isUpdated = true;
                }
                if (licBeginDate) {
                    jOrg.licBeginDate = licBeginDate;
                    isUpdated = true;
                }
                if (licEndDate) {
                    jOrg.licEndDate = licEndDate;
                    isUpdated = true;
                }
                if (!isUpdated) {
                    totalFailed++;
                    logMsg = appendLog(logMsg, "第[" + j + "]行 操作终止，原因是：没有做任何修改");
                    continue;
                }

                owl_orgsService.update(jOrg);
                logMsg = appendLog(logMsg, "第[" + j + "]行 " + "修改成功。");
                totalSuccess++;
            } catch (e) {
                totalFailed++;
                totalCheckFail++;
                logMsg = appendLog(logMsg, "第[" + j + "]行 操作失败，失败原因：" + e);
            }
        }

        logMsg = appendLog(logMsg, "数据批量修改结束。");

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

})();

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

function getCellValue(cells, jTitleIndex, name, extName) {
    var index = jTitleIndex[name];
    if (!index && index != 0) {
        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 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 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;
}

