| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926 | 
							- /**
 
-  * Created by Tony on 2017/4/28.
 
-  */
 
- const mongoose = require('mongoose');
 
- let async = require("async");
 
- let moment = require('moment');
 
- let counter = require('../../../public/counter/counter');
 
- let gljDao = require('./glj_repository');
 
- let rationRepositoryDao = require('./repository_map');
 
- const scMathUtil = require('../../../public/scMathUtil').getUtil();
 
- const rationItemModel = mongoose.model('std_ration_lib_ration_items');
 
- const stdRationLibModel = mongoose.model('std_ration_lib_map');
 
- const compleRationModel = mongoose.model('complementary_ration_items');
 
- import STDGLJListModel from '../../std_glj_lib/models/gljModel';
 
- var rationItemDAO = function(){};
 
- //将消耗量为负的人材机改为正的
 
- rationItemDAO.prototype.toPositive = async function (rationRepId) {
 
-     let rations = await rationItemModel.find({rationRepId: rationRepId, 'rationGljList.consumeAmt': {$lt: 0}});
 
-     let task = [];
 
-     for (let ration of rations) {
 
-         let update = false;
 
-         for (let rGlj of ration.rationGljList) {
 
-             if (rGlj.consumeAmt < 0) {
 
-                 update = true;
 
-                 rGlj.consumeAmt = Math.abs(rGlj.consumeAmt);
 
-             }
 
-         }
 
-         if (update) {
 
-             task.push({updateOne: {filter: {ID: ration.ID}, update: {rationGljList: ration.rationGljList}}});
 
-         }
 
-     }
 
-     if (task.length > 0) {
 
-         await rationItemModel.bulkWrite(task);
 
-     }
 
- };
 
- rationItemDAO.prototype.getRationItemsByLib = async function (rationRepId, showHint = null, returnFields = '') {
 
-     let rationLib = await stdRationLibModel.findOne({ID: rationRepId, deleted: false});
 
-     if(!rationLib){
 
-         return [];
 
-     }
 
-     let startDate = new Date();
 
-     let rations = await rationItemModel.find({rationRepId: rationRepId}, returnFields);
 
-     console.log(`Date: ${new Date() - startDate}====================================`);
 
-     if(!showHint){
 
-         return rations;
 
-     }
 
-     else {
 
-         const stdBillsLibListsModel = new STDGLJListModel();
 
-         const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationLib.gljLib, '-_id ID code name unit gljType');
 
-         let gljMapping = {};
 
-         for(let glj of stdGLJData){
 
-             gljMapping[glj.ID] = glj;
 
-         }
 
-         //设置悬浮
 
-         for(let ration of rations){
 
-             let hintsArr = [];
 
-             //对人材机进行排序
 
-             ration.rationGljList.sort(function (a, b) {
 
-                 let gljA = gljMapping[a.gljId],
 
-                     gljB = gljMapping[b.gljId];
 
-                 if(gljA && gljB){
 
-                     let aV = gljA.gljType + gljA.code,
 
-                         bV = gljB.gljType + gljB.code;
 
-                     if(aV > bV) {
 
-                         return 1;
 
-                     } else if(aV < bV) {
 
-                         return -1;
 
-                     }
 
-                 }
 
-                 return 0;
 
-             });
 
-             for(let rationGlj of ration.rationGljList){
 
-                 let subGlj = gljMapping[rationGlj.gljId];
 
-                 if(subGlj){
 
-                     hintsArr.push(` ${subGlj.code} ${subGlj.name}${subGlj.specs ? '   ' + subGlj.specs : ''}   ${subGlj.unit}   ${rationGlj.consumeAmt}`);
 
-                 }
 
-             }
 
-             hintsArr.push(`基价 元 ${ration.basePrice}`);
 
-             if(ration.jobContent && ration.jobContent.toString().trim() !== ''){
 
-                 hintsArr.push(`工作内容:`);
 
-                 hintsArr = hintsArr.concat(ration.jobContent.split('\n'));
 
-             }
 
-             if(ration.annotation && ration.annotation.toString().trim() !== ''){
 
-                 hintsArr.push(`附注:`);
 
-                 hintsArr = hintsArr.concat(ration.annotation.split('\n'));
 
-             }
 
-             ration._doc.hint = hintsArr.join('<br>');
 
-         }
 
-         return rations;
 
-     }
 
- };
 
