//#import Util.js
//#import excel.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_org_batch_export:services/modelService.jsx
//#import $owl_orgs:services/modelService.jsx
//#import $owlService:services/common/SearchUtil.jsx
//#import DateUtil.js

;(function () {

    var jBatchImport = owl_org_batch_exportService.get(batchId);

    $.log("org_batch_export....batchExport.jsx....begin...jBatchImport=" + JSON.stringify(jBatchImport));
    var logMsg = "";
    var beginTime = (new Date()).getTime();
    try {
        var orgId = jBatchImport._orgId;

        var totalAmount = getTotalCount(jBatchImport);
        if (totalAmount > 10000) {
            logMsg = appendLog(logMsg, "操作终止，原因是：本次商家导出总数量超过10000，请缩小搜索范围分多次导出");
            return;
        }

        var recordList = getMerchantList(jBatchImport);

        var index = 0;
        var titles = [
            {"index": index++, "columnWidth": "22", "field": "parent_id", "title": "上级ID"},
            {"index": index++, "columnWidth": "40", "field": "fullPathName", "title": "上级名称"},
            {"index": index++, "columnWidth": "22", "field": "orgType", "title": "组织类型"},
            {"index": index++, "columnWidth": "22", "field": "merType", "title": "商家类型"},
            {"index": index++, "columnWidth": "22", "field": "id", "title": "商家ID"},
            {"index": index++, "columnWidth": "22", "field": "name", "title": "商家名称"},
            {"index": index++, "columnWidth": "22", "field": "name_en", "title": "英文名称"},
            {"index": index++, "columnWidth": "22", "field": "regionPath", "title": "所在地区"},
            {"index": index++, "columnWidth": "22", "field": "contact", "title": "联系人"},
            {"index": index++, "columnWidth": "22", "field": "mobile", "title": "联系手机"},
            {"index": index++, "columnWidth": "22", "field": "phone", "title": "座机"},
            {"index": index++, "columnWidth": "22", "field": "email", "title": "邮箱"},
            {"index": index++, "columnWidth": "22", "field": "address", "title": "店铺地址"},
            {"index": index++, "columnWidth": "22", "field": "businessTime", "title": "开业时间"},
            {"index": index++, "columnWidth": "22", "field": "openTime", "title": "营业时间"},
            {"index": index++, "columnWidth": "40", "field": "shopAddress", "title": "店铺网址"},
            {"index": index++, "columnWidth": "22", "field": "siteId", "title": "站点Id"},
            {"index": index++, "columnWidth": "40", "field": "homePageId", "title": "移动端首页Id"},
            {"index": index++, "columnWidth": "40", "field": "pcHomePageId", "title": "PC端首页Id"},
            {"index": index++, "columnWidth": "40", "field": "kefuUrl", "title": "客服链接"},
            {"index": index++, "columnWidth": "40", "field": "memo", "title": "备注"},
            {"index": index++, "columnWidth": "40", "field": "deliveryMemo", "title": "配送备注"},
            {"index": index++, "columnWidth": "22", "field": "deliveryMode", "title": "配送方式"},
            {"index": index++, "columnWidth": "60", "field": "moduleIds", "title": "权限组织类型ID"},
            {"index": index++, "columnWidth": "60", "field": "deliveryPriceTemplates", "title": "默认运费模板ID"},
            {"index": index++, "columnWidth": "60", "field": "platformCategories", "title": "经营范围"},
            {"index": index++, "columnWidth": "22", "field": "owl_createTime", "title": "创建时间"},
            {"index": index++, "columnWidth": "22", "field": "certifyState", "title": "审核状态"},
            {"index": index++, "columnWidth": "22", "field": "publishState", "title": "发布状态"},
            {"index": index++, "columnWidth": "22", "field": "enableState", "title": "冻结状态"},
            {"index": index++, "columnWidth": "22", "field": "productCanBuyState", "title": "商品可否购买"},
            {"index": index++, "columnWidth": "22", "field": "canGiveIntegral", "title": "可否赠送积分"},
            {"index": index++, "columnWidth": "40", "field": "tag", "title": "商家标签"}
        ];

        logMsg = appendLog(logMsg, "总导出商家数量：" + recordList.length);

        // $.log("org_batch_export...batchExport.jsx............title=" + JSON.stringify(titles));
        // $.log("org_batch_export...batchExport.jsx............recordList=" + JSON.stringify(recordList));

        var export_fileName = DateUtil.getLongDate(new Date().getTime());

        var fileUrl = Excel.createExcelList(export_fileName, titles, recordList);

        jBatchImport.file = {url: fileUrl, name: export_fileName};

        logMsg = appendLog(logMsg, "商家导出结束。");

    } catch (e) {
        $.log("org_batch_export....batchExport.jsx....error=" + e);
        logMsg = appendLog(logMsg, "操作出现异常，异常信息为：" + e);
    } finally {
        var endTime = (new Date()).getTime();
        var logInfo = "总耗时=" + (endTime - beginTime) + "毫秒";

        logMsg = appendLog(logMsg, "");
        logMsg = appendLog(logMsg, logInfo);

        jBatchImport.msg = logMsg;
        owl_org_batch_exportService.update(jBatchImport);
    }

})();

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

