const mongoose = require('mongoose');
const uuidV1 = require('uuid/v1');
const _ = require('lodash');
const lossModel = mongoose.model('std_ration_lib_loss_rate_list');
const rationModel = mongoose.model('std_ration_lib_ration_items');

const getLossList = async (libID) => {
  return await lossModel.find({ libID }).lean();
}

const batchUpdateRationLoss = async (libID, updateRateData) => {
  const bulks = [];
  const updateRateMap = {};
  updateRateData.forEach(item => {
    updateRateMap[item.ID] = item;
  });
  const rations = await rationModel.find({ rationRepId: libID }, '-_id ID rationGljList').lean();
  rations.forEach(ration => {
    if (ration.rationGljList && ration.rationGljList.length) {
      let needUpdate = false;
      ration.rationGljList.forEach(rGlj => {
        const matchRateItem = updateRateMap[rGlj.lossRateID];
        if (matchRateItem) {
          needUpdate = true;
          rGlj.lossRateNo = matchRateItem.serialNo;
          rGlj.lossRateName = matchRateItem.name;
          rGlj.lossRate = matchRateItem.rate;
        }
      });
      if (needUpdate) {
        bulks.push({ updateOne: { filter: { ID: ration.ID }, update: { $set: { rationGljList: ration.rationGljList } } } });
      }
    }
  });
  if (bulks.length) {
    await rationModel.bulkWrite(bulks);
  }

}

const save = async (data) => {
  console.log(data);
  const { addArr, updateArr, deleteArr } = data;
  const bulks = [];
  const newData = [];
  if (addArr && addArr.length) {
    addArr.forEach(item => {
      const newItem = { ...item, ID: uuidV1() };
      console.log(newItem);
      newData.push(newItem);
      bulks.push({ insertOne: { document: newItem } });
    });
  }
  const updateRateData = [];
  let libID;
  if (updateArr && updateArr.length) {
    updateArr.forEach(item => {
      if (!libID) {
        libID = item.libID;
      }
      const updateObj = { ...item };
      delete updateObj.ID;
      delete updateObj.libID;
      updateRateData.push({ name: updateObj.name, rate: updateObj.rate, serialNo: updateObj.serialNo, ID: item.ID });
      bulks.push({ updateOne: { filter: { ID: item.ID }, update: { $set: updateObj } } });
    });
  }
  if (deleteArr && deleteArr.length) {
    deleteArr.forEach(item => {
      bulks.push({ deleteOne: { filter: { ID: item.ID } } });
    })
  }
  if (bulks.length) {
    await lossModel.bulkWrite(bulks);
  }
  if (libID && updateRateData.length) {
    await batchUpdateRationLoss(libID, updateRateData)
  }
  return newData;
}


const getItemsBySerialNos = async (libID, serialNos) => {
  return await lossModel.find({ libID, serialNo: { $in: serialNos } }).lean();
}


module.exports = {
  getLossList,
  save,
  getItemsBySerialNos,
}