- rationItemDAO.prototype.sortToNumber = function (datas) {
 
-     for(let i = 0, len = datas.length; i < len; i++){
 
-         let data = datas[i]._doc;
 
-         if(_exist(data, 'labourPrice')){
 
-             data['labourPrice'] = parseFloat(data['labourPrice']);
 
-         }
 
-         if(_exist(data, 'materialPrice')){
 
-             data['materialPrice'] = parseFloat(data['materialPrice']);
 
-         }
 
-         if(_exist(data, 'machinePrice')){
 
-             data['machinePrice'] = parseFloat(data['machinePrice']);
 
-         }
 
-         if(_exist(data, 'basePrice')){
 
-             data['basePrice'] = parseFloat(data['basePrice']);
 
-         }
 
-         if(_exist(data, 'rationGljList')){
 
-             for(let j = 0, jLen = data['rationGljList'].length; j < jLen; j++){
 
-                 let raGljObj = data['rationGljList'][j]._doc;
 
-                 if(_exist(raGljObj, 'consumeAmt')){
 
-                     raGljObj['consumeAmt'] = parseFloat(raGljObj['consumeAmt']);
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function _exist(data, attr){
 
-         return data && data[attr] !== undefined && data[attr];
 
-     }
 
- };
 
- rationItemDAO.prototype.getRationItemsBySection = async function(rationRepId, sectionId,callback){
 
-     let me = this;
 
-     try {
 
-         let rations = await rationItemModel.find({rationRepId: rationRepId, sectionId: sectionId});
 
-         me.sortToNumber(rations);
 
-         let matchRationIDs = [],
 
-             matchRations = [];
 
-         for (let ration of rations) {
 
-             if (ration.rationTemplateList) {
 
-                 for (let rt of ration.rationTemplateList) {
 
-                     if (rt.rationID) {
 
-                         matchRationIDs.push(rt.rationID);
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         if (matchRationIDs.length > 0) {
 
-             matchRations = await rationItemModel.find({ID: {$in: matchRationIDs}}, '-_id ID code name');
 
-         }
 
-         for (let mr of matchRations) {
 
-             for (let ration of rations) {
 
-                 if (ration.rationTemplateList) {
 
-                     for (let rt of ration.rationTemplateList) {
 
-                         if (rt.rationID && rt.rationID === mr.ID) {
 
-                             rt.code = mr.code ? mr.code : '';
 
-                             rt.name = mr.name ? mr.name : '';
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         callback(false,"Get items successfully", rations);
 
-     } catch (err) {
 
-         console.log(err);
 
-         callback(true, "Fail to get items", "");
 
-     }
 
-   /*  rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
 
-         if(err) callback(true, "Fail to get items", "");
 
-         else {
 
-             me.sortToNumber(data);
 
-             callback(false,"Get items successfully", data);
 
-         }
 
-     })*/
 
- };
 
- rationItemDAO.prototype.mixUpdateRationItems = function(rationLibId, lastOpr, sectionId, updateItems, addItems, rIds, callback){
 
-     var me = this;
 
-     if (updateItems.length == 0 && rIds.length == 0) {
 
-         me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
 
-     } else {
 
-         me.removeRationItems(rationLibId, lastOpr, rIds, function(err, message, docs) {
 
-             if (err) {
 
-                 callback(true, "Fail to remove", false);
 
-             } else {
 
-                 me.updateRationItems(rationLibId, lastOpr, sectionId, updateItems, function(err, results){
 
-                     if (err) {
 
-                         callback(true, "Fail to save", false);
 
-                     } else {
 
-                         if (addItems && addItems.length > 0) {
 
-                             me.addRationItems(rationLibId, lastOpr, sectionId, addItems, callback);
 
-                         } else {
 
-                             callback(false, "Save successfully", results);
 
-                         }
 
-                     }
 
-                 });
 
-             }
 
-         })
 
-     }
 
- };
 
- rationItemDAO.prototype.removeRationItems = function(rationLibId, lastOpr, rIds,callback){
 
-     if (rIds.length > 0) {
 
-         rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
 
-             if (err) {
 
-                 callback(true, "Fail to remove", false);
 
-             } else {
 
-                 rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
 
-                     if(!err){
 
-                         rationItemModel.update({rationRepId: rationLibId}, {$pull: {rationTemplateList: {rationID: {$in: rIds}}}}, function (theErr) {
 
-                             if (!theErr) {
 
-                                 callback(false, "Remove successfully", docs);
 
-                             } else {
 
-                                 callback(true, "Fail to remove", false);
 
-                             }
 
-                         });
 
-                     } else {
 
-                         callback(true, "Fail to remove", false);
 
-                     }
 
-                 })
 
-             }
 
-         })
 
-     } else {
 
-         callback(false, "No records were deleted!", null);
 
-     }
 
- };
 
- rationItemDAO.prototype.getRationItemsByCode = function(repId, code,callback){
 
-     rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$or": [{"isDeleted": null}, {"isDeleted": false}]},function(err,data){
 
-         if(err) callback(true, "Fail to get items", "")
 
-         else callback(false,"Get items successfully", data);
 
-     })
 
- };
 
- rationItemDAO.prototype.findRation = function (repId, keyword, callback) {
 
-     var filter = {
 
-         'rationRepId': repId,
 
-         '$and': [{
 
-             '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
 
-         }, {
 
-             '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
 
-         }]
 
-     };
 
-     rationItemModel.find(filter, function (err, data) {
 
-         if (err) {
 
-             callback(true, 'Fail to find ration', null);
 
-         } else {
 
-             callback(false, '', data);
 
-         }
 
-     })
 
- }
 
- rationItemDAO.prototype.getRationItem = async function (repId, code) {
 
-     let ration = await rationItemModel.findOne({rationRepId: repId, code: code});
 
-     return ration;
 
- };
 
- rationItemDAO.prototype.addRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
 
-     if (items && items.length > 0) {
 
-         counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
 
-             var maxId = result.sequence_value;
 
-             var arr = [];
 
-             for (var i = 0; i < items.length; i++) {
 
-                 var obj = new rationItemModel(items[i]);
 
-                 obj.ID = (maxId - (items.length - 1) + i);
 
-                 obj.sectionId = sectionId;
 
-                 obj.rationRepId = rationLibId;
 
-                 arr.push(obj);
 
-             }
 
-             rationItemModel.collection.insert(arr, null, function(err, docs){
 
-                 if (err) {
 
-                     callback(true, "Fail to save", false);
 
-                 } else {
 
-                     rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
 
-                         if(err){
 
-                             callback(true, "Fail to sava operator", false);
 
-                         }
 
-                         else{
 
-                             callback(false, "Save successfully", docs);
 
-                         }
 
-                     })
 
-                 }
 
-             })
 
-         });
 
-     } else {
 
-         callback(true, "Source error!", false);
 
-     }
 
- };
 
- rationItemDAO.prototype.updateRationItems = function(rationLibId, lastOpr, sectionId, items,callback){
 
-     console.log('enter============');
 
-     var functions = [];
 
-     for (var i=0; i < items.length; i++) {
 
-         functions.push((function(doc) {
 
-             return function(cb) {
 
-                 var filter = {};
 
-                 if (doc.ID) {
 
-                     filter.ID = doc.ID;
 
-                 } else {
 
-                     filter.sectionId = sectionId;
 
-                     if (rationLibId) filter.rationRepId = rationLibId;
 
-                     filter.code = doc.code;
 
-                 }
 
-                 rationItemModel.update(filter, doc, cb);
 
-             };
 
-         })(items[i]));
 
-     }
 
-     functions.push((function () {
 
-         return function (cb) {
 
-             rationRepositoryDao.updateOprArr({ID: rationLibId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
 
-                 if(err){
 
-                     cb(err);
 
-                 }
 
-                 else{
 
-                     cb(null);
 
-                 }
 
-             });
 
-         }
 
-     })());
 
-     async.parallel(functions, function(err, results) {
 
-         callback(err, results);
 
-     });
 
- };
 
- //ration round func
 
- function round(v,e){
 
-     var t=1;
 
-     for(;e>0;t*=10,e--);
 
-     for(;e<0;t/=10,e++);
 
-     return Math.round(v*t)/t;
 
- }
 
- rationItemDAO.prototype.updateRationBasePrc = function (basePrcArr, callback) {
 
-     async.each(basePrcArr, function (basePrcObj, finalCb) {
 
-         let adjGljId = basePrcObj.gljId, adjBasePrice = basePrcObj.basePrice, adjGljType = basePrcObj.gljType;
 
-         async.waterfall([
 
-             function (cb) {
 
-                 if(typeof basePrcObj.delete !== 'undefined' && basePrcObj.delete === 1){
 
-                     rationItemModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, result) {
 
-                         if(err){
 
-                             cb(err);
 
-                         }
 
-                         else{
 
-                             //删除
 
-                             rationItemModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
 
-                                 if(err){
 
-                                     cb(err);
 
-                                 }
 
-                                 else{
 
-                                     //补充定额
 
-                                     compleRationModel.find({'rationGljList.gljId': adjGljId},{ID: 1, rationGljList: 1}, function (err, compleRst) {
 
-                                         if(err){
 
-                                             cb(err);
 
-                                         }
 
-                                         else {
 
-                                             compleRationModel.update({'rationGljList.gljId': adjGljId}, {$pull: {rationGljList: {gljId: adjGljId}}}, {multi: true}, function (err) {
 
-                                                 if(err){
 
-                                                     cb(err);
 
-                                                 }
 
-                                                 else {
 
-                                                     for(let i = 0, len = compleRst.length; i < len; i++){
 
-                                                         compleRst[i]._doc.type = 'complementary';
 
-                                                     }
 
-                                                     cb(null, result.concat(compleRst));
 
-                                                 }
 
-                                             });
 
-                                         }
 
-                                     });
 
-                                 }
 
-                             });
 
-                         }
 
-                     });
 
-                 }
 
-                 else{
 
-                     rationItemModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, result) {
 
-                         if(err){
 
-                             cb(err);
 
-                         }
 
-                         else{
 
-                             compleRationModel.find({'rationGljList.gljId': adjGljId}, {ID: 1, rationGljList: 1}, function (err, compleRst) {
 
-                                 if(err){
 
-                                     cb(err);
 
-                                 }
 
-                                 else {
 
-                                     for(let i = 0, len = compleRst.length; i < len; i++){
 
-                                         compleRst[i]._doc.type = 'complementary';
 
-                                     }
 
-                                     cb(null, result.concat(compleRst));
 
-                                 }
 
-                             });
 
-                         }
 
-                     });
 
-                 }
 
-             },
 
-             function (result, cb) {
 
-                 let compleRTasks = [], stdRTasks = [];
 
-                 //重算时需要用到的所有工料机,一次性取
 
-                 let compleGljIds = [], stdGljIds = [];
 
-                 for(let ration of result){
 
-                     for(let glj of ration.rationGljList){
 
-                         if(glj.type !== undefined && glj.type === 'complementary'){
 
-                             compleGljIds.push(glj.gljId);
 
-                         }
 
-                         else {
 
-                             stdGljIds.push(glj.gljId);
 
-                         }
 
-                     }
 
-                 }
 
-                 gljDao.getStdCompleGljItems(compleGljIds, stdGljIds, function (err, allGljs) {
 
-                     if(err){
 
-                         cb(err);
 
-                     }
 
-                     else {
 
-                         let gljIndex = {};
 
-                         for(let glj of allGljs){
 
-                             gljIndex[glj.ID] = glj;
 
-                         }
 
-                         async.each(result, function (rationItem, ecb) {
 
-                             let rationGljList = rationItem.rationGljList;
 
-                             let gljArr = [];
 
-                             for(let i=0; i<rationGljList.length; i++){
 
-                                 let theGlj = gljIndex[rationGljList[i].gljId];
 
-                                 if(theGlj !== undefined && theGlj){
 
-                                     if(theGlj.ID === adjGljId){
 
-                                         gljArr.push({gljId: theGlj.ID, basePrice: adjBasePrice, consumeAmt: rationGljList[i].consumeAmt});
 
-                                     } else {
 
-                                         if(theGlj.priceProperty && Object.keys(theGlj.priceProperty).length > 0){
 
-                                             let priceKeys = Object.keys(theGlj.priceProperty);
 
-                                             gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.priceProperty[priceKeys[0]]), consumeAmt: rationGljList[i].consumeAmt});
 
-                                         } else {
 
-                                             gljArr.push({gljId: theGlj.ID, basePrice: parseFloat(theGlj.basePrice), consumeAmt: rationGljList[i].consumeAmt});
 
-                                         }
 
-                                     }
 
-                                 }
 
-                             }
 
-                             //recalculate the price of ration
 
-                             let basePrice = 0;
 
-                             gljArr.forEach(function (gljItem) {
 
-                                 basePrice += gljItem.basePrice * gljItem.consumeAmt;
 
-                             });
 
-                             basePrice = scMathUtil.roundTo(basePrice, 0);
 
-                             let task = {
 
-                                 updateOne: {
 
-                                     filter: {
 
-                                         ID: rationItem.ID
 
-                                     },
 
-                                     update: {
 
-                                         basePrice: basePrice.toString()
 
-                                     }
 
-                                 }
 
-                             };
 
-                             //updateDataBase
 
-                             if(rationItem._doc.type !== undefined && rationItem._doc.type === 'complementary'){
 
-                                 compleRTasks.push(task);
 
-                                 ecb(null);
 
-                             }
 
-                             else {
 
-                                 stdRTasks.push(task);
 
-                                 ecb(null);
 
-                             }
 
-                         }, async function(err){
 
-                             if(err){
 
-                                 cb(err);
 
-                             }
 
-                             else {
 
-                                 //do sth
 
-                                 try{
 
-                                     if(compleRTasks.length > 0){
 
-                                         await compleRationModel.bulkWrite(compleRTasks);
 
-                                     }
 
-                                     if(stdRTasks.length > 0){
 
-                                         await rationItemModel.bulkWrite(stdRTasks);
 
-                                     }
 
-                                 }
 
-                                 catch(e){
 
-                                     cb(err);
 
-                                 }
 
-                                 cb(null);
 
-                             }
 
-                         });
 
-                     }
 
-                 });
 
