helper.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. 'use strict';
  2. /**
  3. * 辅助方法扩展
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/9/28
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const zeroRange = 0.0000000001;
  11. const fs = require('fs');
  12. const path = require('path');
  13. const streamToArray = require('stream-to-array');
  14. const _ = require('lodash');
  15. const bc = require('../lib/base_calc.js');
  16. const Decimal = require('decimal.js');
  17. Decimal.set({ precision: 50, defaults: true });
  18. const SMS = require('../lib/sms');
  19. const WX = require('../lib/wechat');
  20. const timesLen = 100;
  21. const UAParser = require('ua-parser-js');
  22. const math = require('mathjs');
  23. module.exports = {
  24. _,
  25. /**
  26. * 生成随机字符串
  27. *
  28. * @param {Number} length - 需要生成字符串的长度
  29. * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
  30. * @return {String} - 返回生成结果
  31. */
  32. generateRandomString(length, type = 1) {
  33. length = parseInt(length);
  34. length = isNaN(length) ? 1 : length;
  35. let randSeed = [];
  36. let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  37. let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
  38. 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  39. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  40. switch (type) {
  41. case 1:
  42. randSeed = stringSeed.concat(numberSeed);
  43. stringSeed = numberSeed = null;
  44. break;
  45. case 2:
  46. randSeed = numberSeed;
  47. break;
  48. case 3:
  49. randSeed = stringSeed;
  50. break;
  51. default:
  52. break;
  53. }
  54. const seedLength = randSeed.length - 1;
  55. let result = '';
  56. for (let i = 0; i < length; i++) {
  57. const index = Math.ceil(Math.random() * seedLength);
  58. result += randSeed[index];
  59. }
  60. return result;
  61. },
  62. /**
  63. * 字节转换
  64. * @param {number} bytes - 字节
  65. * @return {string} - 大小
  66. */
  67. bytesToSize(bytes) {
  68. if (parseInt(bytes) === 0) return '0 B';
  69. const k = 1024;
  70. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  71. const i = Math.floor(Math.log(bytes) / Math.log(k));
  72. // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
  73. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  74. },
  75. /**
  76. * 浮点乘法计算
  77. * @param {number} arg1 - 乘数
  78. * @param {number} arg2 - 被乘数
  79. * @return {string} - 结果
  80. */
  81. accMul(arg1, arg2) {
  82. if (arg1 === '' || arg1 === null || arg1 === undefined || arg2 === '' || arg2 === null || arg2 === undefined) {
  83. return '';
  84. }
  85. let m = 0;
  86. const s1 = arg1.toString();
  87. const s2 = arg2.toString();
  88. try {
  89. m += s1.split('.')[1] !== undefined ? s1.split('.')[1].length : 0;
  90. } catch (e) {
  91. throw e;
  92. }
  93. try {
  94. m += s2.split('.')[1] !== undefined ? s2.split('.')[1].length : 0;
  95. } catch (e) {
  96. throw e;
  97. }
  98. return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
  99. },
  100. accAdd(arg1, arg2) {
  101. let r1;
  102. let r2;
  103. try {
  104. r1 = arg1.toString().split('.')[1].length;
  105. } catch (e) {
  106. r1 = 0;
  107. }
  108. try {
  109. r2 = arg2.toString().split('.')[1].length;
  110. } catch (e) {
  111. r2 = 0;
  112. }
  113. const c = Math.abs(r1 - r2);
  114. const m = Math.pow(10, Math.max(r1, r2));
  115. if (c > 0) {
  116. const cm = Math.pow(10, c);
  117. if (r1 > r2) {
  118. arg1 = Number(arg1.toString().replace('.', ''));
  119. arg2 = Number(arg2.toString().replace('.', '')) * cm;
  120. } else {
  121. arg1 = Number(arg1.toString().replace('.', '')) * cm;
  122. arg2 = Number(arg2.toString().replace('.', ''));
  123. }
  124. } else {
  125. arg1 = Number(arg1.toString().replace('.', ''));
  126. arg2 = Number(arg2.toString().replace('.', ''));
  127. }
  128. return (arg1 + arg2) / m;
  129. },
  130. // 四舍五入或末尾加零,实现类似php的 sprintf("%.".decimal."f", val);
  131. roundNum(val, decimals) {
  132. if (val === '' || val === null) {
  133. return '';
  134. }
  135. if (val !== '') {
  136. val = parseFloat(val);
  137. if (decimals < 1) {
  138. val = (Math.round(val)).toString();
  139. } else {
  140. const num = val.toString();
  141. if (num.lastIndexOf('.') === -1) {
  142. // num += '.';
  143. // num += this.makezero(decimals);
  144. val = num;
  145. } else {
  146. const valdecimals = num.split('.')[1].length;
  147. if (parseInt(valdecimals) < parseInt(decimals)) {
  148. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  149. val = num;
  150. } else if (parseInt(valdecimals) > parseInt(decimals)) {
  151. val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
  152. const num = val.toString();
  153. if (num.lastIndexOf('.') === -1) {
  154. // num += '.';
  155. // num += this.makezero(decimals);
  156. val = num;
  157. } else {
  158. const valdecimals = num.split('.')[1].length;
  159. if (parseInt(valdecimals) < parseInt(decimals)) {
  160. // num += this.makezero(parseInt(decimals) - parseInt(valdecimals));
  161. val = num;
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return val;
  169. },
  170. // 生成num位的0
  171. makezero(num) {
  172. const arr = new Array(num);
  173. for (let i = 0; i < num; i++) {
  174. arr[i] = 0;
  175. }
  176. return arr.join('');
  177. },
  178. // 生成num位的10倍数
  179. makemultiple(num) {
  180. return Math.pow(10, parseInt(num));
  181. },
  182. // 根据单位获取小数位数
  183. findDecimal(unit) {
  184. let value = 3;
  185. if (unit !== '') {
  186. value = this.ctx.tender.info.precision.other.value;
  187. const changeUnits = this.ctx.tender.info.precision;
  188. for (const d in changeUnits) {
  189. if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
  190. value = changeUnits[d].value;
  191. break;
  192. }
  193. }
  194. }
  195. return value;
  196. },
  197. /**
  198. * 显示排序符号
  199. *
  200. * @param {String} field - 字段名称
  201. * @return {String} - 返回字段排序的符号
  202. */
  203. showSortFlag(field) {
  204. const sort = this.ctx.sort;
  205. if (!(sort instanceof Array) || sort.length !== 2) {
  206. return '';
  207. }
  208. sort[1] = sort[1].toUpperCase();
  209. return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
  210. },
  211. /**
  212. * 判断是否为ajax请求
  213. *
  214. * @param {Object} request - 请求数据
  215. * @return {boolean} 判断结果
  216. */
  217. isAjax(request) {
  218. let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
  219. headerInfo = headerInfo.toLowerCase();
  220. return headerInfo === 'xmlhttprequest';
  221. },
  222. /**
  223. * 模拟发送请求
  224. *
  225. * @param {String} url - 请求地址
  226. * @param {Object} data - 请求数据
  227. * @param {String} type - 请求类型(POST) POST | GET
  228. * @param {String} dataType - 数据类型 json|text
  229. * @return {Object} - 请求结果
  230. */
  231. async sendRequest(url, data, type = 'POST', dataType = 'json') {
  232. // 发起请求
  233. try {
  234. const response = await this.ctx.curl(url, {
  235. method: type,
  236. data,
  237. dataType,
  238. });
  239. if (response.status !== 200) {
  240. throw '请求失败';
  241. }
  242. return response.data;
  243. } catch (err) {
  244. throw '请求失败';
  245. }
  246. },
  247. /**
  248. * 模拟多次发送请求(失败后再获取)
  249. *
  250. * @param {String} url - 请求地址
  251. * @param {Object} data - 失败请求次数
  252. * @param {String} type - 请求类型(POST) POST | GET
  253. * @param {String} dataType - 数据类型 json|text
  254. * @param {String} count - 重复次数
  255. * @return {Object} - 请求结果
  256. */
  257. async sendMoreRequest(url, data = null, type = 'POST', dataType = 'json', count = 3) {
  258. // 发起请求
  259. try {
  260. let response = data ? await this.ctx.curl(url, {
  261. method: type,
  262. data,
  263. dataType,
  264. }) : await this.ctx.curl(url);
  265. // console.log(response);
  266. if (response.status !== 200) {
  267. if (count > 0) {
  268. count = count - 1;
  269. response = await this.sendMoreRequest(url, data, type, dataType, count);
  270. } else {
  271. throw '请求失败';
  272. }
  273. }
  274. return response.data;
  275. } catch (err) {
  276. throw '请求失败';
  277. }
  278. },
  279. /**
  280. * 深度验证数据
  281. *
  282. * @param {Object} rule - 数据规则
  283. * @return {void}
  284. */
  285. validate(rule) {
  286. // 先用内置的验证器验证数据
  287. this.ctx.validate(rule);
  288. // 然后再验证是否有多余的数据
  289. const postData = this.ctx.request.body;
  290. delete postData._csrf_j;
  291. const postDataKey = Object.keys(postData);
  292. const ruleKey = Object.keys(rule);
  293. // 自动增加字段则填充上,以防判断出错
  294. if (postData.create_time !== undefined) {
  295. ruleKey.push('create_time');
  296. }
  297. for (const tmp of postDataKey) {
  298. // 规则里面没有定义则抛出异常
  299. if (ruleKey.indexOf(tmp) < 0) {
  300. throw '参数不正确';
  301. }
  302. }
  303. },
  304. /**
  305. * 拆分path
  306. *
  307. * @param {String|Array} paths - 拆分字符
  308. * @param {String} symbol - 拆分符号
  309. * @return {Array} - 拆分结果
  310. */
  311. explodePath(paths, symbol = '-') {
  312. const result = [];
  313. paths = paths instanceof Array ? paths : [paths];
  314. for (const path of paths) {
  315. // 拆分数据
  316. const pathArray = path.split(symbol);
  317. // 用户缓存循环的数据
  318. const tmpArray = [];
  319. for (const tmp of pathArray) {
  320. // 每次循环都追加一个数据进去
  321. tmpArray.push(tmp);
  322. const tmpPathString = tmpArray.join(symbol);
  323. // 判断是否已经存在有对应数据
  324. if (result.indexOf(tmpPathString) >= 0) {
  325. continue;
  326. }
  327. result.push(tmpPathString);
  328. }
  329. }
  330. return result;
  331. },
  332. /**
  333. * 基于obj, 拷贝sObj中的内容
  334. * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
  335. * @param obj
  336. * @param sObj
  337. * @return {any}
  338. */
  339. updateObj(obj, sObj) {
  340. if (!obj) {
  341. return JSON.parse(JSON.stringify(sObj));
  342. }
  343. const result = JSON.parse(JSON.stringify(obj));
  344. if (sObj) {
  345. for (const prop in sObj) {
  346. result[prop] = sObj[prop];
  347. }
  348. }
  349. return result;
  350. },
  351. /**
  352. * 在数组中查找
  353. * @param {Array} arr
  354. * @param name -
  355. * @param value
  356. * @return {*}
  357. */
  358. findData(arr, name, value) {
  359. if (!arr instanceof Array) {
  360. throw '该方法仅用于数组查找';
  361. }
  362. if (arr.length === 0) { return undefined; }
  363. for (const data of arr) {
  364. if (data[name] == value) {
  365. return data;
  366. }
  367. }
  368. return undefined;
  369. },
  370. /**
  371. * 检查数字是否为0
  372. * @param {Number} value
  373. * @return {boolean}
  374. */
  375. checkZero(value) {
  376. return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
  377. },
  378. /**
  379. * 检查数字是否相等
  380. * @param {Number} value1
  381. * @param {Number} value2
  382. * @return {boolean}
  383. */
  384. checkNumberEqual(value1, value2) {
  385. if (value1 && value2) {
  386. return Math.abs(value2 - value1) > zeroRange;
  387. }
  388. return (!value1 && !value2);
  389. },
  390. /**
  391. * 比较编码
  392. * @param str1
  393. * @param str2
  394. * @param symbol
  395. * @return {number}
  396. */
  397. compareCode(str1, str2, symbol = '-') {
  398. if (!str1) {
  399. return 1;
  400. } else if (!str2) {
  401. return -1;
  402. }
  403. function compareSubCode(code1, code2) {
  404. if (numReg.test(code1)) {
  405. if (numReg.test(code2)) {
  406. return parseInt(code1) - parseInt(code2);
  407. }
  408. return -1;
  409. }
  410. if (numReg.test(code2)) {
  411. return 1;
  412. }
  413. return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
  414. }
  415. const numReg = /^[0-9]+$/;
  416. const aCodes = str1.split(symbol),
  417. bCodes = str2.split(symbol);
  418. for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
  419. const iCompare = compareSubCode(aCodes[i], bCodes[i]);
  420. if (iCompare !== 0) {
  421. return iCompare;
  422. }
  423. }
  424. return aCodes.length - bCodes.length;
  425. },
  426. /**
  427. * 根据 清单编号 获取 章级编号
  428. * @param code
  429. * @param symbol
  430. * @return {string}
  431. */
  432. getChapterCode(code, symbol = '-') {
  433. if (!code || code === '') return '';
  434. const codePath = code.split(symbol);
  435. const reg = /^[^0-9]*[0-9]{3,4}$/;
  436. if (reg.test(codePath[0])) {
  437. const numReg = /[0-9]{3,4}$/;
  438. const result = codePath[0].match(numReg);
  439. const num = parseInt(result[0]);
  440. return this.mul(this.div(num, 100, 0), 100) + '';
  441. }
  442. return '10000';
  443. },
  444. /**
  445. * 树结构节点排序,要求最顶层节点须在同一父节点下
  446. * @param treeNodes
  447. * @param idField
  448. * @param pidField
  449. */
  450. sortTreeNodes(treeNodes, idField, pidField) {
  451. const result = [];
  452. const getFirstLevel = function(nodes) {
  453. let result;
  454. for (const node of nodes) {
  455. if (!result || result > node.level) {
  456. result = node.level;
  457. }
  458. }
  459. return result;
  460. };
  461. const getLevelNodes = function(nodes, level) {
  462. const children = nodes.filter(function(a) {
  463. return a.level = level;
  464. });
  465. children.sort(function(a, b) {
  466. return a.order - b.order;
  467. });
  468. return children;
  469. };
  470. const getChildren = function(nodes, node) {
  471. const children = nodes.filter(function(a) {
  472. return a[pidField] = node[idField];
  473. });
  474. children.sort(function(a, b) {
  475. return a.order - b.order;
  476. });
  477. return children;
  478. };
  479. const addSortNodes = function(nodes) {
  480. for (let i = 0; i < nodes.length; i++) {
  481. result.push(nodes[i]);
  482. addSortNodes(getChildren(nodes[i]));
  483. }
  484. };
  485. const firstLevel = getFirstLevel(treeNodes);
  486. addSortNodes(getLevelNodes(treeNodes, firstLevel));
  487. },
  488. /**
  489. * 判断当前用户是否有指定权限
  490. *
  491. * @param {Number|Array} permission - 权限id
  492. * @return {Boolean} - 返回判断结果
  493. */
  494. hasPermission(permission) {
  495. let result = false;
  496. try {
  497. const sessionUser = this.ctx.session.sessionUser;
  498. if (sessionUser.permission === undefined) {
  499. throw '不存在权限数据';
  500. }
  501. let currentPermission = sessionUser.permission;
  502. if (currentPermission === '') {
  503. throw '权限数据为空';
  504. }
  505. // 管理员则直接返回结果
  506. if (currentPermission === 'all') {
  507. return true;
  508. }
  509. currentPermission = currentPermission.split(',');
  510. permission = permission instanceof Array ? permission : [permission];
  511. let counter = 0;
  512. for (const tmp of permission) {
  513. if (currentPermission[tmp] !== undefined) {
  514. counter++;
  515. }
  516. }
  517. result = counter === permission.length;
  518. } catch (error) {
  519. result = false;
  520. }
  521. return result;
  522. },
  523. /**
  524. * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
  525. * @param pathName
  526. * @return {Promise<void>}
  527. */
  528. async recursiveMkdirSync(pathName) {
  529. if (!fs.existsSync(pathName)) {
  530. const upperPath = path.dirname(pathName);
  531. if (!fs.existsSync(upperPath)) {
  532. await this.recursiveMkdirSync(upperPath);
  533. }
  534. await fs.mkdirSync(pathName);
  535. }
  536. },
  537. /**
  538. * 字节 保存至 本地文件
  539. * @param buffer - 字节
  540. * @param fileName - 文件名
  541. * @return {Promise<void>}
  542. */
  543. async saveBufferFile(buffer, fileName) {
  544. // 检查文件夹是否存在,不存在则直接创建文件夹
  545. const pathName = path.dirname(fileName);
  546. if (!fs.existsSync(pathName)) {
  547. await this.recursiveMkdirSync(pathName);
  548. }
  549. await fs.writeFileSync(fileName, buffer);
  550. },
  551. /**
  552. * 将文件流的数据保存至本地文件
  553. * @param stream
  554. * @param fileName
  555. * @return {Promise<void>}
  556. */
  557. async saveStreamFile(stream, fileName) {
  558. // 读取字节流
  559. const parts = await streamToArray(stream);
  560. // 转化为buffer
  561. const buffer = Buffer.concat(parts);
  562. // 写入文件
  563. await this.saveBufferFile(buffer, fileName);
  564. },
  565. async copyFileSync(source, target) {
  566. const pathName = path.dirname(target);
  567. if (!fs.existsSync(pathName)) {
  568. await this.recursiveMkdirSync(pathName);
  569. }
  570. await fs.copyFileSync(source, target);
  571. },
  572. /**
  573. * 检查code是否是指标模板数据
  574. * @param {String} code
  575. * @return {boolean}
  576. */
  577. validBillsCode(code) {
  578. const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
  579. const reg2 = /([a-z0-9]+$)/i;
  580. return reg1.test(code) && reg2.test(code);
  581. },
  582. getNumberFormatter(decimal) {
  583. if (decimal <= 0) {
  584. return '0';
  585. }
  586. let pre = '0.';
  587. for (let i = 0; i < decimal; i++) {
  588. pre += '#';
  589. }
  590. return pre;
  591. },
  592. /**
  593. * 根据单位查找对应的清单精度
  594. * @param {tenderInfo.precision} list - 清单精度列表
  595. * @param {String} unit - 单位
  596. * @return {number}
  597. */
  598. findPrecision(list, unit) {
  599. if (unit) {
  600. for (const p in list) {
  601. if (list[p].unit && list[p].unit === unit) {
  602. return list[p];
  603. }
  604. }
  605. }
  606. return list.other;
  607. },
  608. /**
  609. * 检查数据中的精度
  610. * @param {Object} Obj - 检查的数据
  611. * @param {Array} fields - 检查的属性
  612. * @param {Number} precision - 精度
  613. * @class
  614. */
  615. checkFieldPrecision(Obj, fields, precision = 2) {
  616. if (Obj) {
  617. for (const field of fields) {
  618. if (Obj[field]) {
  619. Obj[field] = this.round(Obj[field], precision);
  620. }
  621. }
  622. }
  623. },
  624. checkDgnQtyPrecision(data, precision = 3) {
  625. const datas = data instanceof Array ? data : [data];
  626. for (const d of datas) {
  627. for (const prop in d) {
  628. if (prop.indexOf('dgn_qty') >= 0) d[prop] = this.round(d[prop], precision);
  629. }
  630. }
  631. },
  632. /**
  633. * 过滤无效数据
  634. *
  635. * @param obj
  636. * @param fields - 有效数据的数组
  637. */
  638. filterValidFields(data, fields) {
  639. if (data) {
  640. const result = {};
  641. for (const prop in data) {
  642. if (fields.indexOf(prop) !== -1) {
  643. result[prop] = data[prop];
  644. }
  645. }
  646. return result;
  647. }
  648. return data;
  649. },
  650. // 加减乘除方法,为方便调用,兼容num为空的情况
  651. // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
  652. /**
  653. * 加法 num1 + num2
  654. * @param num1
  655. * @param num2
  656. * @return {number}
  657. */
  658. add(num1, num2) {
  659. return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
  660. },
  661. /**
  662. * 减法 num1 - num2
  663. * @param num1
  664. * @param num2
  665. * @return {number}
  666. */
  667. sub(num1, num2) {
  668. return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
  669. },
  670. /**
  671. * 乘法 num1 * num2
  672. * @param num1
  673. * @param num2
  674. * @return {*}
  675. */
  676. mul(num1, num2, digit = 6) {
  677. if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
  678. return 0;
  679. }
  680. return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
  681. },
  682. /**
  683. * 除法 num1 / num2
  684. * @param num1 - 被除数
  685. * @param num2 - 除数
  686. * @return {*}
  687. */
  688. div(num1, num2, digit = 6) {
  689. if (num2 && !this.checkZero(num2)) {
  690. return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
  691. }
  692. return null;
  693. },
  694. /**
  695. * 四舍五入(统一,方便以后万一需要置换)
  696. * @param {Number} value - 舍入的数字
  697. * @param {Number} decimal - 要保留的小数位数
  698. * @return {*}
  699. */
  700. round(value, decimal) {
  701. return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
  702. },
  703. /**
  704. * 汇总
  705. * @param array
  706. * @return {number}
  707. */
  708. sum(array) {
  709. let result = 0;
  710. for (const a of array) {
  711. result = this.add(result, a);
  712. }
  713. return result;
  714. },
  715. /**
  716. * 使用正则替换字符
  717. * @param str
  718. * @param reg
  719. * @param subStr
  720. * @return {*}
  721. */
  722. replaceStr(str, reg, subStr) {
  723. return str ? str.replace(reg, subStr) : str;
  724. },
  725. /**
  726. * 替换字符串中的 换行符回车符
  727. * @param str
  728. * @return {*}
  729. */
  730. replaceReturn(str) {
  731. // return str
  732. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  733. // : str;
  734. return (str && typeof str === 'string')
  735. ? str.replace(/[\r\n]/g, '')
  736. : !_.isNil(str) ? str + '' : str;
  737. },
  738. /**
  739. * 替换字符串中的 换行符回车符为换行符<br>
  740. * @param str
  741. * @return {*}
  742. */
  743. replaceRntoBr(str) {
  744. // return str
  745. // ? (typeof str === 'string') ? str.replace(/[\r\n]/g, '') : str + ''
  746. // : str;
  747. return (str && typeof str === 'string')
  748. ? str.replace(/[\r\n]/g, '<br>')
  749. : !_.isNil(str) ? str + '' : str;
  750. },
  751. /**
  752. * 获取 字符串 数组的 mysql 筛选条件
  753. *
  754. * @param arr
  755. * @return {*}
  756. */
  757. getInArrStrSqlFilter(arr) {
  758. let result = '';
  759. for (const a of arr) {
  760. if (result !== '') {
  761. result = result + ',';
  762. }
  763. result = result + this.ctx.app.mysql.escape(a);
  764. }
  765. return result;
  766. },
  767. /**
  768. * 合并 相关数据
  769. * @param {Array} main - 主数据
  770. * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
  771. */
  772. assignRelaData(main, rela) {
  773. const index = {},
  774. indexPre = 'id_';
  775. const loadFields = function(datas, fields, prefix, relaId) {
  776. for (const d of datas) {
  777. const key = indexPre + d[relaId];
  778. const m = index[key];
  779. if (m) {
  780. for (const f of fields) {
  781. if (d[f] !== undefined) {
  782. m[prefix + f] = d[f];
  783. }
  784. }
  785. }
  786. }
  787. };
  788. for (const m of main) {
  789. index[indexPre + m.id] = m;
  790. for (const r of rela) {
  791. if (r.defaultData) _.assignIn(m, r.defaultData);
  792. }
  793. }
  794. for (const r of rela) {
  795. loadFields(r.data, r.fields, r.prefix, r.relaId);
  796. }
  797. },
  798. whereSql(where, as) {
  799. if (!where) {
  800. return '';
  801. }
  802. const wheres = [];
  803. const values = [];
  804. for (const key in where) {
  805. const value = where[key];
  806. if (Array.isArray(value)) {
  807. wheres.push('?? IN (?)');
  808. } else {
  809. wheres.push('?? = ?');
  810. }
  811. values.push((as && as !== '') ? as + '.' + key : key);
  812. values.push(value);
  813. }
  814. if (wheres.length > 0) {
  815. return this.ctx.app.mysql.format(' WHERE ' + wheres.join(' AND '), values);
  816. }
  817. return '';
  818. },
  819. formatMoney(s = 0, dot = ',', decimal = 2) {
  820. if (!s) {
  821. s = 0;
  822. return s.toFixed(decimal);
  823. }
  824. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(decimal) + '';
  825. if (!decimal) {
  826. s += '.';
  827. }
  828. const l = s.split('.')[0].split('').reverse(),
  829. r = s.split('.')[1];
  830. let t = '';
  831. for (let i = 0; i < l.length; i++) {
  832. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
  833. }
  834. return t.split('').reverse().join('') + (decimal === 0 ? '' : '.' + r);
  835. },
  836. transFormToChinese(num) {
  837. const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  838. const unit = ['', '十', '百', '千', '万'];
  839. num = parseInt(num);
  840. const getWan = temp => {
  841. const strArr = temp.toString().split('').reverse();
  842. let newNum = '';
  843. for (let i = 0; i < strArr.length; i++) {
  844. 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;
  845. }
  846. return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
  847. };
  848. const overWan = Math.floor(num / 10000);
  849. let noWan = num % 10000;
  850. if (noWan.toString().length < 4) noWan = '0' + noWan;
  851. return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  852. },
  853. formatNum(num, pattern) {
  854. const strarr = num ? num.toString().split('.') : ['0'];
  855. const fmtarr = pattern ? pattern.split('.') : [''];
  856. let retstr = '';
  857. // 整数部分
  858. let str = strarr[0];
  859. let fmt = fmtarr[0];
  860. let i = str.length - 1;
  861. let comma = false;
  862. for (var f = fmt.length - 1; f >= 0; f--) {
  863. switch (fmt.substr(f, 1)) {
  864. case '#':
  865. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  866. break;
  867. case '0':
  868. if (i >= 0) retstr = str.substr(i--, 1) + retstr;
  869. else retstr = '0' + retstr;
  870. break;
  871. case ',':
  872. comma = true;
  873. retstr = ',' + retstr;
  874. break;
  875. }
  876. }
  877. if (i >= 0) {
  878. if (comma) {
  879. const l = str.length;
  880. for (;i >= 0; i--) {
  881. retstr = str.substr(i, 1) + retstr;
  882. if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
  883. }
  884. } else retstr = str.substr(0, i + 1) + retstr;
  885. }
  886. retstr = retstr + '.';
  887. // 处理小数部分
  888. str = strarr.length > 1 ? strarr[1] : '';
  889. fmt = fmtarr.length > 1 ? fmtarr[1] : '';
  890. i = 0;
  891. for (var f = 0; f < fmt.length; f++) {
  892. switch (fmt.substr(f, 1)) {
  893. case '#':
  894. if (i < str.length) retstr += str.substr(i++, 1);
  895. break;
  896. case '0':
  897. if (i < str.length) retstr += str.substr(i++, 1);
  898. else retstr += '0';
  899. break;
  900. }
  901. }
  902. return retstr.replace(/^,+/, '').replace(/\.$/, '');
  903. },
  904. dateTran(time, style = 'YYYY年MM月DD日 HH:mm') {
  905. return moment(time).format(style);
  906. },
  907. // 审批日期格式:2020-5-7 9:40:30
  908. formatFullDate(time) {
  909. return moment(time).format('YYYY-MM-DD HH:mm:ss');
  910. },
  911. // 预付款详情页时间线所需格式
  912. formatDate(date) {
  913. if (!date) return '';
  914. const year = date.getFullYear();
  915. let mon = date.getMonth() + 1;
  916. let day = date.getDate();
  917. let hour = date.getHours();
  918. let minute = date.getMinutes();
  919. let scond = date.getSeconds();
  920. if (mon < 10) {
  921. mon = '0' + mon.toString();
  922. }
  923. if (day < 10) {
  924. day = '0' + day.toString();
  925. }
  926. if (hour < 10) {
  927. hour = '0' + hour.toString();
  928. }
  929. if (minute < 10) {
  930. minute = '0' + minute.toString();
  931. }
  932. if (scond < 10) {
  933. scond = '0' + scond.toString();
  934. }
  935. return `${year}<span>${mon}-${day}</span><span>${hour}:${minute}:${scond}</span>`;
  936. },
  937. timeAdd(duration) {
  938. const d = parseInt(duration);
  939. let time = 0;
  940. if (d === 1) {
  941. time = 60 * 15 * 1000;
  942. } else if (d === 2) {
  943. time = 60 * 30 * 1000;
  944. } else if (d === 3) {
  945. time = 3600 * 1000;
  946. } else if (d === 4) {
  947. time = 3600 * 2 * 1000;
  948. }
  949. return time;
  950. },
  951. async sendUserSms(userId, type, judge, msg) {
  952. const mobiles = [];
  953. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  954. const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  955. for (const su of smsUser) {
  956. if (!su.auth_mobile || su.auth_mobile === '') continue;
  957. if (!su.sms_type || su.sms_type === '') continue;
  958. const smsType = JSON.parse(su.sms_type);
  959. if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  960. mobiles.push(su.auth_mobile);
  961. }
  962. }
  963. if (mobiles.length > 0) {
  964. const sms = new SMS(this.ctx);
  965. const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  966. const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  967. const ptmsg = projectName !== '' ? '项目「' + projectName + '」标段「' + tenderName + '」' : tenderName;
  968. const content = '【纵横计量支付】' + ptmsg + msg;
  969. sms.send(mobiles, content);
  970. }
  971. },
  972. async sendAliSms(userId, type, judge, code, data = {}) {
  973. // const mobiles = [];
  974. // if (!userId || (userId instanceof Array && userId.length === 0)) return;
  975. // const smsUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  976. // for (const su of smsUser) {
  977. // if (!su.auth_mobile || su.auth_mobile === '') continue;
  978. // if (!su.sms_type || su.sms_type === '') continue;
  979. //
  980. // const smsType = JSON.parse(su.sms_type);
  981. // if (smsType[type] && smsType[type].indexOf(judge) !== -1) {
  982. // mobiles.push(su.auth_mobile);
  983. // }
  984. // }
  985. //
  986. // if (mobiles.length > 0) {
  987. // const sms = new SMS(this.ctx);
  988. // const tenderName = await sms.contentChange(this.ctx.tender.data.name);
  989. // const projectName = await sms.contentChange(this.ctx.tender.info.deal_info.buildName);
  990. // const param = {
  991. // project: projectName,
  992. // number: tenderName,
  993. // };
  994. // const postParam = Object.assign(param, data);
  995. // sms.aliSend(mobiles, postParam, code);
  996. // }
  997. },
  998. async sendWechat(userId, type, judge, template, data = {}) {
  999. const wechats = [];
  1000. if (!userId || (userId instanceof Array && userId.length === 0)) return;
  1001. const wxUser = await this.ctx.service.projectAccount.getAllDataByCondition({ where: { id: userId } });
  1002. for (const user of wxUser) {
  1003. if (!user.wx_openid || user.wx_openid === '') continue;
  1004. if (!user.wx_type || user.wx_type === '') continue;
  1005. const wxType = JSON.parse(user.wx_type);
  1006. if (wxType[type] && wxType[type].indexOf(judge) !== -1) {
  1007. wechats.push(user.wx_openid);
  1008. }
  1009. }
  1010. if (wechats.length > 0) {
  1011. const wx = new WX(this.ctx);
  1012. const tenderName = await wx.contentChange(this.ctx.tender.data.name);
  1013. const projectName = await wx.contentChange(this.ctx.tender.info.deal_info.buildName);
  1014. const param = {
  1015. projectName,
  1016. tenderName,
  1017. };
  1018. const postParam = Object.assign(param, data);
  1019. wx.Send(wechats, template, postParam);
  1020. }
  1021. },
  1022. /**
  1023. *
  1024. * @param setting
  1025. * @param data
  1026. * @return {{} & any & {"!ref": string} & {"!cols"}}
  1027. */
  1028. simpleXlsxSheetData(setting, data) {
  1029. const headerStyle = {
  1030. font: { sz: 10, bold: true },
  1031. alignment: { horizontal: 'center' },
  1032. };
  1033. const sHeader = setting.header
  1034. .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
  1035. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1036. const sData = data
  1037. .map((v, i) => v.map((k, j) => Object.assign({}, {
  1038. v: k ? k : '',
  1039. s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
  1040. position: String.fromCharCode(65 + j) + (i + 2) })))
  1041. .reduce((prev, next) => prev.concat(next))
  1042. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
  1043. const output = Object.assign({}, sHeader, sData);
  1044. const outputPos = Object.keys(output);
  1045. const result = Object.assign({}, output,
  1046. { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
  1047. { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
  1048. return result;
  1049. },
  1050. log(error) {
  1051. if (error.stack) {
  1052. this.ctx.logger.error(error);
  1053. } else {
  1054. this.ctx.getLogger('fail').info(JSON.stringify({
  1055. error,
  1056. project: this.ctx.session.sessionProject,
  1057. user: this.ctx.session.sessionUser,
  1058. body: this.ctx.session.body,
  1059. }));
  1060. }
  1061. },
  1062. /**
  1063. * 添加debug信息
  1064. * 在debug模式下,debug信息将传输到浏览器并打印
  1065. *
  1066. * @param {String}key
  1067. * @param {*}data
  1068. */
  1069. addDebugInfo(key, ...data) {
  1070. if (!this.ctx.debugInfo) {
  1071. this.ctx.debugInfo = { key: {}, other: [] };
  1072. }
  1073. if (key) {
  1074. this.ctx.debugInfo.key[key] = data;
  1075. } else {
  1076. this.ctx.debugInfo.other.push(data);
  1077. }
  1078. },
  1079. /**
  1080. * 深拷贝
  1081. * @param obj
  1082. * @return {*}
  1083. */
  1084. clone(obj) {
  1085. if (obj === null) return null;
  1086. const o = obj instanceof Array ? [] : {};
  1087. for (const i in obj) {
  1088. o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
  1089. }
  1090. return o;
  1091. },
  1092. /**
  1093. * 短链接生成(暂停生成)
  1094. * @param url
  1095. * @return {*}
  1096. */
  1097. async urlToShort(url) {
  1098. // const apiUrl = 'http://scn.ink/api/shorturl';
  1099. // const data = {
  1100. // url: encodeURI(url),
  1101. // };
  1102. // const result = await this.sendRequest(apiUrl, data, 'get');
  1103. // return result && result.code === 200 && result.url ? result.url : url;
  1104. return url;
  1105. },
  1106. /**
  1107. * 判断是否wap访问
  1108. * @param request
  1109. * @return {*}
  1110. */
  1111. isWap(request) {
  1112. return request.url.indexOf('/wap/') !== -1;
  1113. },
  1114. check18MainCode(code) {
  1115. return /^([0-9]([0-9][0-9])*)?(GD[0-9]{3}([0-9][0-9])*)?$/.test(code);
  1116. },
  1117. check18SubCode(code) {
  1118. return /^(GD)?G?[A-Z]{2}[A-Z]{0,2}([0-9]{2})+$/.test(code);
  1119. },
  1120. /**
  1121. * 判断是否是移动端访问
  1122. * @param request
  1123. * @return {*}
  1124. */
  1125. isMobile(agent) {
  1126. return agent.match(/(iphone|ipod|android)/i);
  1127. },
  1128. /**
  1129. * 删除文件
  1130. * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
  1131. * @return {void}
  1132. */
  1133. async delFiles(fileList) {
  1134. if (fileList.length) {
  1135. for (const att of fileList) {
  1136. if (att.filepath && fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  1137. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1138. }
  1139. }
  1140. }
  1141. },
  1142. /**
  1143. * 匹配图片、pdf(用于预览)
  1144. * @param {String} ext 后缀名
  1145. * @return {Boolean} 匹配结果
  1146. */
  1147. canPreview(ext) {
  1148. const reg = /(.png)|(.gif)|(.txt)|(.jpg)|(.jpeg)|(.pdf)/;
  1149. return reg.test(ext);
  1150. },
  1151. /**
  1152. * 查找数组中某个字符的个数
  1153. * @param {Array} array 数组
  1154. * @param {string} val 字符串
  1155. * @return {Boolean} 匹配结果
  1156. */
  1157. arrayCount(array, val) {
  1158. const counts = (arr, value) => arr.reduce((a, v) => { return value.indexOf(v) !== -1 ? a + 1 : a + 0; }, 0);
  1159. return counts(array, val);
  1160. },
  1161. filterTimesOrderData(data, keyFields, timesField, orderField, times, order) {
  1162. const dataIndex = {};
  1163. for (const d of data) {
  1164. if (d[timesField] > times || (d[timesField] = times && d[orderField] > order)) continue;
  1165. let key = 'd';
  1166. for (const kf of keyFields) {
  1167. key = key + '.' + (d[kf] || '');
  1168. }
  1169. const di = dataIndex[key];
  1170. if (di) {
  1171. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1172. } else {
  1173. dataIndex[key] = d;
  1174. }
  1175. }
  1176. const result = [];
  1177. for (const prop in dataIndex) {
  1178. result.push(dataIndex[prop]);
  1179. }
  1180. return result;
  1181. },
  1182. filterLastestData(data, keyFields, timesField = 'times', orderField = 'order') {
  1183. const dataIndex = {};
  1184. for (const d of data) {
  1185. let key = 'd';
  1186. for (const kf of keyFields) {
  1187. key = key + '.' + (d[kf] || '');
  1188. }
  1189. const di = dataIndex[key];
  1190. if (di) {
  1191. if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
  1192. } else {
  1193. dataIndex[key] = d;
  1194. }
  1195. }
  1196. const result = [];
  1197. for (const prop in dataIndex) {
  1198. result.push(dataIndex[prop]);
  1199. }
  1200. return result;
  1201. },
  1202. calcExpr(expr) {
  1203. const validExpr = expr.replace('=', '').replace('%', '/100');
  1204. return math.eval(validExpr);
  1205. },
  1206. /**
  1207. * 创建登录日志
  1208. * @return {Boolean} 日志是否创建成功
  1209. * @param {Number} type - 登录类型
  1210. * @param {Number} status - 是否显示记录
  1211. */
  1212. async getUserIPMsg() {
  1213. const { ctx } = this;
  1214. const ip = ctx.request.ip ? ctx.request.ip : '';
  1215. const ipInfo = await this.getIpInfoFromApi(ip);
  1216. const parser = new UAParser(ctx.header['user-agent']);
  1217. const osInfo = parser.getOS();
  1218. const cpuInfo = parser.getCPU();
  1219. const browserInfo = parser.getBrowser();
  1220. const ipMsg = {
  1221. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  1222. browser: `${browserInfo.name} ${browserInfo.version}`,
  1223. ip,
  1224. address: ipInfo,
  1225. };
  1226. return ipMsg;
  1227. },
  1228. /**
  1229. * 根据ip请求获取详细地址
  1230. * @param {String} a_ip - ip地址
  1231. * @return {String} 详细地址
  1232. */
  1233. async getIpInfoFromApi(a_ip = '') {
  1234. if (!a_ip) return '';
  1235. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  1236. const { ip = '', region = '', city = '', isp = '' } = await this.sendIpRequest(a_ip);
  1237. let address = '';
  1238. region && (address += region + '省');
  1239. city && (address += city + '市 ');
  1240. isp && (address += isp + ' ');
  1241. ip && (address += `(${ip})`);
  1242. return address;
  1243. },
  1244. /**
  1245. * 发送请求获取详细地址
  1246. * @param {String} ip - ip地址
  1247. * @return {Object} the result of request
  1248. * @private
  1249. */
  1250. async sendIpRequest(ip) {
  1251. return new Promise(resolve => {
  1252. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  1253. dateType: 'json',
  1254. encoding: 'utf8',
  1255. timeout: 2000,
  1256. headers: {
  1257. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  1258. },
  1259. }).then(({ status, data }) => {
  1260. if (status === 200) {
  1261. const result = JSON.parse(data.toString()).data;
  1262. if (!result.ip) {
  1263. resolve({});
  1264. } else {
  1265. resolve(result);
  1266. }
  1267. } else {
  1268. resolve({});
  1269. }
  1270. }).catch(() => {
  1271. resolve({});
  1272. });
  1273. });
  1274. },
  1275. refreshSpreadShow(sjsRela, sjsSetting) {
  1276. function removeFieldCols(setting, cols) {
  1277. _.remove(setting.cols, function(c) {
  1278. return cols.indexOf(c.field) > -1;
  1279. });
  1280. }
  1281. const sjsSettings = sjsSetting instanceof Array ? sjsSetting : [sjsSetting];
  1282. for (const field of sjsRela) {
  1283. if (field.show) {
  1284. for (const ss of sjsSetting) {
  1285. const lCol = ss.cols.find(x => {
  1286. return x.field === field.field;
  1287. });
  1288. if (lCol) lCol.title = field.alias || field.name;
  1289. }
  1290. } else {
  1291. for (const ss of sjsSetting) {
  1292. removeFieldCols(ss, [field.field]);
  1293. }
  1294. }
  1295. }
  1296. }
  1297. };