/**
 * Created by CSL on 2017-10-10.
 */

const uuidV1 = require('uuid/v1');
let logger = require("../../../logs/log_helper").logger;
let mongoose = require('mongoose');
let stdLabourCoesModel = mongoose.model('std_labour_coes');
let projectLabourCoesModel = mongoose.model('labour_coes');
let EngineeringLibModel = require("../../users/models/engineering_lib_model");
let _=require("lodash");
let consts = require('../models/project_consts');
let projectConsts = consts.projectConst;

module.exports = {
    newProjectLabourCoe: newProjectLabourCoe,
    getProjectLabourCoe: getProjectLabourCoe,
    getStdLabourCoe: getStdLabourCoe,
    getData: getData,
    save: save
};

async function newProjectLabourCoe(data) {
    logger.info(`Create new LabourCoe file for project : ${data.ID}`);
    let rst = null;
    let egnrModel = new EngineeringLibModel();
    let egnr = await egnrModel.getEngineering(data.property.engineering_id);
    if(!egnr) return rst;
    let valid_LC_libs = egnr._doc.artificial_lib;
    if (valid_LC_libs == undefined  || valid_LC_libs.length == 0) return rst;
    // 绑定多个人工系数标准文件时，默认取第一个作为标准模板。
    let stdLC = await getStdLabourCoe(valid_LC_libs[0].id);
    let doc={
        ID: uuidV1(),
        projectID: data.ID,
        name: data.name,
        libID: stdLC.ID,
        libName: stdLC.libName,
        coes: stdLC.coes
    };
    await projectLabourCoesModel.create(doc);
    rst = {ID: doc.ID, name: doc.name};
    return rst;
};

async function getProjectLabourCoe(ID) {
    let projLC = await projectLabourCoesModel.findOne({ID:ID});
    return projLC;
};


async function getStdLabourCoe(libID) {
    let stdLC = await stdLabourCoesModel.findOne({ID:libID});
    return stdLC;
};

// 统一的 getData() 方法供project调用
function getData(projectID, callback) {
    projectLabourCoesModel.findOne({projectID: projectID}, '-_id', function (err, datas) {
        if (!err) {
            // 旧项目没有人工系数文件，默认给它生成一个。
            if (!datas) {
                logger.info(`Create a LabourCoe file for old project : ${projectID}`);
                getStdLabourCoe(1).then(function (stdLC) {
                    if(stdLC){
                        let doc = {
                            ID: uuidV1(),
                            projectID: projectID,
                            name: '[旧项目补人工系数文件]',
                            libID: stdLC.ID,
                            libName: stdLC.libName,
                            coes: stdLC.coes
                        };
                        projectLabourCoesModel.create(doc);
                    }
                    callback(0, projectConsts.LABOUR_COE, stdLC);
                });
            } else {
                callback(0, projectConsts.LABOUR_COE, datas);
            };
        } else {
            callback(1, projectConsts.LABOUR_COE, null);
        };
    });
};

// 统一的 save() 方法供project调用
// data 格式要求：{projectID: projectID, libID: libID, libName: libName, newItemArr: needUpdateDatas}
// needUpdateDatas: [{ID: 5, value: 2.87}, {ID: 13, value: 2.91}]
function save (data, callback) {
    let updateArr = [];
    // let datas = JSON.parse(data);

    if (data.libID){
        let ItemObj = {
            updateOne: {
                filter: {projectID: data.projectID},
                update: { 'libID': data.projectID, 'libName': data.libName }
            }
        };
        updateArr.push(ItemObj);
    };

    for (let Item of data.newItemArr) {
         let ItemObj = {
             updateOne: {
                 filter: {projectID: data.projectID, 'coes.ID': Item.ID},
                 update: { 'coes.$.coe': Item.coe }
             }
         };
         updateArr.push(ItemObj);
    };
    // console.log(JSON.stringify(updateArr));
    projectLabourCoesModel.bulkWrite(updateArr)
        .then(function(){
            logger.info(`Project LabourCoe saved successful : ${data.projectID}`);
            callback('', null);
        })
        .catch(function (err) {
            logger.err('labourCoe save error: ' + err);
            callback(err, null)
        });
}