-             },
 
-         ], function (err) {
 
-             if(err){
 
-                 finalCb(err);
 
-             }
 
-             else{
 
-                 finalCb(null);
 
-             }
 
-         });
 
-     }, function (err) {
 
-         if(err){
 
-             callback(err, 'Error');
 
-         }
 
-         else{
 
-             callback(null, '');
 
-         }
 
-     });
 
- };
 
- rationItemDAO.prototype.getRationGljIds = function (data, callback) {
 
-     let repId = data.repId;
 
-     rationItemModel.find({rationRepId: repId}, function (err, result) {
 
-         if(err){
 
-             callback(err, 'Error', null);
 
-         }
 
-         else{
 
-             let rstIds = [], newRst = [];
 
-             result.forEach(function (data) {
 
-                 if(data.rationGljList.length >0){
 
-                     data.rationGljList.forEach(function (gljObj) {
 
-                         rstIds.push(gljObj.gljId);
 
-                     })
 
-                 }
 
-             });
 
-             for(let i= 0; i< rstIds.length; i++){
 
-                 if(newRst.indexOf(rstIds[i]) === -1){
 
-                     newRst.push(rstIds[i]);
 
-                 }
 
-             }
 
-             callback(null, '', newRst);
 
-         }
 
-     });
 
- };
 
