/**
 * Created by Mai on 2017/1/18.
 */
import UnitPriceFileModel from "../../glj/models/unit_price_file_model";
let ProjectsData = require('../models/project_model').project;
let projType = require('../models/project_model').projType;
const engineering = require("../../common/const/engineering");
let EngineeringLibModel = require("../../users/models/engineering_lib_model");
let fee_rate_facade = require("../../fee_rates/facade/fee_rates_facade");

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


module.exports = {
    checkRight: function (req, res) {
        let data = JSON.parse(req.body.data);
        if (data.user_id) {
            return data.user_id === req.session.sessionUser.ssoId;
        } else {
            return false;
        }
    },
    checkProjectRight: function (userId, projectId, callback) {
        ProjectsData.getProject(projectId).then(function (result) {
            /**
             * result._doc.userID(Number): MongoDB
             * userId(String): Session.userID
             */
            if (result._doc.userID == userId && result._doc.projType === projType.tender) {
                callback(true);
            } else {
                callback(false);
            }
        }).catch(function (err) {
            callback(false);
        });
    },
    getProjects: function(req, res){
        ProjectsData.getUserProjects(req.session.sessionUser.ssoId, function(err, message, projects){
            if (projects) {
                callback(req, res, err, message, projects);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },
    updateProjects: async function (req, res) {
        let data = JSON.parse(req.body.data);
        await ProjectsData.updateUserProjects(req.session.sessionUser.ssoId, data.updateData, function (err, message, data) {
            if (err === 0) {
                callback(req, res, err, message, data);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },
    copyProjects: function (req, res) {
        let data = JSON.parse(req.body.data);
        ProjectsData.copyUserProjects(req.session.sessionUser.ssoId, data.updateData, function (err, message, data) {
            if (err === 0) {
                callback(req, res, err, message, data);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },
    rename: function (req, res) {
        let data = JSON.parse(req.body.data);
        ProjectsData.rename(req.session.sessionUser.ssoId, data, function (err, message) {
            callback(req, res, err, message, null);
        });
    },
    getProject: function(req, res){
        let data = JSON.parse(req.body.data);
        ProjectsData.getUserProject(req.session.sessionUser.ssoId, data.proj_id, async function(err, message, data){
            if (err === 0) {
                let engineeringLibModel = new EngineeringLibModel();
                let engineeringInfo = data !== null && data.property.engineering_id !== undefined ?
                    await engineeringLibModel.getEngineering(data.property.engineering_id) : null;
                let strData = JSON.stringify(data);
                let projInfo = JSON.parse(strData);
                if (engineeringInfo !== null) {
                    projInfo.engineeringInfo = engineeringInfo;
                }
                callback(req, res, err, message, projInfo);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },
    beforeOpenProject: function (req, res) {
        let data = JSON.parse(req.body.data);
        ProjectsData.beforeOpenProject(req.session.sessionUser.ssoId, data.proj_id, data.updateData, function (err, message, data) {
            callback(req, res, err, message, data);
        });
    },
    getNewProjectID: function (req, res) {
        let data = JSON.parse(req.body.data);
        ProjectsData.getNewProjectID(data.count, function (err, message, data) {
            callback(req, res, err, message, data);
        });
    },
    // 项目管理首页
    index: async function(request, response) {
        // 获取编办信息
        let sessionCompilation = request.session.sessionCompilation;


        // 清单计价
        let billValuation = sessionCompilation.bill_valuation !== undefined ?
            sessionCompilation.bill_valuation : [];

        // 获取标准库数据
        let engineeringLibModel = new EngineeringLibModel();
        billValuation = await engineeringLibModel.getLib(billValuation);

        // 定额计价
        let rationValuation = sessionCompilation.ration_valuation !== undefined ?
            sessionCompilation.ration_valuation : [];
        rationValuation = await engineeringLibModel.getLib(rationValuation);

        let renderData = {
            userAccount: request.session.userAccount,
            userID: request.session.sessionUser.ssoId,
            compilationData: sessionCompilation,
            billValuation: JSON.stringify(billValuation),
            rationValuation: JSON.stringify(rationValuation),
            engineeringList: JSON.stringify(engineering.List)
        };

        response.render('building_saas/pm/html/project-management.html', renderData);
    },
    // 获取单价文件列表
    getUnitFileList: async function(request, response) {
        let data = request.body.data;
        try {
            data = JSON.parse(data);
            let projectId = data.parentID !== undefined ? data.parentID : 0;
            if (isNaN(projectId) && projectId <= 0) {
                throw {msg: 'id数据有误!', err: 1};
            }
            // 获取对应建设项目下所有的单位工程id
            let idList = await ProjectsData.getTenderByProjectId(projectId);
            if (idList.length <= 0) {
                throw {msg: '不存在对应单位工程', err: 0};
            }
            // 获取对应的单价文件
            let unitPriceFileModel = new UnitPriceFileModel();
            let unitPriceFileData = await unitPriceFileModel.getDataByTenderId(idList);

            if (unitPriceFileData === null) {
                throw {msg: '不存在对应单价文件', err: 0};
            }

            // 整理数据
            let unitPriceFileList = [];
            for (let unitPriceFile of unitPriceFileData) {
                let tmp = {
                    name: unitPriceFile.name,
                    id: unitPriceFile.id
                };
                unitPriceFileList.push(tmp);
            }

            callback(request, response, 0, '', unitPriceFileList);
        } catch (error) {
            console.log(error);
            let responseData = error.err === 1 ? null : [];
            callback(request, response, error.err, error.msg, responseData);
        }
    },
    getFeeRateFileList:async function(request, response) {
        let data = request.body.data;
        try {
            data = JSON.parse(data);
            let projectId = data.parentID !== undefined ? data.parentID : 0;
            if (isNaN(projectId) && projectId <= 0) {
                throw {msg: 'id数据有误!', err: 1};
            }
            // 获取对应建设项目下所有的单位工程id
            let feeRateFileList = await fee_rate_facade.getFeeRatesByProject(projectId);
            callback(request, response, 0, '',feeRateFileList );
        } catch (error) {
            console.log(error);
            let responseData = error.err === 1 ? null : [];
            callback(request, response, error.err, error.msg, responseData);
        }
    }
};