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

;(function () {

    var jBatchImport = owl_user_batch_base_exportService.get(batchId);

    $.log("user_batch_base_export...batchExport.jsx...begin...jBatchImport=" + JSON.stringify(jBatchImport));
    var logMsg = "";
    var beginTime = (new Date()).getTime();
    try {
        var orgId = jBatchImport._orgId;
        if (orgId != "0") {
            logMsg = appendLog(logMsg, "操作终止，原因是：该功能只支持在平台后台操作，请切换到平台后台进行");
            return;
        }

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

        var recordList = getUserRecordList(jBatchImport);
        var index = 0;
        var titles = [
            {"index": index++, "columnWidth": "22", "field": "id", "title": "用户ID"},
            {"index": index++, "columnWidth": "8", "field": "isEnableName", "title": "状态"},
            {"index": index++, "columnWidth": "12", "field": "name", "title": "名称"},
            {"index": index++, "columnWidth": "22", "field": "loginId", "title": "登录ID"},
            {"index": index++, "columnWidth": "12", "field": "realName", "title": "真实姓名"},
            {"index": index++, "columnWidth": "12", "field": "nickName", "title": "昵称"},
            {"index": index++, "columnWidth": "14", "field": "mobile", "title": "手机号"},
            {"index": index++, "columnWidth": "12", "field": "checkedphoneStatusName", "title": "手机已验证"},
            {"index": index++, "columnWidth": "16", "field": "email", "title": "邮箱"},
            {"index": index++, "columnWidth": "12", "field": "checkedemailStatusName", "title": "邮箱已验证"},
            {"index": index++, "columnWidth": "16", "field": "source_name", "title": "会员来源"},
            {"index": index++, "columnWidth": "16", "field": "recommendedUserId", "title": "推荐人"},
            {"index": index++, "columnWidth": "20", "field": "owl_createTime", "title": "创建时间"},
            {"index": index++, "columnWidth": "100", "field": "userCategories", "title": "所属分类"}
        ];

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

        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("user_batch_base_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_user_batch_base_exportService.update(jBatchImport);
    }

})();

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

function getUserRecordList(jBatchImport) {
    var search_args = jBatchImport.search_args || {};
    var searchArgs = getSearchArgs(jBatchImport);

    var pageLimit = 500;
    var totalRecords = owl_mall_uService.count(null, searchArgs, search_args.keyword);
    var totalPages = (totalRecords + pageLimit - 1) / pageLimit;
    $.log("user_batch_base_export...batchExport.jsx.....getUserRecordList....searchArgs=" + JSON.stringify(searchArgs));
    $.log("user_batch_base_export...batchExport.jsx.....getUserRecordList....totalPages=" + totalPages + "...totalRecords=" + totalRecords);

    var totalOrder = 0;
    var resultList = [];
    for (var k = 1; k <= totalPages; k++) {
        var start = (k - 1) * pageLimit;
        $.log("user_batch_base_export.........start=" + start);

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

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

                try {

                    var isEnableName = "正常";
                    if (jRecord.isEnable == "0") {
                        isEnableName = "冻结";
                    }

                    var checkedphoneStatusName = "是";
                    if (jRecord.checkedphoneStatus == "0") {
                        checkedphoneStatusName = "否";
                    }
                    var checkedemailStatusName = "是";
                    if (jRecord.checkedemailStatus == "0") {
                        checkedemailStatusName = "否";
                    }

                    var userCategories = getUserCategoryInfo(jRecord);

                    jRecord.isEnableName = isEnableName;
                    jRecord.checkedphoneStatusName = checkedphoneStatusName;
                    jRecord.checkedemailStatusName = checkedemailStatusName;
                    jRecord.userCategories = userCategories;


                    jRecord.owl_createTime = DateUtil.getLongDate(new Date(jRecord.owl_createTime));

                    resultList.push(jRecord);
                    totalOrder++;
                } catch (e) {
                    $.log("user_batch_base_export...doExportOrder.jsx...数据获取异常...userId=" + jRecord.id + "...error=" + e);
                }
            }
        }

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

    return resultList;
}

function searchUserRecords(searchArgs, jBatchImport, from, pageSize) {
    var search_args = jBatchImport.search_args || {};

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

function getSearchArgs(jBatchImport) {
    var search_args = jBatchImport.search_args || {};

    var filterKeys = [];
    filterKeys.push("keyword");
    filterKeys.push("beginCreateTime");
    filterKeys.push("endCreateTime");
    filterKeys.push("categoryId");
    filterKeys.push("categoryName");
    filterKeys.push("isEnable");
    filterKeys.push("checkedphoneStatus");
    filterKeys.push("checkedemailStatus");
    filterKeys.push("source_isOnline");

    var beginTime = 0;
    if (search_args.beginCreateTime) {
        beginTime = new Date(search_args.beginCreateTime).getTime();
    }
    var endTime = 0;
    if (search_args.endCreateTime) {
        endTime = new Date(search_args.endCreateTime).getTime();
    }
    var searchArgs = {};
    if (jBatchImport._orgId != "0") {
        searchArgs._orgIds = jBatchImport._orgId;
    }
    if (search_args.isEnable != "all") {
        searchArgs.isEnable = search_args.isEnable;
    }
    if (search_args.checkedphoneStatus != "all") {
        searchArgs.checkedphoneStatus = search_args.checkedphoneStatus;
    }
    if (search_args.checkedemailStatus != "all") {
        searchArgs.checkedemailStatus = search_args.checkedemailStatus;
    }
    if (search_args.source_isOnline != "all") {
        searchArgs.source_isOnline = search_args.source_isOnline;
    }
    if(beginTime || endTime) {
        searchArgs.owl_createTime = SearchUtil.getSearchDateRangeEx(beginTime, endTime);
    }

    //这个是通用的搜索字段，特别的搜索特别处理
    for (var key in search_args) {
        if (!search_args[key]) {
            continue;
        }
        if (isFilterSearchKey(filterKeys, key)) {
            continue;
        }
        searchArgs[key] = search_args[key];
    }

    return searchArgs;
}

function isFilterSearchKey(filterKeys, key) {
    for (var m = 0; m < filterKeys.length; m++) {
        if (filterKeys[m] == key) {
            return true;
        }
    }
    return false;
}

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

function getUserCategoryInfo(jUser) {
    var result = "";
    if (jUser.user_categories) {
        for (var i = 0; i < jUser.user_categories.length; i++) {
            var jCategory = jUser.user_categories[i];
            if (result != "") {
                result += ",";
            }
            result += jCategory.name;
        }

    }
    return result;
}