- rationItemDAO.prototype.getRationsCodes = function (data, callback) {
 
-     let repId = data.repId;
 
-     rationItemModel.find({rationRepId: repId, isDeleted: false}, function (err, result) {
 
-         if(err){
 
-             callback(err, 'Error', null);
 
-         }
 
-         else{
 
-             let rstCodes = [];
 
-             result.forEach(function (rationItem) {
 
-                 rstCodes.push(rationItem.code);
 
-             });
 
-             callback(null, 'get all rationCodes success', rstCodes);
 
-         }
 
-     })
 
- };
 
- rationItemDAO.prototype.updateJobContent = function (lastOpr, repId, updateArr, callback) {
 
-     rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
 
-         async.each(updateArr, function (obj, cb) {
 
-             rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {jobContent: obj.jobContent}}, function (err) {
 
-                 if(err){
 
-                     cb(err);
 
-                 }
 
-                 else{
 
-                     cb(null);
 
-                 }
 
-             })
 
-         }, function (err) {
 
-             if(err){
 
-                 callback(err);
 
-             }
 
-             else{
 
-                 callback(null);
 
-             }
 
-         });
 
-     });
 
- }
 
- rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr, callback) {
 
-     rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
 
-         async.each(updateArr, function (obj, cb) {
 
-             rationItemModel.update({rationRepId: repId, code: obj.code}, {$set: {annotation: obj.annotation}}, function (err) {
 
-                 if(err){
 
-                     cb(err);
 
-                 }
 
-                 else{
 
-                     cb(null);
 
-                 }
 
-             })
 
-         }, function (err) {
 
-             if(err){
 
-                 callback(err);
 
-             }
 
-             else{
 
-                 callback(null);
 
-             }
 
-         });
 
-     });
 