function getMerchantList(jBatchImport) {

    var searchArgs = getSearchArgs(jBatchImport);

    var pageLimit = 500;
    var totalRecords = owl_orgsService.count(null, searchArgs, jBatchImport.keyword);
    var totalPages = (totalRecords + pageLimit - 1) / pageLimit;
    $.log("org_batch_export...batchExport.jsx.....getMerchantList....totalPages=" + totalPages + "...totalRecords=" + totalRecords);

    var totalMerchant = 0;
    var resultList = [];
    for (var k = 1; k <= totalPages; k++) {
        var start = (k - 1) * pageLimit;
        $.log("org_batch_export...batchExport.jsx...getMerchantList...start=" + start);

        var beginExecTime = new Date().getTime();

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

                try {
                    var publishStateName = "";
                    if (jMerchant.publishState == "0") {
                        publishStateName = "不发布";
                    } else if (jMerchant.publishState == "1") {
                        publishStateName = "发布";
                    }
                    var certifyStateName = "";
                    if (jMerchant.certifyState == "0") {
                        certifyStateName = "新增待审核";
                    } else if (jMerchant.certifyState == "1") {
                        certifyStateName = "修改待审核";
                    } else if (jMerchant.certifyState == "2") {
                        certifyStateName = "审核不通过";
                    } else if (jMerchant.certifyState == "3") {
                        certifyStateName = "审核通过";
                    }
                    var enableStateName = "";
                    if (jMerchant.enableState == "Y") {
                        enableStateName = "激活";
                    } else if (jMerchant.enableState == "N") {
                        enableStateName = "冻结";
                    }
                    var productCanBuyStateName = "";
                    if (jMerchant.productCanBuyState == "0") {
                        productCanBuyStateName = "不可以";
                    } else if (jMerchant.productCanBuyState == "1") {
                        productCanBuyStateName = "可以";
                    }
                    var canGiveIntegralName = "";
                    if (jMerchant.canGiveIntegral == "0") {
                        canGiveIntegralName = "不可以";
                    } else if (jMerchant.canGiveIntegral == "1") {
                        canGiveIntegralName = "可以";
                    }

                    var contactInfo = jMerchant.contactInfo || {};
                    var qiyu_info = jMerchant.qiyu_info || {};

                    var orgTypeName = getOrgTypeName(jMerchant.orgType);
                    var merTypeName = getMerTypeName(jMerchant.merType);
                    var deliveryModeName = getDeliveryModeName(jMerchant.deliveryMode);
                    var moduleIds = getOrgModules(jMerchant);
                    var deliveryPriceTemplates = getDeliveryPriceTemplate(jMerchant);
                    var platformCategories = getPlatformCategoryName(jMerchant);

                    jMerchant.moduleIds = moduleIds;
                    jMerchant.deliveryPriceTemplates = deliveryPriceTemplates;
                    jMerchant.platformCategories = platformCategories;
                    jMerchant.orgType = orgTypeName;
                    jMerchant.merType = merTypeName;
                    jMerchant.deliveryMode = deliveryModeName;
                    jMerchant.publishState = publishStateName;
                    jMerchant.certifyState = certifyStateName;
                    jMerchant.enableState = enableStateName;
                    jMerchant.productCanBuyState = productCanBuyStateName;
                    jMerchant.canGiveIntegral = canGiveIntegralName;
                    jMerchant.contact = contactInfo.contact || "";
                    jMerchant.mobile = contactInfo.mobile || "";
                    jMerchant.phone = contactInfo.phone || "";
                    jMerchant.email = contactInfo.email || "";
                    jMerchant.address = contactInfo.address || "";
                    jMerchant.businessTime = contactInfo.businessTime || "";
                    jMerchant.openTime = contactInfo.openTime || "";
                    jMerchant.shopAddress = contactInfo.shopAddress || "";
                    jMerchant.siteId = contactInfo.siteId || "";
                    jMerchant.homePageId = contactInfo.homePageId || "";
                    jMerchant.pcHomePageId = contactInfo.pcHomePageId || "";
                    jMerchant.kefuUrl = qiyu_info.kefuUrl || "";
                    jMerchant.owl_createTime = DateUtil.getLongDate(new Date(jMerchant.owl_createTime));
                    if (jMerchant.owl_modifyTime) {
                        jMerchant.lastModifyTime = DateUtil.getLongDate(new Date(jMerchant.owl_modifyTime));
                    }

                    // $.log("org_batch_export...batchExport.jsx...orgInfo...orgId=" + jMerchant.id + "...jMerchant=" + JSON.stringify(jMerchant));

                    resultList.push(jMerchant);
                    totalMerchant++;
                } catch (e) {
                    $.log("org_batch_export...batchExport.jsx...商家获取异常...orgId=" + jMerchant.id + "...error=" + e);
                }
            }
        }

        var endExecTime = new Date().getTime();
        $.log("org_batch_export...batchExport.jsx.....getMerchantList....totalTime=" + (endExecTime - beginExecTime) + "ms" + "...totalMerchant=" + totalMerchant);
    }

    return resultList;
}

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

