/**
 * Created by Tony on 2017/6/1.
 */

let async = require("async");
let counter = require('../../../public/counter/counter');

let RptTplModel = require('../models/rpt_template');
let TreeNodeModel = require('../models/tpl_tree_node');
let rptTplDef = require("../../../public/rpt_tpl_def").getUtil();
let stringUtil = require("../../../public/stringUtil");
let JV = require('../rpt_component/jpc_value_define');

//let test_glj_type_util = require("../../../public/cache/std_glj_type_util");

//统一回调函数
let callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
}

module.exports = {
    getRptTplTree: function(req, res) {
        let params = JSON.parse(req.body.params),
            grpType = params.grpType,
            userId = params.userId,
            tplType = params.tplType;
        let filter = {"grpType": grpType, "$or": [{"isDeleted": null}, {"isDeleted": false} ]};
        if (userId) {
            filter.userId = userId;
        }
        if ((tplType && tplType !== rptTplDef.TplType.ALL)) {
            filter.tplType = tplType;
        }
        TreeNodeModel.find(filter, '-_id', function(err, data){
            if (err) {
                callback(req,res, true,"", null);
            } else callback(req,res,false,"", data);
        });
        // let obj = test_glj_type_util.getStdGljTypeCacheObj();
        // console.log(obj.toArray());
        // console.log(obj.getItemById(1));
    },
    updateTreeNodes: function(req, res) {
        let params = JSON.parse(req.body.params),
            nodes = params.nodes;
        let functions = [];
        for (let node of nodes) {
            functions.push((function(doc) {
                return function(cb) {
                    TreeNodeModel.update({ID: doc.ID}, doc, cb);
                };
            })(node));
        }
        async.parallel(functions, function(err, results) {
            callback(req,res, err, "", results);
        });
    },
    deleteRptTplNodes: function(req, res){
        let params = JSON.parse(req.body.params),
            nodeIds = params.nodeIds,
            preNodeId = params.preNodeId,
            preNodeNextId = params.preNodeNextId;
        let functions = [];
        if (preNodeId !== -1) {
            functions.push((function(nodeId, nextId) {
                return function(cb) {
                    TreeNodeModel.update({ID: nodeId}, {"NextSiblingID": nextId}, cb);
                };
            })(preNodeId, preNodeNextId));
        }
        for (let nId of nodeIds) {
            functions.push((function(nodeId) {
                return function(cb) {
                    TreeNodeModel.update({ID: nodeId}, {"isDeleted": true}, cb);
                };
            })(nId));
        }
        async.parallel(functions, function(err, results) {
            callback(req,res, err, "", results);
        });
    },
    createTplTreeNode: function(req, res){
        let params = JSON.parse(req.body.params),
            lastNodeId = params.lastNodeId,
            nodeData = params.rawNodeData;
        counter.counterDAO.getIDAfterCount(counter.moduleName.report, 1, function(err, result){
            nodeData.ID = result.value.sequence_value;
            let node = new TreeNodeModel(nodeData);
            node.save(function (err, result) {
                if (err) {
                    callback(req,res, "树节点错误！", "", null);
                } else {
                    if (lastNodeId > 0) {
                        TreeNodeModel.update({ID: lastNodeId}, {"NextSiblingID": nodeData.ID}, function(err, rst){
                            if (err) {
                                callback(req,res, "树节点错误！", "", null);
                            } else {
                                callback(req,res, false, "", result);
                            }
                        });
                    } else callback(req,res, false, "", result);
                }
            });
        });
    },
    createDftRptTpl: function(req, res) {
        let params = JSON.parse(req.body.params),
            treeNodeId = params.treeNodeId,
            //grpChars = stringUtil.getPinYinFullChars(params.grpChars),
            rptDftTplId = params.rptDftTplId;
        let filter = {"ID": rptDftTplId};
        RptTplModel.findOne(filter, '-_id').exec().then(function(dftTplRst) {
            if (dftTplRst) {
                let _doc = dftTplRst["_doc"];
                _doc["ID"] = treeNodeId;
                _doc["GROUP_KEY"] = "";
                _doc["ID_KEY"] = "";
                let rptTpl = new RptTplModel(_doc);
                rptTpl.save(function (err, actTplRst) {
                    if (err) {
                        callback(req,res, "报表模板创建错误", "", null);
                    } else {
                        //TreeNodeModel.update();
                        TreeNodeModel.update({ID: treeNodeId}, {"refId": treeNodeId}, function(err, rst){
                            if (err) {
                                callback(req,res, "报表模板创建错误", "", null);
                            } else {
                                callback(req,res, false, "", actTplRst);
                            }
                        });
                    }
                });
            } else {
                callback(req, res, 'Create report template failed!', null);
            }
        })
    },
    getRefRptTpl: function (req, res) {
        let params = JSON.parse(req.body.params),
            rptTplId = params.rptTplId;
        let filter = {"ID": rptTplId};
        RptTplModel.findOne(filter, '-_id').exec().then(function(rstTpl) {
            if (rstTpl) {
                callback(req,res, false, "", rstTpl);
            } else {
                callback(req, res, 'The report template was not found!', null);
            }
        })
    },
    updateRptTpl: function (req, res) {
        let params = JSON.parse(req.body.params),
            rptTpl = JSON.parse(params.rptTpl);
        let filter = {"ID": parseInt(rptTpl[JV.PROP_ID])};
        RptTplModel.update(filter, rptTpl, function (err, rst) {
            if (err) {
                callback(req, res, true, 'The report template was updated failed!', false);
            } else {
                callback(req, res, false, 'The report template was updated successfully!', true);
            }
        });
    }
}