- };
 
- //更新定额下模板关联
 
- rationItemDAO.prototype.updateRationTemplate = async function (rationRepId, rationID, templateData) {
 
-     //自动匹配定额
 
-     let matachCodes = [],
 
-         matchRations = [];
 
-     //要保存的数据
 
-     let saveData = [];
 
-     for (let data of templateData) {
 
-         if (data.code) {
 
-             matachCodes.push(data.code);
 
-         }
 
-     }
 
-     matachCodes = Array.from(new Set(matachCodes));
 
-     if (matachCodes.length > 0) {
 
-         matchRations = await rationItemModel.find({rationRepId: rationRepId, code: {$in: matachCodes}}, '-_id ID code name');
 
-     }
 
-     let validData = [];
 
-     //设置展示数据
 
-     for (let data of templateData) {
 
-         let match = false;
 
-         for (let ration of matchRations) {
 
-             if (data.code && data.code === ration.code) {
 
-                 match = true;
 
-                 data.name = ration.name;
 
-                 data.rationID = ration.ID;
 
-                 break;
 
-             }
 
-         }
 
-         if (!match) {
 
-             data.code = '';
 
-             data.name = '';
 
-         }
 
-         if (data.type || data.code || data.name || data.billsLocation) {
 
-             validData.push(data);
 
-         }
 
-     }
 
-     for (let data of validData) {
 
-         saveData.push({rationID: data.rationID ? data.rationID : null, type: data.type, billsLocation: data.billsLocation});
 
-     }
 
-     //更新
 
-     await rationItemModel.update({ID: rationID}, {$set: {rationTemplateList: saveData}});
 
-     return validData;
 
- };
 
