/**
 * Created by zhang on 2018/9/12.
 */
let logger = require("../../../logs/log_helper").logger;
let mongoose = require('mongoose');
let material_lib = mongoose.model('std_material_replace_lib');
let replace_bills = mongoose.model('std_replace_bills');
let replace_material = mongoose.model('std_replace_material');
let _=require("lodash");
let ration_glj_facade = require('../../ration_glj/facade/ration_glj_facade');
let glj_calculate_facade = require('../../ration_glj/facade/glj_calculate_facade');


module.exports = {
    findMaterial: async function(dataMap,compilationId){
        let libMap = {},resultMap={};
        for(let key in dataMap) {
            let billsLibId = dataMap[key].billsLibId;
            let libID = libMap[compilationId + billsLibId] ? libMap[compilationId + billsLibId] : await getLibID(billsLibId, compilationId);
            libMap[compilationId + billsLibId] = libID;
            if (libID == null) continue;
            let bills = await getBills(key, libID);
            if (bills == null) continue;
            let materialList = await getMaterialByBillsID(bills.ID);
            resultMap[key] = {bills:bills,materialMap:_.indexBy(materialList,'code')};
        }
        return resultMap;
    },
    replace:async function(datas){
        let resultList = [];
        let rationMap = _.groupBy(datas,function(item){//先按定额进行分组
            return item.glj.rationID;
        });
        for(let rationID in rationMap){
           let result = await eachRationGroup(rationID,rationMap[rationID]);
           resultList.push(result);
        }
        return resultList
    }
};

async function eachRationGroup(rationID,datas) {
    let query={rationID:rationID},gljs=[];
    for(let d of datas){
         query["projectID"] = d.glj.projectID;
         gljs.push(await updateRationGLJ(d));
    }
    if(query.projectID){
        let stateResult = await glj_calculate_facade.calculateQuantity(query,null,true);
        return {rationID:rationID,name:stateResult.rationName,adjustState:stateResult.adjustState,ration_gljs:gljs}
    }else {
        throw new Error("人材机的项目ID有问题");
    }

}

async function updateRationGLJ(data) {
    let glj = data.glj;
    let priceInfo = {
        base_price: glj.basePrice,
        market_price: glj.marketPrice
    };
    let [projcetGLJ_n,doc] = await ration_glj_facade.updateRationGLJFromDoc(glj,data.doc,priceInfo);
    return {ID:glj.ID,doc:doc}

}

/*async function doRationGLJUpdate(data) {
    let resutl = {};
    let doc = data.doc;
    let priceInfo = data.priceInfo;
    let rg = await ration_glj.findOne(data.query);
    let gljListModel = new GLJListModel();
    let projectGLJ = getGLJSearchInfo(rg);
    for (let key in doc) {
        projectGLJ[key] = doc[key]
    }
    projectGLJ.base_price = priceInfo.base_price;
    projectGLJ.market_price = priceInfo.market_price;
    let projcetGLJ_n = await gljListModel.modifyGLJ(projectGLJ, rg);
    doc.code = projcetGLJ_n.code;
    doc.projectGLJID = projcetGLJ_n.id;
    if (projcetGLJ_n.unit_price.is_add == 1) {
        doc.createType = 'replace';
        doc.rcode = projcetGLJ_n.original_code;
    } else {
        doc.createType = 'normal';
        doc.rcode = '';
    }
    await ration_glj.findOneAndUpdate(data.query, doc);
    //取价格
    gljListModel.getGLJPrice(projcetGLJ_n);
    doc.basePrice = projcetGLJ_n.unit_price.base_price;
    doc.marketPrice = projcetGLJ_n.unit_price.market_price;
    doc.adjustPrice = projcetGLJ_n.adjust_price;
    doc.isAdd = projcetGLJ_n.unit_price.is_add;
    resutl.doc = doc;
    let stateResult = await glj_calculate_facade.calculateQuantity({
        projectID: data.query.projectID,
        rationID: data.query.rationID
    },null,true);
    resutl.adjustState = stateResult.adjustState;
    resutl.name = stateResult.rationName;
    return resutl;
}*/


async function getLibID(billsLibId,compilationId) {
    let lib = await material_lib.findOne({"compilationId":compilationId,billsLibId:billsLibId});
    if(lib) return lib.ID;
    return null;
}

async function getBills(code,libID) {
    let bills = await replace_bills.findOne({code:code,libID:libID});
    if(bills) return bills;
    return null;
}

async  function getMaterialByBillsID(billsItemID) {
    return await replace_material.find({billsItemID:billsItemID},['code','name','specs','type','unit']);
}