//#import Util.js
//#import @handlers/include/checklogin.jsx
//#import $@projectCode:services/modelService.jsx
//#import excel.js
//#import DateUtil.js


var formSpecs = @formSpecs;
var spec = @spec;

main(@projectCodeService, spec);
function formatDateWithTimeZone (date, timeZone) {
    if (date === null || date === undefined) {
        return null;
    }
    var dateObj = new Date(date);
    var ts = new Date(dateObj.getTime() + timeZone*60*60*1000);
    var year = ts.getUTCFullYear();
    var month = ts.getUTCMonth() + 1;
    var day = ts.getUTCDate();
    var hour = ts.getUTCHours();
    var minute = ts.getUTCMinutes();
    var second = ts.getUTCSeconds();
    return year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + " " + (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
}


function main(modelService,spec){

    var ctx = JSON.parse(env);
    var params = ctx.params;
    var key = params.key;

    /******************************/
    var ret = getRows(modelService, spec);
    var taskInfo = modelService.getExportTaskInfo(taskInfoId);
    taskInfo.processState = "processing";
    taskInfo.percent = 20;
    taskInfo.lastTime = new Date().getTime();
    taskInfo.total = ret.total;
    taskInfo.msg = "获取数据记录完成, 数据条数:" + ret.total;
    modelService.updateExportTaskInfo(taskInfoId, taskInfo);
    /*****************************/


    /****************************************/
    var exportConfig = getExportConfig(spec,key);
    var titleList = exportConfig.cols;
    if(!titleList){
        return;
    }
    titleList.forEach(function(title){
        var fullKey = title.field;
        var fullField = modelService.getField(fullKey);
        title.fullField = fullField;

    });
    var recordList = ret.rows.map(function(row){

        var record = {};
        try{
            titleList.forEach(function(title){
                var field = title.fieldKey|| title.field
                var value = modelService.getValue(title.field,row);
                if(title.type==="date"){
                    if(value){
                        if(!isNaN(value)){
                            value = Number(value);
                        }
                        var ts = new Date(value);
                        value = formatDateWithTimeZone(ts, 8);
                        // value = ts /86400000+25569; //这是excel的特殊的格式，用小数点表示
                    }

                }
                if(title.fullField && title.fullField.options && title.fullField.fieldType==='choice'){
                    var options = title.fullField.options;
                    for(var i=0;i<options.length;i++){
                        var option = options[i];
                        if(option[0] === value){
                            value = option[1];
                            break;
                        }
                    }

                }
                if(title.type==="imgUrls"){
                    if(value && value.length>0){
                        var urls = value.map(function(imgObj){
                            return imgObj.url;
                        });
                        value = urls.join("\n");
                    }
                }
                if(title.type==="img"){
                    if(value && value.length>0){
                        var imgIdx = title.imgIdx || 0;
                        if(value.length>imgIdx && value[imgIdx] && value[imgIdx].url){
                            value = value[imgIdx].url;
                            if(title.spec && value.indexOf("?")===-1){
                                value = value + title.spec;
                            }
                        }
                        else{
                            value = "";
                        }
                    }
                }
                record[field] = value;
            });
        }
        catch(e){
            $.log(e.toString());
        }

        return record;
    });

    var taskInfo = modelService.getExportTaskInfo(taskInfoId);
    taskInfo.processState = "processing";
    taskInfo.percent = 40;
    taskInfo.lastTime = new Date().getTime();
    taskInfo.msg = "准备完数据,正在生成Excel文件......";
    modelService.updateExportTaskInfo(taskInfoId, taskInfo);
    /****************************************/


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

    titleList.forEach(function(title){
        //date类型的值，已经变成了字符串，不需要再设置导出类型，默认为字符串
        if(title.type==='date'){
            delete title.type;
        }
    });
    var fileUrl = Excel.createExcelList(export_fileName, titleList, recordList);

    var taskInfo = modelService.getExportTaskInfo(taskInfoId);
    taskInfo.processState = "succeeded";
    taskInfo.percent = 100;
    taskInfo.lastTime = new Date().getTime();
    taskInfo.msg = "导出文件成功，共导出" + ret.total + "条数据";
    taskInfo.fileUrl = fileUrl;
    modelService.updateExportTaskInfo(taskInfoId, taskInfo);
    /********************************************/
}

function getExportConfig(spec, key) {
    var meta = spec['#meta'];
    var exportConfigs = meta.export;
    var effectiveExportConfig = null;
    exportConfigs.forEach(function(exportConfig){
        if(exportConfig.key === key){
            effectiveExportConfig = exportConfig;
        }
    });
    return effectiveExportConfig;
}

function getRows(modelService, spec) {

    var meta = spec['#meta'];
    var maxRows = Number(meta.maxRows) || 10000;
    var isPublic = meta && meta.isPublic;
    var tableId = 'owl_' + spec._t;
    var ctx = JSON.parse(env);
    var params = ctx.params;

    var loginId = ctx.loginId;
    var roleId = params.rroleId || ctx.roleId;
    var orgId = params.rorgId || ctx.orgId;

    var searchArgs = params.searchArgs;
    var templateId = params.templateId;

    var sort = params.sort;
    var exportRange = params.exportRange;
    var outputTarget = params.outputTarget;
    var ids = params.ids;
    var key = params.key;

    if (exportRange === "all") {
        var keyword = searchArgs.keyword;
        var mfilters = null;
        delete searchArgs.keyword;
        if (isPublic || orgId === '0') {
            delete searchArgs["_orgIds"];
        } else {
            searchArgs["_orgIds"] = orgId;
            var permissions = getPermissions(roleId,tableId);
            mfilters = getListPermissionFilter(tableId, roleId, orgId, loginId, permissions);
        }

        delete searchArgs.recycleBin;

        var pageSize = Number(maxRows);
        var from = 0;
        var sort = {
            owl_modifyTime: {order: "desc"}
        }

        var sr = modelService.search(mfilters, searchArgs, keyword, from, pageSize, sort);
        if(sr.state==='ok'){
            var rows = [];
            sr.list.forEach(function(r){
                var row = modelService.get(r.id);
                if(row){
                    rows.push(row);
                }
            });
            return {
                rows: rows,
                total: rows.length
            }
        }
        else{
            return {
                rows: [],
                total: 0
            }
        }

    }
    else if(exportRange=== "checkedOnly") {
        var ids = params.ids;
        var rows = [];
        ids.forEach(function(id){
            var row = modelService.get(id);
            if(row){
                rows.push(row);
            }
        });
        return {
            rows: rows,
            total: rows.length
        }
    }
    return {
        rows: [],
        total: 0
    };

}