- //计算导入数据的价格
 
- rationItemDAO.prototype.calcForRation = function (stdGljList, ration) {
 
-     let rationGljList = ration.rationGljList;
 
-     let basePrice = 0;
 
-     for(let rationGlj of rationGljList) {
 
-         let glj = stdGljList[rationGlj.gljId];
 
-         if (glj) {
 
-             basePrice += glj.basePrice * rationGlj.consumeAmt;
 
-         }
 
-     }
 
-     ration.basePrice = scMathUtil.roundTo(basePrice, 0).toString();
 
- };
 
- /**
 
-  * 根据条件获取定额数据
 
-  *
 
-  * @param {Object} condition
 
-  * @param {Object} fields
 
-  * @param {String} indexBy
 
-  * @return {Promise|Array}
 
-  */
 
- rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
 
-     let result = [];
 
-     if (Object.keys(condition).length <= 0) {
 
-         return result;
 
-     }
 
-     result = await rationItemModel.find(condition, fields).sort({code: 1});
 
-     if (indexBy !== null && result.length > 0) {
 
-         let tmpResult = {};
 
-         for(let tmp of result) {
 
-             tmpResult[tmp[indexBy]] = tmp;
 
-         }
 
-         result = tmpResult;
 
-     }
 
-     return result;
 
- };
 
- /**
 
-  * 从excel中批量新增数据
 
-  *
 
-  * @param {Number} rationRepId
 
-  * @param {Array} data
 
-  * @return {bool}
 
-  */
 
- rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
 
-     if (data.length <= 0) {
 
-         return false;
 
-     }
 
-     // 获取定额库相关数据
 
-     const rationRepository = await rationRepositoryDao.getRepositoryById(rationRepId);
 
-     if (rationRepository.length !== 1 || rationRepository[0].gljLib === undefined) {
 
-         return false;
 
-     }
 
-     // 获取标准工料机库数据
 
-     const stdBillsLibListsModel = new STDGLJListModel();
 
-     const stdGLJData = await stdBillsLibListsModel.getGljItemsByRepId(rationRepository[0].gljLib);
 
-     // 整理标准工料机库数据
 
-     let stdGLJList = {};
 
-     let stdGLJListByID = {};
 
-     for (const tmp of stdGLJData) {
 
-         stdGLJList[tmp.code.toString()] = tmp.ID;
 
-         stdGLJListByID[tmp.ID] = tmp;
 
-     }
 
-     let lastData = {};
 
-     const rationData = [];
 
-     // 编码列表,用于查找库中是否有对应数据
 
-     let rationCodeList = [];
 
-     let gljCodeList = [];
 
-     // 插入失败的工料机列表(用于提示)
 
-     this.failGLJList = [];
 
