/**
 * Created by Tony on 2017/8/9.
 */

// let consts = require('../../../modules/main/models/project_consts');
// let projectConst = consts.projectConst;
let prjMdl = require('../../../modules/pm/models/project_model');
let projectDataMdl = require('../../../modules/main/models/project');
let projectFacade = require('../../../modules/main/facade/project_facade');
let billsUnitPriceFeatureModel = mongoose.model('std_bills_unitprice_feature_lib');

module.exports = {
    prepareProjectData: prepareProjectData,
    getBudgetSummayDatas: getBudgetSummayDatas,
    getGLJSummayDatas: getGLJSummayDatas,
    prepareMultiProjectData: prepareMultiProjectData,
    prepareMultiProjectDataEx: prepareMultiProjectDataEx,
};

function prepareProjectData(userId, prjId, filter, callback) {
    let rawDataObj = null;
    let basicInformation = prjMdl.project.getBasicInfo(prjId);
    let estUnitPriceFeature = null;
    prjMdl.project.getUserProject(userId, prjId, function(err, msg, rst){
        if (!err) {
            rawDataObj = {};
            rawDataObj.prj = rst;
            let doc = rst._doc? rst._doc : rst;
            if (doc.property.engineeringName === '指标估算') {
                //要加料
                let conditions = {compilationId: doc.compilation};
                estUnitPriceFeature = billsUnitPriceFeatureModel.findOne(conditions,{_id: 0}).lean();
                // billsUnitPriceFeatureModel
            }
            projectDataMdl.getFilterData(prjId, filter, function (results) {
                if (results) {
                    rawDataObj.prjData = results;
                    basicInformation.then(function(basicRst) {
                        if (basicRst !== null && basicRst !== undefined) {
                            let doc = (rawDataObj.prj._doc)?rawDataObj.prj._doc:rawDataObj.prj;
                            doc.property.basicInformation = basicRst;
                        }
                        if (estUnitPriceFeature) {
                            estUnitPriceFeature.then( (features) => {
                                let doc = (rawDataObj.prj._doc)?rawDataObj.prj._doc:rawDataObj.prj;
                                doc.property.estUnitPriceFeature = features.feature;
                                // console.log(features);
                                callback(false, 'Succeeded!', rawDataObj);
                            });
                        } else {
                            callback(false, 'Succeeded!', rawDataObj);
                        }
                    });
                    // callback(false, 'Succeeded!', rawDataObj);
                } else {
                    callback(true, 'No data were found!', null);
                }
            });
        } else {
            callback(err, msg, null);
        }
    });
}

async function getBudgetSummayDatas(prjIds, userId, CompilationId, overWriteUrl) {
    return await projectFacade.getBudgetSummayDatas(prjIds, userId, CompilationId, overWriteUrl);
}

async function getGLJSummayDatas(prjIds, compilationName = '') {
    return await projectFacade.getGLJSummayDatas(prjIds, compilationName);
}

// prepareMultiProjectData 方法实际测试有并行问题，并行的结果有时候会乱来，弃用。以prepareMultiProjectDataEx代替
async function prepareMultiProjectData(userId, prjIds, filter) {
    function getProjectPageData(prjId, basicRst) {
        return new Promise(function(resolve, reject) {
            let estUnitPriceFeature = null;
            prjMdl.project.getUserProject(userId, prjId, function(err, msg, rst){
                if (!err) {
                    projectDataMdl.getFilterData(prjId, filter, function(results) {
                        let doc = rst._doc? rst._doc : rst;
                        if (doc.property.engineeringName === '指标估算') {
                            //要加料
                            let conditions = {compilationId: doc.compilation};
                            estUnitPriceFeature = billsUnitPriceFeatureModel.findOne(conditions,{_id: 0}).lean();
                        }
                        if (results) {
                            rawDataObj = {};
                            rawDataObj.prj = rst;
                            rawDataObj.prjData = results;
                            // let doc = (rawDataObj.prj._doc)?rawDataObj.prj._doc:rawDataObj.prj;
                            if (basicRst !== null) {
                                doc.property.basicInformation = basicRst;
                            }
                            if (estUnitPriceFeature) {
                                estUnitPriceFeature.then( (features) => {
                                    // let doc = (rawDataObj.prj._doc)?rawDataObj.prj._doc:rawDataObj.prj;
                                    doc.property.estUnitPriceFeature = features.feature;
                                    console.log(`prjId: ${prjId}`);
                                    console.log(rawDataObj);
                                    resolve(rawDataObj);
                                });
                            } else {
                                resolve(rawDataObj);
                            }
                        } else {
                            return reject('No data were found!');
                        }
                    });
                } else {
                    return reject(err);
                }
            });
        });
    }
    let parallelFunctions = [];
    for (let pidx = 0; pidx < prjIds.length; pidx++) {
        let firstBasicRst = await prjMdl.project.getBasicInfo(prjIds[pidx]);
        parallelFunctions.push(getProjectPageData(prjIds[pidx], firstBasicRst));
    }
    let rst = await Promise.all(parallelFunctions);
    return rst;
}

async function prepareMultiProjectDataEx(userId, prjIds, filter) {
    let rstData = [];
    for (let pidx = 0; pidx < prjIds.length; pidx++) {
        let basicRst = await prjMdl.project.getBasicInfo(prjIds[pidx]);
        let prj = await prjMdl.project.getUserProjectAsync(userId, prjIds[pidx]);
        let prjData = await projectDataMdl.getFilterDataSync(prjIds[pidx], filter);
        let prjDoc = prj._doc ? prj._doc : prj;
        if (prjDoc.property.engineeringName === '指标估算') {
            //要加料
            let conditions = {compilationId: prjDoc.compilation};
            let estUnitPriceFeature = await billsUnitPriceFeatureModel.findOne(conditions,{_id: 0}).lean();
            prjDoc.property.estUnitPriceFeature = estUnitPriceFeature.feature;
        }
        let rawDataObj = {};
        rawDataObj.prj = prj;
        rawDataObj.prjData = prjData;
        prjDoc.property.basicInformation = basicRst;
        rstData.push(rawDataObj);
    }
    return rstData;
}