function getFormatTime(jMerchant, jParentOrder, timeKey) {
    if (jMerchant.time_info && jMerchant.time_info[timeKey]) {
        return DateUtil.getLongDate(new Date(jMerchant.time_info[timeKey]));
    }
    if (jParentOrder) {
        if (jParentOrder.time_info && jParentOrder.time_info[timeKey]) {
            return DateUtil.getLongDate(new Date(jParentOrder.time_info[timeKey]));
        }
    }
    return "";
}


function getPlatformCategoryName(jMerchant) {
    var result = "";
    var platform_category = jMerchant.platform_category;
    if (platform_category) {
        var count = 0;
        for (var i = 0; i < platform_category.length; i++) {
            if (result != "") {
                result += ";\n";
            }
            result += platform_category[i].fullPathName || platform_category[i].name;
            count++;
            if(count >= 100) {
                result += ";\n";
                result += "【注意：经营范围超过100个，后面的经营范围不做展示，如需查看，请到系统中查看】";
                break;
            }
        }
    }
    return result;
}

function getTotalCount(jBatchImport) {
    var searchArgs = getSearchArgs(jBatchImport);
    return owl_orgsService.count(null, searchArgs, jBatchImport.keyword);
}


function getSearchArgs(jBatchImport) {
    var beginTime = 0;
    var endTime = 4102415999000;
    if (jBatchImport.beginCreateTime) {
        beginTime = new Date(jBatchImport.beginCreateTime).getTime();
    }
    if (jBatchImport.endCreateTime) {
        endTime = new Date(jBatchImport.endCreateTime).getTime();
    }
    var searchArgs = {};
    if(jBatchImport._orgId != "0") {
        searchArgs._orgIds = jBatchImport._orgId;
    } else {
        if (jBatchImport.parent_id) {
            searchArgs._orgIds = jBatchImport.parent_id;
        }
    }
    if (jBatchImport.orgType && jBatchImport.orgType != "all") {
        searchArgs.orgType = jBatchImport.orgType;
    }
    if (jBatchImport.merType && jBatchImport.merType != "all") {
        searchArgs.merType = jBatchImport.merType;
    }
    if (jBatchImport.publishState && jBatchImport.publishState != "all") {
        searchArgs.publishState = jBatchImport.publishState;
    }
    if (jBatchImport.certifyState && jBatchImport.certifyState != "all") {
        searchArgs.certifyState = jBatchImport.certifyState;
    }
    if (jBatchImport.enableState && jBatchImport.enableState != "all") {
        searchArgs.enableState = jBatchImport.enableState;
    }
    if (jBatchImport.deliveryMode && jBatchImport.deliveryMode != "all") {
        searchArgs.deliveryMode = jBatchImport.deliveryMode;
    }
    if (jBatchImport.productCanBuyState && jBatchImport.productCanBuyState != "all") {
        searchArgs.productCanBuyState = jBatchImport.productCanBuyState;
    }
    if (jBatchImport.canGiveIntegral && jBatchImport.canGiveIntegral != "all") {
        searchArgs.canGiveIntegral = jBatchImport.canGiveIntegral;
    }
    if (jBatchImport.parent_name) {
        searchArgs.parent_name = jBatchImport.parent_name;
    }
    searchArgs.owl_createTime = SearchUtil.getSearchDateRangeEx(beginTime, endTime);
    return searchArgs;
}


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

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

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

function getOrgModules(jMerchant) {
    var result = "";
    var org_modules = jMerchant.org_modules;
    if (org_modules) {
        for (var i = 0; i < org_modules.length; i++) {
            var jModule = org_modules[i];
            if (result != "") {
                result += ";";
            }
            result += jModule.id;
        }
    }
    return result;
}

function getDeliveryPriceTemplate(jMerchant) {
    var result = "";
    var delivery_price_template = jMerchant.delivery_price_template;
    if (delivery_price_template) {
        for (var i = 0; i < delivery_price_template.length; i++) {
            var jModule = delivery_price_template[i];
            if (result != "") {
                result += ";";
            }
            result += jModule.id;
        }
    }
    return result;
}

