| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064 | 
							- 'use strict';
 
- /**
 
-  * 辅助方法扩展
 
-  *
 
-  * @author CaiAoLin
 
-  * @date 2017/9/28
 
-  * @version
 
-  */
 
- const moment = require('moment');
 
- const zeroRange = 0.0000000001;
 
- const fs = require('fs');
 
- const path = require('path');
 
- const streamToArray = require('stream-to-array');
 
- const _ = require('lodash');
 
- const bc = require('../lib/base_calc.js');
 
- const Decimal = require('decimal.js');
 
- Decimal.set({ precision: 50, defaults: true });
 
- const SMS = require('../lib/sms');
 
- module.exports = {
 
-     _: _,
 
-     /**
 
-      * 生成随机字符串
 
-      *
 
-      * @param {Number} length - 需要生成字符串的长度
 
-      * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
 
-      * @return {String} - 返回生成结果
 
-      */
 
-     generateRandomString(length, type = 1) {
 
-         length = parseInt(length);
 
-         length = isNaN(length) ? 1 : length;
 
-         let randSeed = [];
 
-         let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 
-         let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
 
-             'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
 
-             'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
 
-         switch (type) {
 
-             case 1:
 
-                 randSeed = stringSeed.concat(numberSeed);
 
-                 stringSeed = numberSeed = null;
 
-                 break;
 
-             case 2:
 
-                 randSeed = numberSeed;
 
-                 break;
 
-             case 3:
 
-                 randSeed = stringSeed;
 
-                 break;
 
-             default:
 
-                 break;
 
-         }
 
-         const seedLength = randSeed.length - 1;
 
-         let result = '';
 
-         for (let i = 0; i < length; i++) {
 
-             const index = Math.ceil(Math.random() * seedLength);
 
-             result += randSeed[index];
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 字节转换
 
-      * @param {number} bytes - 字节
 
-      * @return {string} - 大小
 
-      */
 
-     bytesToSize(bytes) {
 
-         if (parseInt(bytes) === 0) return '0 B';
 
-         const k = 1024;
 
-         const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
 
-         const i = Math.floor(Math.log(bytes) / Math.log(k));
 
-         // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
 
-         return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
 
-     },
 
-     /**
 
-      * 浮点乘法计算
 
-      * @param {number} arg1 - 乘数
 
-      * @param {number} arg2 - 被乘数
 
-      * @return {string} - 结果
 
-      */
 
-     accMul(arg1, arg2) {
 
-         if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
 
-             return '';
 
-         }
 
-         let m = 0;
 
-         const s1 = arg1.toString();
 
-         const s2 = arg2.toString();
 
-         try {
 
-             m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
 
-         } catch (e) {
 
-             throw e;
 
-         }
 
-         try {
 
-             m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
 
-         } catch (e) {
 
-             throw e;
 
-         }
 
-         return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
 
-     },
 
-     accAdd(arg1, arg2) {
 
-         let r1;
 
-         let r2;
 
-         try {
 
-             r1 = arg1.toString().split('.')[1].length;
 
-         } catch (e) {
 
-             r1 = 0;
 
-         }
 
-         try {
 
-             r2 = arg2.toString().split('.')[1].length;
 
-         } catch (e) {
 
-             r2 = 0;
 
-         }
 
-         const c = Math.abs(r1 - r2);
 
-         const m = Math.pow(10, Math.max(r1, r2));
 
-         if (c > 0) {
 
-             const cm = Math.pow(10, c);
 
-             if (r1 > r2) {
 
-                 arg1 = Number(arg1.toString().replace('.', ''));
 
-                 arg2 = Number(arg2.toString().replace('.', '')) * cm;
 
-             } else {
 
-                 arg1 = Number(arg1.toString().replace('.', '')) * cm;
 
-                 arg2 = Number(arg2.toString().replace('.', ''));
 
-             }
 
-         } else {
 
-             arg1 = Number(arg1.toString().replace('.', ''));
 
-             arg2 = Number(arg2.toString().replace('.', ''));
 
-         }
 
-         return (arg1 + arg2) / m;
 
-     },
 
-     // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
 
-     roundNum(val, decimals) {
 
-         if (val === '' || val === null) {
 
-             return '';
 
-         }
 
-         if (val !== '') {
 
-             val = parseFloat(val);
 
-             if (decimals < 1) {
 
-                 val = (Math.round(val)).toString();
 
-             } else {
 
-                 let num = val.toString();
 
-                 if (num.lastIndexOf('.') === -1) {
 
-                     // num += '.';
 
-                     // num += this.makezero(decimals);
 
-                     val = num;
 
-                 } else {
 
-                     const valdecimals = num.split('.')[1].length;
 
-                     if (parseInt(valdecimals) < parseInt(decimals)) {
 
-                         // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
 
-                         val = num;
 
-                     } else if (parseInt(valdecimals) > parseInt(decimals)) {
 
-                         val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
 
-                         let num = val.toString();
 
-                         if (num.lastIndexOf('.') === -1) {
 
-                             // num += '.';
 
-                             // num += this.makezero(decimals);
 
-                             val = num;
 
-                         } else {
 
-                             const valdecimals = num.split('.')[1].length;
 
-                             if (parseInt(valdecimals) < parseInt(decimals)) {
 
-                                 // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
 
-                                 val = num;
 
-                             }
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         return val;
 
-     },
 
-     // 生成num位的0
 
-     makezero(num) {
 
-         const arr = new Array(num);
 
-         for (let i = 0; i < num; i++) {
 
-             arr[i] = 0;
 
-         }
 
-         return arr.join('');
 
-     },
 
-     // 生成num位的10倍数
 
-     makemultiple(num) {
 
-         return Math.pow(10, parseInt(num));
 
-     },
 
-     // 根据单位获取小数位数
 
-     findDecimal(unit) {
 
-         let value = 3;
 
-         if (unit !== '') {
 
-             value = this.ctx.tender.info.precision.other.value;
 
-             const changeUnits = this.ctx.tender.info.precision;
 
-             for (const d in changeUnits) {
 
-                 if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
 
-                     value = changeUnits[d].value;
 
-                     break;
 
-                 }
 
-             }
 
-         }
 
-         return value;
 
-     },
 
-     /**
 
-      * 显示排序符号
 
-      *
 
-      * @param {String} field - 字段名称
 
-      * @return {String} - 返回字段排序的符号
 
-      */
 
-     showSortFlag(field) {
 
-         const sort = this.ctx.sort;
 
-         if (!(sort instanceof Array) || sort.length !== 2) {
 
-             return '';
 
-         }
 
-         sort[1] = sort[1].toUpperCase();
 
-         return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
 
-     },
 
-     /**
 
-      * 判断是否为ajax请求
 
-      *
 
-      * @param {Object} request - 请求数据
 
-      * @return {boolean} 判断结果
 
-      */
 
-     isAjax(request) {
 
-         let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
 
-         headerInfo = headerInfo.toLowerCase();
 
-         return headerInfo === 'xmlhttprequest';
 
-     },
 
-     /**
 
-      * 模拟发送请求
 
-      *
 
-      * @param {String} url - 请求地址
 
-      * @param {Object} data - 请求数据
 
-      * @param {String} type - 请求类型(POST) POST | GET
 
-      * @param {String} dataType - 数据类型 json|text
 
-      * @return {Object} - 请求结果
 
-      */
 
-     async sendRequest(url, data, type = 'POST', dataType = 'json') {
 
-         // 发起请求
 
-         try {
 
-             const response = await this.ctx.curl(url, {
 
-                 method: type,
 
-                 data,
 
-                 dataType,
 
-             });
 
-             if (response.status !== 200) {
 
-                 throw '请求失败';
 
-             }
 
-             return response.data;
 
-         } catch (err) {
 
-             throw '请求失败';
 
-         }
 
-     },
 
-     /**
 
-      * 深度验证数据
 
-      *
 
-      * @param {Object} rule - 数据规则
 
-      * @return {void}
 
-      */
 
-     validate(rule) {
 
-         // 先用内置的验证器验证数据
 
-         this.ctx.validate(rule);
 
-         // 然后再验证是否有多余的数据
 
-         const postData = this.ctx.request.body;
 
-         delete postData._csrf;
 
-         const postDataKey = Object.keys(postData);
 
-         const ruleKey = Object.keys(rule);
 
-         // 自动增加字段则填充上,以防判断出错
 
-         if (postData.create_time !== undefined) {
 
-             ruleKey.push('create_time');
 
-         }
 
-         for (const tmp of postDataKey) {
 
-             // 规则里面没有定义则抛出异常
 
-             if (ruleKey.indexOf(tmp) < 0) {
 
-                 throw '参数不正确';
 
-             }
 
-         }
 
-     },
 
-     /**
 
-      * 拆分path
 
-      *
 
-      * @param {String|Array} paths - 拆分字符
 
-      * @param {String} symbol - 拆分符号
 
-      * @return {Array} - 拆分结果
 
-      */
 
-     explodePath(paths, symbol = '-') {
 
-         const result = [];
 
-         paths = paths instanceof Array ? paths : [paths];
 
-         for (const path of paths) {
 
-             // 拆分数据
 
-             const pathArray = path.split(symbol);
 
-             // 用户缓存循环的数据
 
-             const tmpArray = [];
 
-             for (const tmp of pathArray) {
 
-                 // 每次循环都追加一个数据进去
 
-                 tmpArray.push(tmp);
 
-                 const tmpPathString = tmpArray.join(symbol);
 
-                 // 判断是否已经存在有对应数据
 
-                 if (result.indexOf(tmpPathString) >= 0) {
 
-                     continue;
 
-                 }
 
-                 result.push(tmpPathString);
 
-             }
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 基于obj, 拷贝sObj中的内容
 
-      * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
 
-      * @param obj
 
-      * @param sObj
 
-      * @returns {any}
 
-      */
 
-     updateObj(obj, sObj) {
 
-         if (!obj) {
 
-             return JSON.parse(JSON.stringify(sObj));
 
-         }
 
-         const result = JSON.parse(JSON.stringify(obj));
 
-         if (sObj) {
 
-             for (const prop in sObj) {
 
-                 result[prop] = sObj[prop];
 
-             }
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 在数组中查找
 
-      * @param {Array} arr
 
-      * @param name -
 
-      * @param value
 
-      * @returns {*}
 
-      */
 
-     findData(arr, name, value) {
 
-         if (!arr instanceof Array) {
 
-             throw '该方法仅用于数组查找';
 
-         }
 
-         if (arr.length === 0) { return undefined; }
 
-         for (const data of arr) {
 
-             if (data[name] == value) {
 
-                 return data;
 
-             }
 
-         }
 
-         return undefined;
 
-     },
 
-     /**
 
-      * 检查数字是否为0
 
-      * @param {Number} value
 
-      * @return {boolean}
 
-      */
 
-     checkZero(value) {
 
-         return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
 
-     },
 
-     /**
 
-      * 检查数字是否相等
 
-      * @param {Number} value1
 
-      * @param {Number} value2
 
-      * @returns {boolean}
 
-      */
 
-     checkNumberEqual(value1, value2) {
 
-         if (value1 && value2) {
 
-             return Math.abs(value2 - value1) > zeroRange;
 
-         } else {
 
-             return (!value1 && !value2)
 
-         }
 
-     },
 
-     /**
 
-      * 比较编码
 
-      * @param str1
 
-      * @param str2
 
-      * @param symbol
 
-      * @returns {number}
 
-      */
 
-     compareCode(str1, str2, symbol = '-') {
 
-         if (!str1) {
 
-             return 1;
 
-         } else if (!str2) {
 
-             return -1;
 
-         }
 
-         function compareSubCode(code1, code2) {
 
-             if (numReg.test(code1)) {
 
-                 if (numReg.test(code2)) {
 
-                     return parseInt(code1) - parseInt(code2);
 
-                 } else {
 
-                     return -1
 
-                 }
 
-             } else {
 
-                 if (numReg.test(code2)) {
 
-                     return 1;
 
-                 } else {
 
-                     return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); //code1.localeCompare(code2);
 
-                 }
 
-             }
 
-         }
 
-         const numReg = /^[0-9]+$/;
 
-         const aCodes = str1.split(symbol), bCodes = str2.split(symbol);
 
-         for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
 
-             const iCompare = compareSubCode(aCodes[i], bCodes[i]);
 
-             if (iCompare !== 0) {
 
-                 return iCompare;
 
-             }
 
-         }
 
-         return aCodes.length - bCodes.length;
 
-     },
 
-     /**
 
-      * 根据 清单编号 获取 章级编号
 
-      * @param code
 
-      * @param symbol
 
-      * @returns {string}
 
-      */
 
-     getChapterCode(code, symbol = '-') {
 
-         if (!code || code === '') return '';
 
-         const codePath = code.split(symbol);
 
-         const reg = /^[0-9]*$/;
 
-         if (reg.test(codePath[0])) {
 
-             const num = parseInt(codePath[0]);
 
-             return this.mul(this.div(num, 100, 0), 100) + '';
 
-         } else {
 
-             return '10000';
 
-         }
 
-     },
 
-     /**
 
-      * 树结构节点排序,要求最顶层节点须在同一父节点下
 
-      * @param treeNodes
 
-      * @param idField
 
-      * @param pidField
 
-      */
 
-     sortTreeNodes (treeNodes, idField, pidField) {
 
-         const result = [];
 
-         const getFirstLevel = function (nodes) {
 
-             let result;
 
-             for (const node of nodes) {
 
-                 if (!result || result > node.level) {
 
-                     result = node.level;
 
-                 }
 
-             }
 
-             return result;
 
-         };
 
-         const getLevelNodes = function (nodes, level) {
 
-             const children = nodes.filter(function (a) {
 
-                 return a.level = level;
 
-             });
 
-             children.sort(function (a, b) {
 
-                 return a.order - b.order;
 
-             });
 
-             return children;
 
-         };
 
-         const getChildren = function (nodes, node) {
 
-             const children = nodes.filter(function (a) {
 
-                 return a[pidField] = node[idField];
 
-             });
 
-             children.sort(function (a, b) {
 
-                 return a.order - b.order;
 
-             });
 
-             return children;
 
-         };
 
-         const addSortNodes = function (nodes) {
 
-             for (let i = 0; i< nodes.length; i++) {
 
-                 result.push(nodes[i]);
 
-                 addSortNodes(getChildren(nodes[i]));
 
-             }
 
-         };
 
-         const firstLevel = getFirstLevel(treeNodes);
 
-         addSortNodes(getLevelNodes(treeNodes, firstLevel));
 
-     },
 
-     /**
 
-      * 判断当前用户是否有指定权限
 
-      *
 
-      * @param {Number|Array} permission - 权限id
 
-      * @return {Boolean} - 返回判断结果
 
-      */
 
-     hasPermission(permission) {
 
-         let result = false;
 
-         try {
 
-             const sessionUser = this.ctx.session.sessionUser;
 
-             if (sessionUser.permission === undefined) {
 
-                 throw '不存在权限数据';
 
-             }
 
-             let currentPermission = sessionUser.permission;
 
-             if (currentPermission === '') {
 
-                 throw '权限数据为空';
 
-             }
 
-             // 管理员则直接返回结果
 
-             if (currentPermission === 'all') {
 
-                 return true;
 
-             }
 
-             currentPermission = currentPermission.split(',');
 
-             permission = permission instanceof Array ? permission : [permission];
 
-             let counter = 0;
 
-             for (const tmp of permission) {
 
-                 if (currentPermission[tmp] !== undefined) {
 
-                     counter++;
 
-                 }
 
-             }
 
-             result = counter === permission.length;
 
-         } catch (error) {
 
-             result = false;
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
 
-      * @param pathName
 
-      * @returns {Promise<void>}
 
-      */
 
-     async recursiveMkdirSync(pathName) {
 
-         if (!fs.existsSync(pathName)) {
 
-             const upperPath = path.dirname(pathName);
 
-             if (!fs.existsSync(upperPath)) {
 
-                 await this.recursiveMkdirSync(upperPath);
 
-             }
 
-             await fs.mkdirSync(pathName);
 
-         }
 
-     },
 
-     /**
 
-      * 字节 保存至 本地文件
 
-      * @param buffer - 字节
 
-      * @param fileName - 文件名
 
-      * @returns {Promise<void>}
 
-      */
 
-     async saveBufferFile(buffer, fileName) {
 
-         // 检查文件夹是否存在,不存在则直接创建文件夹
 
-         const pathName = path.dirname(fileName);
 
-         if (!fs.existsSync(pathName)) {
 
-             await this.recursiveMkdirSync(pathName);
 
-         }
 
-         await fs.writeFileSync(fileName, buffer);
 
-     },
 
-     /**
 
-      * 将文件流的数据保存至本地文件
 
-      * @param stream
 
-      * @param fileName
 
-      * @returns {Promise<void>}
 
-      */
 
-     async saveStreamFile(stream, fileName) {
 
-         // 读取字节流
 
-         const parts = await streamToArray(stream);
 
-         // 转化为buffer
 
-         const buffer = Buffer.concat(parts);
 
-         // 写入文件
 
-         await this.saveBufferFile(buffer, fileName);
 
-     },
 
-     /**
 
-      * 检查code是否是指标模板数据
 
-      * @param {String} code
 
-      * @returns {boolean}
 
-      */
 
-     validBillsCode(code) {
 
-         const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
 
-         const reg2 = /([a-z0-9]+$)/i;
 
-         return reg1.test(code) && reg2.test(code);
 
-     },
 
-     getNumberFormatter(decimal) {
 
-         if (decimal <= 0) {
 
-             return "0";
 
-         }
 
-         let pre = "0.";
 
-         for (let i = 0; i < decimal; i++) {
 
-             pre += "#"
 
-         }
 
-         return pre;
 
-     },
 
-     /**
 
-      * 根据单位查找对应的清单精度
 
-      * @param {tenderInfo.precision} list - 清单精度列表
 
-      * @param {String} unit - 单位
 
-      * @returns {number}
 
-      */
 
-     findPrecision(list, unit) {
 
-         if (unit) {
 
-             for (const p in list) {
 
-                 if (list[p].unit && list[p].unit === unit) {
 
-                     return list[p];
 
-                 }
 
-             }
 
-         }
 
-         return list.other;
 
-     },
 
-     /**
 
-      * 检查数据中的精度
 
-      * @param {Object} Obj - 检查的数据
 
-      * @param {Array} fields - 检查的属性
 
-      * @param {Number} precision - 精度
 
-      * @constructor
 
-      */
 
-     checkFieldPrecision(Obj, fields, precision = 2) {
 
-         if (Obj) {
 
-             for (const field of fields) {
 
-                 if (Obj[field]) {
 
-                     Obj[field] = this.round(Obj[field], precision);
 
-                 }
 
-             }
 
-         }
 
-     },
 
-     /**
 
-      * 过滤无效数据
 
-      *
 
-      * @param obj
 
-      * @param fields - 有效数据的数组
 
-      */
 
-     filterValidFields(data, fields) {
 
-         if (data) {
 
-             const result = {};
 
-             for (const prop in data) {
 
-                 if (fields.indexOf(prop) !== -1) {
 
-                     result[prop] = data[prop];
 
-                 }
 
-             }
 
-             return result;
 
-         } else {
 
-             return data;
 
-         }
 
-     },
 
-     // 加减乘除方法,为方便调用,兼容num为空的情况
 
-     // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
 
-     /**
 
-      * 加法 num1 + num2
 
-      * @param num1
 
-      * @param num2
 
-      * @returns {number}
 
-      */
 
-     add(num1, num2) {
 
-         return bc.add(num1 ? num1 : 0, num2 ? num2: 0);
 
-     },
 
-     /**
 
-      * 减法 num1 - num2
 
-      * @param num1
 
-      * @param num2
 
-      * @returns {number}
 
-      */
 
-     sub(num1, num2) {
 
-         return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
 
-     },
 
-     /**
 
-      * 乘法 num1 * num2
 
-      * @param num1
 
-      * @param num2
 
-      * @returns {*}
 
-      */
 
-     mul(num1, num2, digit = 6) {
 
-         if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
 
-             return 0;
 
-         }
 
-         return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
 
-     },
 
-     /**
 
-      * 除法 num1 / num2
 
-      * @param num1 - 被除数
 
-      * @param num2 - 除数
 
-      * @returns {*}
 
-      */
 
-     div(num1, num2, digit = 6) {
 
-         if (num2 && !this.checkZero(num2)) {
 
-             return Decimal.div(num1 ? num1: 0, num2).toDecimalPlaces(digit).toNumber();
 
-         } else {
 
-             return null;
 
-         }
 
-     },
 
-     /**
 
-      * 四舍五入(统一,方便以后万一需要置换)
 
-      * @param {Number} value - 舍入的数字
 
-      * @param {Number} decimal - 要保留的小数位数
 
-      * @returns {*}
 
-      */
 
-     round(value, decimal) {
 
-         //return value ? bc.round(value, decimal) : null;
 
-         return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
 
-     },
 
-     /**
 
-      * 汇总
 
-      * @param array
 
-      * @returns {number}
 
-      */
 
-     sum(array) {
 
-         let result = 0;
 
-         for (const a of array) {
 
-             result = this.add(result, a);
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 使用正则替换字符
 
-      * @param str
 
-      * @param reg
 
-      * @param subStr
 
-      * @returns {*}
 
-      */
 
-     replaceStr(str, reg, subStr) {
 
-         return str ? str.replace(reg, subStr) : str;
 
-     },
 
-     /**
 
-      * 替换字符串中的 换行符回车符
 
-      * @param str
 
-      * @returns {*}
 
-      */
 
-     replaceReturn(str) {
 
-         // return str
 
-         //     ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
 
-         //     : str;
 
-         return (str && typeof str === 'string')
 
-             ? str.replace(/[\r\n]/g, '')
 
-             : !_.isNil(str) ? str + '' : str;
 
-     },
 
-     /**
 
-      * 替换字符串中的 换行符回车符为换行符<br>
 
-      * @param str
 
-      * @returns {*}
 
-      */
 
-     replaceRntoBr(str) {
 
-         // return str
 
-         //     ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
 
-         //     : str;
 
-         return (str && typeof str === 'string')
 
-             ? str.replace(/[\r\n]/g, '<br>')
 
-             : !_.isNil(str) ? str + '' : str;
 
-     },
 
-     /**
 
-      * 获取 字符串 数组的 mysql 筛选条件
 
-      *
 
-      * @param arr
 
-      * @returns {*}
 
-      */
 
-     getInArrStrSqlFilter(arr) {
 
-         let result = '';
 
-         for (const a of arr) {
 
-             if (result !== '') {
 
-                 result = result + ','
 
-             }
 
-             result = result + this.ctx.app.mysql.escape(a);
 
-         }
 
-         return result;
 
-     },
 
-     /**
 
-      * 合并 相关数据
 
-      * @param {Array} main - 主数据
 
-      * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
 
-      */
 
-     assignRelaData(main, rela) {
 
-         const index = {}, indexPre = 'id_';
 
-         const loadFields = function (datas, fields, prefix, relaId) {
 
-             for (const d of datas) {
 
-                 const key = indexPre + d[relaId];
 
-                 const m = index[key];
 
-                 if (m) {
 
-                     for (const f of fields) {
 
-                         if (d[f] !== undefined) {
 
-                             m[prefix + f] = d[f];
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-         };
 
-         for (const m of main) {
 
-             index[indexPre + m.id] = m;
 
-         }
 
-         for (const r of rela) {
 
-             loadFields(r.data, r.fields, r.prefix, r.relaId);
 
-         }
 
-     },
 
-     whereSql (where, as) {
 
-         if (!where) {
 
-             return '';
 
-         }
 
-         const wheres = [];
 
-         const values = [];
 
-         for (const key in where) {
 
-             const value = where[key];
 
-             if (Array.isArray(value)) {
 
-                 wheres.push('?? IN (?)');
 
-             } else {
 
-                 wheres.push('?? = ?');
 
-             }
 
-             values.push((as && as !== '') ? as + '.' + key : key);
 
-             values.push(value);
 
-         }
 
-         if (wheres.length > 0) {
 
-             return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
 
-         }
 
-         return '';
 
-     },
 
-     formatMoney(s, dot = ',') {
 
-         if (!s) return '0.00';
 
-         s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
 
-         var l = s.split(".")[0].split("").reverse(),
 
-             r = s.split(".")[1];
 
-         let t = "";
 
-         for(let i = 0; i < l.length; i ++ )   {
 
-             t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
 
-         }
 
-         return t.split("").reverse().join("") + "." + r;
 
-     },
 
-     transFormToChinese(num) {
 
-         const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
 
-         const unit = ["", "十", "百", "千", "万"];
 
-         num = parseInt(num);
 
-         let getWan = (temp) => {
 
-             let strArr = temp.toString().split("").reverse();
 
-             let newNum = "";
 
-             for (var i = 0; i < strArr.length; i++) {
 
-                 newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
 
-             }
 
-             return strArr.length === 2 && newNum.indexOf("一十") !== -1 ? newNum.replace('一十', '十') : newNum;
 
-         }
 
-         let overWan = Math.floor(num / 10000);
 
-         let noWan = num % 10000;
 
-         if (noWan.toString().length < 4) noWan = "0" + noWan;
 
-         return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
 
-     },
 
-     dateTran(time) {
 
-         return moment(time).format('YYYY年MM月DD日 HH:mm');
 
-     },
 
-     timeAdd(duration) {
 
-         const d = parseInt(duration);
 
-         let time = 0;
 
-         if (d === 1) {
 
-             time = 60 * 15 * 1000;
 
-         } else if (d === 2) {
 
-             time = 60 * 30 * 1000;
 
-         } else if (d === 3) {
 
-             time = 3600 * 1000;
 
-         } else if (d === 4) {
 
-             time = 3600 * 2 * 1000;
 
-         }
 
-         return time;
 
-     },
 
-     async sendUserSms(userId, type, judge, msg) {
 
-         const mobiles = [];
 
-         if (!userId || (userId instanceof Array && userId.length === 0)) return;
 
-         const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
 
-         for (const su of smsUser) {
 
-             if (!su.auth_mobile || su.auth_mobile === '') continue;
 
-             if (!su.sms_type || su.sms_type === '') continue;
 
-             const smsType = JSON.parse(su.sms_type);
 
-             if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
 
-                 mobiles.push(su.auth_mobile);
 
-             }
 
-         }
 
-         if (mobiles.length > 0) {
 
-             const sms = new SMS(this.ctx);
 
-             const tenderName = await sms.contentChange(this.ctx.tender.data.name);
 
-             const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
 
-             const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
 
-             const content = '【纵横计量支付】' + ptmsg + msg;
 
-             sms.send(mobiles, content);
 
-         }
 
-     },
 
-     async sendAliSms(userId, type, judge, code, data = {}) {
 
-         const mobiles = [];
 
-         if (!userId || (userId instanceof Array && userId.length === 0)) return;
 
-         const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
 
-         for (const su of smsUser) {
 
-             if (!su.auth_mobile || su.auth_mobile === '') continue;
 
-             if (!su.sms_type || su.sms_type === '') continue;
 
-             const smsType = JSON.parse(su.sms_type);
 
-             if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
 
-                 mobiles.push(su.auth_mobile);
 
-             }
 
-         }
 
-         if (mobiles.length > 0) {
 
-             const sms = new SMS(this.ctx);
 
-             const tenderName = await sms.contentChange(this.ctx.tender.data.name);
 
-             const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
 
-             const param = {
 
-                 project: projectName,
 
-                 number: tenderName,
 
-             };
 
-             const postParam = Object.assign(param, data);
 
-             sms.aliSend(mobiles, postParam, code);
 
-         }
 
-     },
 
-     /**
 
-      *
 
-      * @param setting
 
-      * @param data
 
-      * @returns {{} & any & {"!ref": string} & {"!cols"}}
 
-      */
 
-     simpleXlsxSheetData(setting, data) {
 
-         const headerStyle = {
 
-             font: { sz: 10, bold: true },
 
-             alignment: { horizontal: 'center' },
 
-         };
 
-         const sHeader = setting.header
 
-             .map((v, i) => Object.assign({}, { v: v, s: headerStyle, position: String.fromCharCode(65+i) + 1 }))
 
-             .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
 
-         const sData = data
 
-             .map((v, i) => v.map((k, j) => Object.assign({}, {
 
-                 v: k ? k : '',
 
-                 s: { font: { sz: 10 }, alignment: {horizontal: setting.hAlign[j]}},
 
-                 position: String.fromCharCode(65+j) + (i+2) })))
 
-             .reduce((prev, next) => prev.concat(next))
 
-             .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
 
-         const output = Object.assign({}, sHeader, sData);
 
-         const outputPos = Object.keys(output);
 
-         const result = Object.assign({}, output,
 
-             {'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]},
 
-             {'!cols': setting.width.map((w) => Object.assign({}, {wpx: w}))});
 
-         return result;
 
-     },
 
-     log(error) {
 
-         if (error.stack) {
 
-             this.ctx.logger.error(error);
 
-         } else {
 
-             this.ctx.getLogger('fail').info(JSON.stringify({
 
-                 error: error,
 
-                 project: this.ctx.session.sessionProject,
 
-                 user: this.ctx.session.sessionUser,
 
-                 body: this.ctx.session.body,
 
-             }));
 
-         }
 
-     },
 
-     /**
 
-      * 添加debug信息
 
-      * 在debug模式下,debug信息将传输到浏览器并打印
 
-      *
 
-      * @param {String}key
 
-      * @param {*}data
 
-      */
 
-     addDebugInfo(key, ...data) {
 
-         if (!this.ctx.debugInfo) {
 
-             this.ctx.debugInfo = { key: {}, other: [] };
 
-         }
 
-         if (key) {
 
-             this.ctx.debugInfo.key[key] = data;
 
-         } else {
 
-             this.ctx.debugInfo.other.push(data);
 
-         }
 
-     },
 
-     /**
 
-      * 深拷贝
 
-      * @param obj
 
-      * @returns {*}
 
-      */
 
-     clone: function (obj) {
 
-         if (obj === null) return null;
 
-         var o = obj instanceof Array ? [] : {};
 
-         for (var i in obj) {
 
-             o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? this.clone(obj[i]) : obj[i]);
 
-         }
 
-         return o;
 
-     },
 
-     /**
 
-      * 短链接生成
 
-      * @param url
 
-      * @returns {*}
 
-      */
 
-     async urlToShort(url) {
 
-         const apiUrl = 'http://scn.ink/api/shorturl';
 
-         const data = {
 
-             url: encodeURI(url),
 
-         };
 
-         const result = await this.sendRequest(apiUrl, data, 'get');
 
-         return result && result.code === 200 && result.url ? result.url : url;
 
-     },
 
-     /**
 
-      * 判断是否wap访问
 
-      * @param request
 
-      * @returns {*}
 
-      */
 
-     isWap(request) {
 
-         return request.url.indexOf('/wap/') !== -1;
 
-     },
 
-     checkBillsWithPos(bills, pos, fields) {
 
-         const result = {
 
-             error: [],
 
-             source: {
 
-                 bills: [],
 
-                 pos: [],
 
-             }
 
-         };
 
-         for (const b of bills) {
 
-             const pr = _.remove(pos, {lid: b.id});
 
-             const checkData = {}, calcData = {};
 
-             if (pr && pr.length > 0) {
 
-                 for (const field of fields) {
 
-                     checkData[field] = b[field] ? b[field] : 0;
 
-                 }
 
-                 for (const p of pr) {
 
-                     for (const field of fields) {
 
-                         calcData[field] = this.add(calcData[field], p[field]);
 
-                     }
 
-                 }
 
-                 if (!_.isMatch(checkData, calcData)) {
 
-                     result.error.push({
 
-                         ledger_id: b.ledger_id,
 
-                         b_code: b.b_code,
 
-                         name: b.name,
 
-                         error: {checkData: checkData, calcData: calcData}
 
-                     });
 
-                     result.source.bills.push(b);
 
-                     for (const p of pr) {
 
-                         result.source.pos.push(p);
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         return result;
 
-     },
 
-     check18MainCode(code) {
 
-         return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
 
-     },
 
-     check18SubCode(code) {
 
-         return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
 
-     },
 
-     /**
 
-      * 判断是否是移动端访问
 
-      * @param request
 
-      * @returns {*}
 
-      */
 
-     isMobile(agent) {
 
-         return agent.match(/(iphone|ipod|android)/i);
 
-     },
 
- }
 
 
  |