module.exports = {
  getUnitPriceData:getUnitPriceData,
  setIDfromCounter:setIDfromCounter,
  getNewProjectGLJFromMissMixratio:getNewProjectGLJFromMissMixratio
};

let mongoose = require("mongoose");
let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
let unitPriceModel = mongoose.model('unit_price');
let counterModel =  mongoose.model('counter');

async function setIDfromCounter(name,list,map,keyfield){//map,keyfield

  let update = {$inc: {sequence_value: list.length}};
  let condition = {_id: name};
  let options = {new: true};

  // 先查找更新
  let counter = await counterModel.findOneAndUpdate(condition, update, options);
  let firstID = counter.sequence_value - (list.length - 1);
  for(let a of list){
      a.id = firstID;
      firstID+=1
      if(map && keyfield){
        let key = a[keyfield];
        map[key]?map[key].push(a):map[key]=[a]
      }
  }
}

function getProjectGLJNewData(tmp,projectId,ext){
  let gljData = {
      glj_id: tmp.ID,
      repositoryId:tmp.repositoryId,
      project_id: projectId,
      code: tmp.code,
      name: tmp.name,
      specs: tmp.specs?tmp.specs:'',
      unit: tmp.unit === undefined ? '' : tmp.unit,
      type: tmp.gljType,
      adjCoe:tmp.adjCoe,
      original_code:tmp.code,
      materialType: tmp.materialType,   //三材类别
      materialCoe: tmp.materialCoe,
      base_price: tmp.basePrice,
      market_price: tmp.basePrice,
      from:tmp.from?tmp.from:"std"
  };
  if(gljData.from == 'std' && ext && ext.priceField &&(tmp.priceProperty && tmp.priceProperty[ext.priceField]!= undefined && tmp.priceProperty[ext.priceField]!=null)){
    basePrice = scMathUtil.roundTo(tmp.priceProperty[ext.priceField],-6);
    gljData.base_price = basePrice;
    gljData.market_price = basePrice;
  }
  return gljData;
}

//根据缺少项目工料机的组成物信息，反向生成对应的项目工料机
async function getNewProjectGLJFromMissMixratio(projectID,lessMix,projectGLJMap,newProjectGLJList,ext){
  let lessIDList=[];
  let uniqMap ={};//去重
  let lessStdMix = [];//防止组成物中改了名称等，但是通过glj_id取出来的是还没改前的原始数据
  if(lessMix.length > 0){
    for(let lm of lessMix){
      let parentglj = projectGLJMap[lm.connect_key];
      if(!parentglj) throw `含有组成物工料机${lm.connect_key}，没有找到，添加定额失败`;
      if((parentglj.from == "std" || lm.from == "std") && lm.code!="80CCS"){//车船税特殊处理
        if(!uniqMap[lm.glj_id]){
          lessIDList.push(lm.glj_id);
          uniqMap[lm.glj_id] = lm;
        }
        lessStdMix.push(lm);
      }else {//来自组成物的直接设置    
        lm.from = 'cpt';
        lm.gljType = lm.type;
        let t_mg = getProjectGLJNewData(lm,projectID);
        newProjectGLJList.push(t_mg);
        projectGLJMap[getIndex(lm)] = t_mg;
      }
    }
  }

  if(lessIDList.length > 0){
    let less_stds =  await std_glj_lib_gljList_model.find({'ID':{'$in':lessIDList}}).lean();
    let less_stds_map = {};
    for(let les of  less_stds){
      less_stds_map[les.ID] = les;
    }
    for(let t_l_m of lessStdMix){
      let t_nglj = less_stds_map[t_l_m.glj_id];
      t_nglj.from = 'std';
      //防止组成物中改了名称等，但是通过glj_id取出来的是还没改前的原始数据
      t_nglj.name = t_l_m.name;
      t_nglj.code = t_l_m.code;
      t_nglj.gljType = t_l_m.type;
      t_nglj.specs = t_l_m.specs;
      t_nglj.unit = t_l_m.unit;
      let t_np = getProjectGLJNewData(t_nglj,projectID,ext);
      newProjectGLJList.push(t_np);
      projectGLJMap[getIndex(t_l_m)] = t_np;
    }
  }
  return newProjectGLJList;
}

//找到并返回单价文件信息，如果没有自动插入
async function getUnitPriceData(newProjectGLJList,gljCodes,unitPriceFileId){
  let unitPriceMap = {};
  let newUnitPriceList = [];
  let unitPriceList = await unitPriceModel.find({unit_price_file_id: unitPriceFileId,'code':{'$in':gljCodes}}).lean();
  for(let u of unitPriceList){
    unitPriceMap[getIndex(u)]=u;
  }

  for(let np of newProjectGLJList){
    let pkey = getIndex(np);
    if(unitPriceMap[pkey]) continue;

    let insertData = {
      code: np.code,
      base_price: np.base_price,
      market_price: np.market_price,
      unit_price_file_id: unitPriceFileId,
      name: np.name,
      specs:np.specs?np.specs:'',
      original_code:np.original_code,
      unit:np.unit?np.unit:'',
      type: np.type,
      short_name: np.shortName !== undefined ? np.shortName : '',
      glj_id: np.glj_id,
      is_add:0,
      grossWeightCoe:np.grossWeightCoe,
      purchaseStorageRate:np.purchaseStorageRate,
      offSiteTransportLossRate:np.offSiteTransportLossRate,
      handlingLossRate:np.handlingLossRate
    };
    if(np.from=='cpt') insertData.is_add=1;//如果是来自补充工料机，则都添加新增标记
    if(insertData.code != insertData.original_code) insertData.is_add=1;//添加的时候如果是复制整块来的，可能在源项目中是新增的工料机，这里也要添上(暂时可能还用不到)
    newUnitPriceList.push(insertData);
    unitPriceMap[pkey] = insertData;
  }


  if(newUnitPriceList.length > 0){
    await setIDfromCounter("unit_price",newUnitPriceList);
    await unitPriceModel.insertMany(newUnitPriceList);
  } 

  return [unitPriceMap,newUnitPriceList];
}

function getIndex(obj, pops){
  let t_index = '';
  let k_arr = [];
  if(!pops) pops = ['code','name','specs','unit','type'];
  for (let p of pops) {
      let tmpK = (obj[p] == undefined || obj[p] == null || obj[p] == '') ? 'null' : obj[p];
      k_arr.push(tmpK);
  }
  t_index = k_arr.join("|-|");
  return t_index;
}