-     for (const tmp of data) {
 
-         if (tmp.length <= 0) {
 
-             continue;
 
-         }
 
-         // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
 
-         if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
 
-             // 如果不存在对应的工料机库数据则跳过
 
-             if (stdGLJList[tmp[1]] === undefined) {
 
-                 const failString = '定额' + lastData.code + '下的' + tmp[1];
 
-                 this.failGLJList.push(failString);
 
-                 continue;
 
-             }
 
-             const tmpRationGlj = {
 
-                 gljId: stdGLJList[tmp[1]],
 
-                 consumeAmt: tmp[4],
 
-                 proportion: 0,
 
-             };
 
-             lastData.rationGljList.push(tmpRationGlj);
 
-             if (gljCodeList.indexOf(tmp[1]) < 0) {
 
-                 gljCodeList.push(tmp[1]);
 
-             }
 
-             continue;
 
-         }
 
-         if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
 
-             rationData.push(lastData);
 
-         }
 
-         // 组装数据
 
-         lastData = {
 
-             code: tmp[1],
 
-             name: tmp[2],
 
-             unit: tmp[3],
 
-             caption: tmp[2],
 
-             rationRepId: rationRepId,
 
-             sectionId: 0,
 
-             labourPrice: '0',
 
-             materialPrice: '0',
 
-             machinePrice: '0',
 
-             basePrice: '0',
 
-             rationGljList: []
 
-         };
 
-         // 防止重复加入
 
-         if (rationCodeList.indexOf(tmp[1]) < 0) {
 
-             rationCodeList.push(tmp[1]);
 
-         }
 
-     }
 
-     // 最后一个入数组
 
-     rationData.push(lastData);
 
-     // 查找数据库中是否已存在待插入数据
 
-     const condition = {
 
-         rationRepId: rationRepId,
 
-         code: { $in: rationCodeList }
 
-     };
 
-     const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
 
-     // 过滤插入数据
 
-     let insertData = [];
 
-     //已存在定额,则更新价格及rationGLjList字段
 
-     let updateData = [];
 
-     for (const ration of rationData) {
 
-         if (existCodeList[ration.code] !== undefined) {
 
-             updateData.push(ration);
 
-             continue;
 
-         }
 
-         insertData.push(ration);
 
-     }
 
-     //更新定额
 
-     let updateBulk = [];
 
-     for(let ration of updateData){
 
-         this.calcForRation(stdGLJListByID, ration);
 
-         updateBulk.push({
 
-             updateOne: {
 
-                 filter: {rationRepId: rationRepId, code: ration.code},
 
-                 update: {$set: {rationGljList: ration.rationGljList, basePrice: ration.basePrice}}
 
-             }
 
-         });
 
-     }
 
-     //更新数据库
 
-     if(updateBulk.length > 0){
 
-         await rationItemModel.bulkWrite(updateBulk);
 
-     }
 
-     // 如果都已经存在,直接返回
 
-     if (insertData.length <= 0) {
 
-         return true;
 
-     }
 
-     //计算价格
 
-     for(let ration of insertData){
 
-         this.calcForRation(stdGLJListByID, ration);
 
-     }
 
-     // 组织id
 
-     const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
 
-     let maxId = counterInfo.sequence_value;
 
-     maxId = parseInt(maxId);
 
-     let count = 0;
 
-     for (const index in insertData) {
 
-         insertData[index].ID = maxId - (insertData.length - 1) + count;
 
-         count++;
 
-     }
 
-     // 插入数据库
 
-     const result = await rationItemModel.create(insertData);
 
-     return result.length > 0;
 
- };
 
- /**
 
-  * 导出到excel的数据
 
-  *
 
-  * @param {Number} rationRepId
 
-  * @return {Array}
 
-  */
 
