
let mongoose = require("mongoose")
let logger = require("../../../logs/log_helper").logger;
let config = require("../../../config/config.js");
let unitPriceFileModel = mongoose.model('unit_price_file');
let projectModel = mongoose.model('projects');
const ProjectDao = require('../../pm/models/project_model').project;
let unitPriceModel = mongoose.model('unit_price');
let mixRatioModel = mongoose.model('mix_ratio');
let com_electrovalence_model = mongoose.model('com_electrovalence');
let glj_type_util = require('../../../public/cache/std_glj_type_util');
let ration_facade = require('../../main/facade/ration_facade');
let _ = require("lodash");

module.exports={
    index:async function(req,res){
      let unitPriceFileID = req.params.unitPriceFileID;
      let unitPriceFile = await unitPriceFileModel.findOne({id:unitPriceFileID}).lean();
      let project = await projectModel.findOne({ID:unitPriceFile.root_project_id}).lean();
      let tenderData = await ProjectDao.getTenderByUnitPriceFileId(unitPriceFileID);
      let unitpriceList = await unitPriceModel.find({unit_price_file_id:unitPriceFileID},{supplyLocation:0}).lean();
      let mixRatioList = await mixRatioModel.find({unit_price_file_id:unitPriceFileID}).lean();
      let mixRatioMap = _.groupBy(mixRatioList,"connect_key");
      let com_electrovalence = await com_electrovalence_model.findOne({"unit_price_file_id":unitPriceFileID}).lean();
      let projectID = null;

      let gljTypeMap = glj_type_util.getStdGljTypeCacheObj().innerGljTypeObj;
      let usedTenderList = [];
      if (tenderData !== null && tenderData.length > 0) {
          for (let tmp of tenderData) {
              usedTenderList.push(tmp.name);
          }
          projectID = tenderData[0].ID;
      }
      let usedTenderString = "人材机单价的变化，将自动影响以下单位工程造价：<br>"+usedTenderList.join("<br>");
      res.render('building_saas/unit_price_file/index.html',
        {
          userAccount: req.session.userAccount,
          userID: req.session.sessionUser.id,
          unitPriceFileID:unitPriceFileID,
          projectID:projectID,
          versionName: req.session.compilationVersion,
          unitFileName:unitPriceFile.name,
          rootProjectName:project.name,
          usedTenderList:usedTenderList,
          usedTenderString:usedTenderString,
          unitpriceList:JSON.stringify(unitpriceList),
          gljTypeMap:JSON.stringify(gljTypeMap),
          mixRatioMap:JSON.stringify(mixRatioMap),
          com_electrovalence:JSON.stringify(com_electrovalence),
          LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        });
    },
    addMixRatio:async function(req,res){
      let result={
        error:0
    };
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let gljList = data.gljList, parentInfo = data.parentInfo,mixRatios = [],gljCodes=[];

        if(gljList.length > 0){
          for(let newProjectGLJ of gljList){
              let mixRatio = {
                  glj_id:newProjectGLJ.glj_id,
                  consumption:0,
                  unit_price_file_id:parentInfo.unit_price_file_id,
                  connect_key:parentInfo.connect_key,
                  type: newProjectGLJ.type,
                  code: newProjectGLJ.code,
                  specs:newProjectGLJ.specs,
                  name:newProjectGLJ.name,
                  unit:newProjectGLJ.unit,
                  model:newProjectGLJ.model
              };
              mixRatios.push(mixRatio);
              gljCodes.push(newProjectGLJ.code);
          }
          let [unitPriceMap,newUnitPriceList] = await ration_facade.getUnitPriceData(gljList,gljCodes,parentInfo.unit_price_file_id); 
          await ration_facade.setIDfromCounter("mix_ratio",mixRatios);    
          await mixRatioModel.insertMany(mixRatios);
          result.data = {mixRatios:mixRatios,newUnitPriceList:newUnitPriceList};
        }
       
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
      res.json(result);
    }
}

// engineerID = req.params.engineerID;