//#import Util.js
//#import DateUtil.js
//#import excel.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_mall_o:services/modelService.jsx
//#import $owl_user_batch_export_by_userid:services/modelService.jsx
//#import $owlService:services/org/OrgUtil.jsx

;(function () {

    var jBatchImport = owl_user_batch_export_by_useridService.get(batchId);

    var logMsg = "";
    var total = 0;
    var totalSuccess = 0;
    var totalFailed = 0;
    var totalNullOrder = 0;
    var beginTime = (new Date()).getTime();
    try {

        var jFile = jBatchImport.file_userIds;
        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;
        }

        logMsg = appendLog(logMsg, "数据导出正在进行");
        jBatchImport.msg = logMsg;
        owl_user_batch_export_by_useridService.update(jBatchImport);

        var sheet = jData.sheets[0];
        var rows = sheet.rows;

        var recordList = [];
        for (var j = 1; j < rows.length; j++) {
            try {
                total++;

                var row = rows[j];
                var cells = row.cells;
                var userId = getCellValue(cells, 0);

                if (!userId || userId == "") {
                    totalFailed++;
                    recordList.push({userId: userId});
                    continue;
                }

                var jUser = owl_mall_uService.get(userId);
                if (!jUser) {
                    $.log("user_batch_export_by_userid...batchExportTask.jsx...user is null...userId=" + userId);
                    totalFailed++;
                    continue;
                }

                var orderList = getUserOrders(userId);
                if (!orderList || orderList.length == 0) {
                    totalNullOrder++;
                    recordList.push({userId: userId});
                    continue;
                }
                $.log("user_batch_export_by_userid...batchExportTask.jsx...userId=" + userId + "...orderList.length=" + orderList.length);

                var createTime = DateUtil.getLongDate(new Date(jUser.owl_createTime).getTime());
                var lastOrderTime = getLastOrderTime(orderList);

                var jRecord = {};
                jRecord.userId = userId;
                jRecord.mobile = jUser.mobile || "";
                jRecord.createTime = createTime;
                jRecord.lastOrderTime = lastOrderTime;
                jRecord.parentOrder_total = getTotalOrderNum(orderList, "n", null, null);
                jRecord.parentOrder_total_price = getTotalOrderPrice(orderList, "n", null, null);
                jRecord.parentOrder_unpaid = getTotalOrderNum(orderList, "n", "unpaid", null);
                jRecord.parentOrder_unpaid_price = getTotalOrderPrice(orderList, "n", "unpaid", null);
                jRecord.parentOrder_paid = getTotalOrderNum(orderList, "n", "paid", "submitted");
                jRecord.parentOrder_paid_price = getTotalOrderPrice(orderList, "n", "paid", "submitted");
                jRecord.parentOrder_cancel = getTotalOrderNum(orderList, "n", "unpaid", "canceled");
                jRecord.parentOrder_cancel_price = getTotalOrderPrice(orderList, "n", "unpaid", "canceled");
                jRecord.order_total = getTotalOrderNum(orderList, "y", null, null);
                jRecord.order_total_price = getTotalOrderPrice(orderList, "y", null, null);
                jRecord.order_paid = getTotalOrderNum(orderList, "y", null, "paid");
                jRecord.order_paid_price = getTotalOrderPrice(orderList, "y", null, "paid");
                jRecord.order_outbound = getTotalOrderNum(orderList, "y", null, "outbound");
                jRecord.order_outbound_price = getTotalOrderPrice(orderList, "y", null, "outbound");
                jRecord.order_signed = getTotalOrderNum(orderList, "y", null, "signed");
                jRecord.order_signed_price = getTotalOrderPrice(orderList, "y", null, "signed");
                jRecord.order_canceled = getTotalOrderNum(orderList, "y", null, "canceled");
                jRecord.order_canceled_price = getTotalOrderPrice(orderList, "y", null, "canceled");
                recordList.push(jRecord);

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

        var titles = getTitles();

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

        var fileUrl = Excel.createExcelList(export_fileName, titles, recordList);
        $.log("user_batch_export_by_userid....batchExportTask.jsx....fileUrl=" + fileUrl);

        jBatchImport = owl_user_batch_export_by_useridService.get(jBatchImport.id);
        jBatchImport.file = {url: fileUrl, name: export_fileName};

    } catch (e) {
        $.log("user_batch_export_by_userid....batchExportTask.jsx....error=" + e);
        logMsg = appendLog(logMsg, "操作出现异常，异常信息为：" + e);
    } finally {
        var endTime = (new Date()).getTime();
        var logInfo = "总耗时=" + (endTime - beginTime) + "毫秒";
        logInfo += "。总处理数量=" + total;
        logInfo += "。成功处理数量=" + totalSuccess;
        logInfo += "; 未处理总数量=" + totalFailed;
        logInfo += "; 无任何订单数量=" + totalNullOrder;

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

        jBatchImport.msg = logMsg;
        owl_user_batch_export_by_useridService.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 getTitles() {
    var index = 0;

    var titles = [];
    titles.push({"index": index++, "columnWidth": "30", "field": "userId", "title": "会员ID"});
    titles.push({"index": index++, "columnWidth": "16", "field": "mobile", "title": "手机号码"});
    titles.push({"index": index++, "columnWidth": "22", "field": "createTime", "title": "注册时间"});
    titles.push({"index": index++, "columnWidth": "22", "field": "lastOrderTime", "title": "最近下单时间"});
    titles.push({"index": index++, "columnWidth": "12", "field": "parentOrder_total", "title": "母订单总数"});
    titles.push({"index": index++, "columnWidth": "12", "field": "parentOrder_total_price", "title": "母订单总金额"});
    titles.push({"index": index++, "columnWidth": "16", "field": "parentOrder_unpaid", "title": "待支付母订单数"});
    titles.push({
        "index": index++,
        "columnWidth": "18",
        "field": "parentOrder_unpaid_price",
        "title": "待支付母订单总金额"
    });
    titles.push({"index": index++, "columnWidth": "16", "field": "parentOrder_paid", "title": "已支付母订单数"});
    titles.push({
        "index": index++,
        "columnWidth": "18",
        "field": "parentOrder_paid_price",
        "title": "已支付母订单总金额"
    });
    titles.push({"index": index++, "columnWidth": "16", "field": "parentOrder_cancel", "title": "已取消母订单数"});
    titles.push({
        "index": index++,
        "columnWidth": "18",
        "field": "parentOrder_cancel_price",
        "title": "已取消母订单总金额"
    });
    titles.push({"index": index++, "columnWidth": "12", "field": "order_total", "title": "订单总数"});
    titles.push({"index": index++, "columnWidth": "12", "field": "order_total_price", "title": "订单总金额"});
    titles.push({"index": index++, "columnWidth": "16", "field": "order_paid", "title": "待发货订单数"});
    titles.push({"index": index++, "columnWidth": "18", "field": "order_paid_price", "title": "待发货订单总金额"});
    titles.push({"index": index++, "columnWidth": "16", "field": "order_outbound", "title": "已出库订单数"});
    titles.push({"index": index++, "columnWidth": "18", "field": "order_outbound_price", "title": "已出库订单总金额"});
    titles.push({"index": index++, "columnWidth": "16", "field": "order_signed", "title": "已签收订单数"});
    titles.push({"index": index++, "columnWidth": "18", "field": "order_signed_price", "title": "已签收订单总金额"});
    titles.push({"index": index++, "columnWidth": "16", "field": "order_canceled", "title": "已取消订单数"});
    titles.push({"index": index++, "columnWidth": "16", "field": "order_canceled_price", "title": "已取消订单总金额"});
    return titles;
}

function getUserOrders(userId) {
    var searchArgs = {};
    searchArgs["buyer_info.user_id"] = userId;

    var pageSize = 5000;
    var from = 0;

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

function getLastOrderTime(orderList) {
    for (var i = 0; i < orderList.length; i++) {
        var jOrder = orderList[i];
        if (jOrder.isSubOrder == "n") {
            return DateUtil.getLongDate(new Date(jOrder.owl_createTime).getTime());
        }
    }
    return "";
}

function getTotalOrderNum(orderList, type, payState, processState) {
    var totalNum = 0;
    for (var i = 0; i < orderList.length; i++) {
        var jOrder = orderList[i];
        if (jOrder.isSubOrder != type) {
            continue;
        }
        if (payState && jOrder.pay_state != payState) {
            continue;
        }
        if (processState && jOrder.process_state != processState) {
            continue;
        }
        totalNum++;
    }
    return totalNum;
}

function getTotalOrderPrice(orderList, type, payState, processState) {
    var totalPrice = 0;
    for (var i = 0; i < orderList.length; i++) {
        var jOrder = orderList[i];
        if (jOrder.isSubOrder != type) {
            continue;
        }
        if (payState && jOrder.pay_state != payState) {
            continue;
        }
        if (processState && jOrder.process_state != processState) {
            continue;
        }
        totalPrice += Number(jOrder.price_info.total_deal_price || 0);
    }
    return Number(totalPrice).toFixed(2);
}