- rationItemDAO.prototype.exportExcelData = async function(rationRepId) {
 
-     const condition = {
 
-         rationRepId: rationRepId
 
-     };
 
-     // @todo 限制导出的数量以防内存溢出
 
-     const rationDataList = await this.getRationItemByCondition(condition, ['name', 'code', 'ID', 'sectionId', 'feeType', 'caption', 'basePrice']);
 
-     // 整理数据
 
-     let rationData = [];
 
-     for (const tmp of rationDataList) {
 
-         const sectionId = tmp.sectionId <= 0 || tmp.sectionId === undefined ? null : tmp.sectionId;
 
-         const feeType = tmp.feeType === '' || tmp.feeType === undefined ? null : tmp.feeType;
 
-         const ration = [sectionId, feeType, tmp.ID, tmp.code, tmp.name, tmp.caption, tmp.basePrice];
 
-         rationData.push(ration);
 
-     }
 
-     //根据编号排序,优先级:number-number-..., number, Anumber....
 
-     /*let regConnector = /-/g,
 
-         regLetter = /[a-z,A-Z]/g,
 
-         regNum = /\d+/g;
 
-     rationData.sort(function (a, b) {
 
-         let aCode = a[3],
 
-             bCode = b[3],
 
-             rst = 0;
 
-         function compareConnector(arrA, arrB) {
 
-             let lessArr = arrA.length <= arrB ? arrA : arrB;
 
-             for (let i = 0; i < lessArr.length; i++) {
 
-                 let result = compareUnit(arrA[i], arrB[i]);
 
-                 if (result !== 0) {
 
-                     return result;
 
-                 } else {
 
-                 }
 
-             }
 
-             function compareUnit(uA, uB) {
 
-                 let uAV = parseFloat(uA),
 
-                     uBV = parseFloat(uB);
 
-                 if (uAV > uBV) {
 
-                     return 1;
 
-                 } else if (uAV < uBV) {
 
-                     return -1;
 
-                 }
 
-                 return 0;
 
-             }
 
-         }
 
-         if (regConnector.test(a) && !regConnector.test(b)) {
 
-             rst = -1;
 
-         } else if (!regConnector.test(a) && regConnector.test(b)) {
 
-             rst = 1;
 
-         } else if (regConnector.test(a) && regConnector.test(b)) {
 
-         }
 
-     });
 
-     rationData.sort(function (a, b) {
 
-         let aCode = a[3],
 
-             bCode = b[3],
 
-             rst = 0,
 
-             splitA = aCode.split('-'),
 
-             splitB = bCode.split('-');
 
-         if(splitA[0] > splitB[0]){
 
-             rst = 1;
 
-         }
 
-         else if(splitA[0] < splitB[0]){
 
-             rst = -1;
 
-         }
 
-         else {
 
-             if(splitA[1] && splitB[1]){
 
-                 let floatA = parseFloat(splitA[1]),
 
-                     floatB = parseFloat(splitB[1]);
 
-                 if(floatA > floatB){
 
-                     rst = 1;
 
-                 }
 
-                 else if(floatA < floatB){
 
-                     rst = -1;
 
-                 }
 
-             }
 
-         }
 
-         return rst;
 
-     });*/
 
-     const excelData = [['树ID', '取费专业', '定额ID', '定额编码', '定额名', '定额显示名称', '基价']];
 
-     excelData.push.apply(excelData, rationData);
 
-     return excelData;
 
- };
 
- /**
 
-  * 批量更改章节id
 
-  *
 
-  * @param {Object} data
 
-  * @return {bool}
 
-  */
 
- rationItemDAO.prototype.batchUpdateSectionIdFromExcel = async function(data) {
 
-     if (data.length <= 0) {
 
-         return false;
 
-     }
 
-     // 批量执行update
 
-     let bulkOprs = [];
 
-     for (const tmp of data) {
 
-         let rationId = parseInt(tmp[2]);
 
-         rationId = isNaN(rationId) || rationId <= 0 ? 0 : rationId;
 
-         let sectionId = parseInt(tmp[0]);
 
-         sectionId = isNaN(sectionId) || sectionId <= 0 ? 0 : sectionId;
 
-         // 取费专业
 
-         let feeType = tmp[1] ? parseInt(tmp[1]) : null;
 
-         feeType = isNaN(feeType) || feeType <= 0 ? null : feeType;
 
-         let name = tmp[4];
 
-         name = name ? name : '';
 
-         let caption = tmp[5];
 
-         caption = caption ? caption : '';
 
-         if (sectionId <= 0 || rationId <= 0) {
 
-             continue;
 
-         }
 
-         bulkOprs.push({updateOne: {filter: {ID: rationId}, update: {$set: {sectionId: sectionId, feeType: feeType, name: name, caption: caption}}}});
 
-     }
 
-     if(bulkOprs.length <= 0){
 
-         throw '无有效数据(树ID、定额ID不为空、且为数值)';
 
-     }
 
-     await rationItemModel.bulkWrite(bulkOprs);
 
- };
 
- module.exports = new rationItemDAO();
 
 
  |