/**
 * Created by Zhong on 2017/8/22.
 */
import BaseController from "../../common/base/base_controller";
import stdgljutil  from "../../../public/cache/std_glj_type_util";
import GljDao from "../models/gljModel";
import EngineeringLibModel from "../../users/models/engineering_lib_model";
let config = require("../../../config/config.js");

let gljDao = new GljDao();
let callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
};

class GljController extends BaseController{
    async redirectGlj(req, res){
        let gljLibId = null, engineeringId, sessionCompilation = req.session.sessionCompilation,
            rationValuation = sessionCompilation.ration_valuation,
            billValuation = sessionCompilation.bill_valuation,
            engineeringLibModel = new EngineeringLibModel(),
            valuationIDs = [] ;
        for(let r of rationValuation){//{ "glj_lib.0": {$exists:1} }
            if(r.id){
                valuationIDs.push(r.id);
            }
        }
        for(let b of billValuation){
            if(b.id){
                valuationIDs.push(b.id);
            }
        }
        if(valuationIDs.length > 0){
            let engineeringInfo = await engineeringLibModel.findDataByCondition({'valuationID': {"$in": valuationIDs},"glj_lib.0": {$exists:1}});//数组大于0
            gljLibId = engineeringInfo.glj_lib.length > 0 && typeof engineeringInfo.glj_lib !== 'undefined' ? engineeringInfo.glj_lib[0].id : null;
        }
        let overWriteUrl = req.session.sessionCompilation && req.session.sessionCompilation.overWriteUrl &&
                            req.session.sessionCompilation._id !== '5b4d581023a924000b760f2d' ? req.session.sessionCompilation.overWriteUrl : null;
        res.render('building_saas/complementary_glj_lib/html/tools-gongliaoji.html',{
            userID: req.session.sessionUser.id,
            gljLibId: gljLibId,
            compilationId: sessionCompilation._id,
            compilationName: sessionCompilation.name,
            versionName: req.session.compilationVersion,
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
            overWriteUrl: overWriteUrl,
        });
    }
    getGljDistType (req, res) {
        let gljDistTypeCache = stdgljutil.getStdGljTypeCacheObj().toArray();
        if(gljDistTypeCache.length >0 ){
            callback(req, res, 0, '', gljDistTypeCache);
        }
        else {
            callback(req, res, 1, 'Error', null);
        }
    }
    getGljTree(req,res){
        let data = JSON.parse(req.body.data);
        let gljLibId = data.gljLibId;
        gljDao.getGljTypes(gljLibId,function(err,data){
            callback(req,res,err, 'Get Tree', data)
        });
    }
    //获取标准分类树和补充分类树
    async getMixedTree(req, res){
        try {
            let data = JSON.parse(req.body.data);
            let treeData = await gljDao.getMixedTree(data.gljLibId, req.session.sessionUser.id, req.session.sessionCompilation._id);
            callback(req, res, 0, 'success', treeData);
        } catch (err) {
            console.log(err);
            callback(req, res, 1, err, null);
        }
    }

    createNewGljTypeNode(req, res) {
        let repId = req.body.repositoryId;
        let lastNodeId = req.body.lastNodeId;
        let lastOpr = req.body.lastOpr;
        let nodeData = JSON.parse(req.body.rawNodeData);
        gljDao.createNewNode(repId, lastOpr, lastNodeId, nodeData, function(err, msg, data){
            callback(req,res,err,msg, data)
        });
    }
    updateGljNodes(req, res) {
        let nodes = JSON.parse(req.body.nodes);
        let repId = req.body.repId,
            lastOpr = req.body.lastOpr;
        gljDao.updateNodes(repId, lastOpr, nodes, function(err,results){
            callback(req,res, err, results)
        });
    }
    deleteGljNodes(req, res) {
        let nodes = JSON.parse(req.body.nodes);
        let preNodeId = req.body.preNodeId;
        let preNodeNextId = req.body.preNodeNextId;
        let repId = req.body.repId, lastOpr = req.body.lastOpr;
        gljDao.removeNodes(repId, lastOpr, nodes, preNodeId, preNodeNextId, function(err,results){
            callback(req,res, err, results)
        });
    }
    getGljItems(req, res) {
        let data = JSON.parse(req.body.data);
        let stdGljLibId = data.stdGljLibId;
        let projection = data.projection;
        gljDao.getGljItems(stdGljLibId, req.session.sessionUser.id, req.session.sessionCompilation._id, projection, function(err, data){
            callback(req,res,err,'Get Items',data)
        });
    }
    getStdItems(req, res) {
        let data = JSON.parse(req.body.data),
            stdGljLibId = data.stdGljLibId,
            projection = data.projection;
        gljDao.getStdItems(stdGljLibId, projection, function (err, data) {
            callback(req, res, err, '获取人材机数据失败', data);
        });
    }

    updateComponent(req, res){
        let userId = req.body.userId;
        let updateArr = JSON.parse(req.body.updateArr);
        gljDao.updateComponent(userId, updateArr, function (err, message, rst) {
            callback(req, res, err, message, rst);
        })
    }
    mixUpdateGljItems(req, res){
        let user_id = req.session.sessionUser.id,
            compilation_id = req.session.sessionCompilation._id;
        let data = JSON.parse(req.body.data);
        let updateItems = data.updateItems,
            addItems = data.addItems,
            removeIds = data.removeIds;
        gljDao.mixUpdateGljItems(user_id, compilation_id, updateItems, addItems, removeIds, function(err, message, rst){
            if (err) {
                callback(req, res, err, message, null);
            } else {
                callback(req, res, 0, message, rst);
            }
        });
    }
}

export default GljController;