base.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /**
  2. * @author Zhong
  3. * @date 2019/6/20
  4. * @version
  5. */
  6. const INTERFACE_EXPORT_BASE = (() => {
  7. 'use strict';
  8. const { hasValue, isHan } = window.commonUtil;
  9. // 属性类型
  10. const TYPE = {
  11. DATE: 1, // 日期类型YYYY-MM-DD
  12. DATE_TIME: 2, // 日期类型YYY-MM-DDTHH:mm:ss
  13. INT: 3, // 整数类型
  14. DECIMAL: 4, // 数值类型,不限制小数位数
  15. NUM2: 5, // 数值类型2:最多两位小数
  16. BOOL: 6 // 布尔型
  17. };
  18. // 需要特殊处理的属性类型默认空值(当一个值为undefined、null的时候,默认给赋什么值)
  19. const DEFAULT_VALUE = {
  20. [TYPE.INT]: '0',
  21. [TYPE.DECIMAL]: '0',
  22. [TYPE.NUM2]: '0',
  23. [TYPE.BOOL]: 'false'
  24. };
  25. // 空白字符处理
  26. const WHITE_SPACE = {
  27. COLLAPSE: 1 // 移除所有空白字符(换行、回车、空格以及制表符会被替换为空格,开头和结尾的空格会被移除,而多个连续的空格会被缩减为一个单一的空格)
  28. };
  29. // 承包人材料调整类型
  30. const ADJUST_TYPE = {
  31. info: 'priceInfo', // 造价信息差额调整法
  32. coe: 'priceCoe' // 价格指数调整法
  33. };
  34. // 加载数据间隔,减少服务器压力
  35. const TIMEOUT_TIME = 400;
  36. const {
  37. GRANULARITY,
  38. EXPORT_KIND
  39. } = window.commonConstants;
  40. /* const EXPORT_KIND_NAME = {
  41. 1: '招标',
  42. 2: '投标',
  43. 3: '控制价'
  44. }; */
  45. // 配置项
  46. const CONFIG = Object.freeze({
  47. TYPE,
  48. WHITE_SPACE,
  49. ADJUST_TYPE,
  50. TIMEOUT_TIME,
  51. });
  52. // 缓存项 不需要的时候需要清空
  53. const _cache = {
  54. // 项目数据(不包含详细数据,项目管理数据)
  55. projectData: {},
  56. // 当前导出类型,默认投标
  57. exportKind: EXPORT_KIND.BID_SUBMISSION,
  58. // 记录拉取的单位工程项目详细数据,导出的时候,可能会导出多个文件,只有导出第一个文件的时候需要请求数据
  59. tenderDetailMap: {}
  60. };
  61. // 返回缓存项
  62. function getItem(key) {
  63. return _cache[key] || null;
  64. }
  65. // 设置缓存项
  66. function setItem(key, value) {
  67. // 与原数据是同类型的数据才可设置成功
  68. if (_cache[key] &&
  69. Object.prototype.toString.call(_cache[key]) ===
  70. Object.prototype.toString.call(value)) {
  71. _cache[key] = value;
  72. }
  73. }
  74. // 清空缓存项
  75. function clear() {
  76. _cache.projectData = {};
  77. _cache.exportKind = EXPORT_KIND.BID_SUBMISSION;
  78. _cache.tenderDetailMap = {};
  79. }
  80. const CACHE = Object.freeze({
  81. getItem,
  82. setItem,
  83. clear
  84. });
  85. /*
  86. * 定义不设置一个Node方法统一进入的原因:模板化比较直观,不分开定义节点的话,调用传参也很麻烦而且不直观。
  87. * 一个节点对应一个构造方法,方便调整配置、方便其他版本开发、接手的人看起来更直观
  88. * @param {String}name 节点名
  89. * {Array}attrs 节点属性数据
  90. * @return {void}
  91. * */
  92. function Element(name, attrs = []) {
  93. this.name = name;
  94. this.attrs = attrs;
  95. check(this.attrs);
  96. handleXMLEntity(this.attrs);
  97. this.children = [];
  98. }
  99. /*
  100. * xml字符实体的处理,这些特殊字符不处理会导致xml文件格式出错:""、<>、&
  101. * 要先处理&amp
  102. * */
  103. const _xmlEntity = {
  104. '&': '&amp;',
  105. '\n': '&#xA;',
  106. '"': '&quot;',
  107. '\'': '&apos;',
  108. '<': '&lt;',
  109. '>': '&gt;'
  110. };
  111. // 对每个元素的所有属性值进行特殊字符处理
  112. function handleXMLEntity(attrs) {
  113. for (const attr of attrs) {
  114. if (!attr.value) {
  115. continue;
  116. }
  117. for (const [key, value] of Object.entries(_xmlEntity)) {
  118. attr.value = attr.value.replace(new RegExp(key, 'g'), value);
  119. }
  120. }
  121. }
  122. // 获取处理实体字符后的数据
  123. function getParsedData(arr) {
  124. return arr.map(data => {
  125. for (const [key, value] of Object.entries(_xmlEntity)) {
  126. data = data.replace(new RegExp(key, 'g'), value);
  127. }
  128. return data;
  129. });
  130. }
  131. // 获取Date类型默认值
  132. function getDateTypeDefaultValue(date) {
  133. const month = String(date.getMonth() + 1);
  134. const formattedMonth = month.length === 1 ? `0${month}` : month;
  135. const day = String(date.getDate());
  136. const formattedDay = day.length === 1 ? `0${day}` : day;
  137. return `${date.getFullYear()}-${formattedMonth}-${formattedDay}`;
  138. }
  139. /*
  140. * 检查
  141. * 创建节点时检查节点的数据(原本是用于自检,现在来处理默认值)
  142. * @param {Array}datas 需要检查的属性数据
  143. * @return {void}
  144. * */
  145. function check(datas) {
  146. for (const data of datas) {
  147. const isHasValue = hasValue(data.value);
  148. // 值统一转换成String,并且处理各类型属性空值时的默认取值
  149. data.value = !isHasValue
  150. ? DEFAULT_VALUE[data.type]
  151. ? DEFAULT_VALUE[data.type]
  152. : ''
  153. : String(data.value);
  154. if (data.whiteSpace && data.whiteSpace === WHITE_SPACE.COLLAPSE) { //处理空格相关
  155. data.value = data.value.replace(/[\r\n\t]/g, ' ');
  156. data.value = data.value.trim();
  157. data.value = data.value.replace(/\s{1,}/g, ' ');
  158. }
  159. // 类型对应得值不正确时,赋类型对应默认值
  160. if (!data.type) {
  161. continue;
  162. }
  163. const dateReg = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
  164. if (data.type === TYPE.DATE && !dateReg.test(data.value)) {
  165. data.value = getDateTypeDefaultValue(new Date());
  166. } else if (data.type === TYPE.INT && !Number.isInteger(parseFloat(data.value))) {
  167. data.value = DEFAULT_VALUE[TYPE.INT];
  168. } else if (data.type === TYPE.DECIMAL && isNaN(parseFloat(data.value))) {
  169. data.value = DEFAULT_VALUE[TYPE.DECIMAL];
  170. } else if (data.type === TYPE.NUM2) {
  171. data.value = DEFAULT_VALUE[TYPE.NUM2];
  172. } else if (data.type === TYPE.BOOL && !['true', 'false'].includes(String(data.value))) {
  173. data.value = DEFAULT_VALUE[TYPE.BOOL];
  174. }
  175. }
  176. }
  177. // 等待一段时间
  178. function setTimeoutSync(handle, time) {
  179. return new Promise((resolve, reject) => {
  180. setTimeout(() => {
  181. if (handle && typeof handle === 'function') {
  182. handle();
  183. }
  184. resolve();
  185. }, time);
  186. });
  187. }
  188. /*
  189. * 将节点属性数据(attr数组)转换成简单key-value数据
  190. * @param {Object}ele 元素节点数据Element实例
  191. * @return {Object}
  192. * */
  193. function getPlainAttrs(ele) {
  194. const obj = {};
  195. ele.attrs.forEach(attr => obj[attr.name] = attr.value);
  196. return obj;
  197. }
  198. /*
  199. * 从fees数组中获取相关费用
  200. * @param {Array}fees 费用数组
  201. * {String}feeFields 费用字段
  202. * @return {Number}
  203. * @example getFee(source.fees, 'common.totalFee')
  204. * */
  205. function getFee(fees, feeFields) {
  206. if (!Array.isArray(fees)) {
  207. return 0;
  208. }
  209. const fields = feeFields.split('.');
  210. const fee = fees.find(data => data.fieldName === fields[0]);
  211. if (!fee) {
  212. return 0;
  213. }
  214. return fee[fields[1]] || 0;
  215. }
  216. // 获取节点的汇总价格
  217. function getAggregateFee(nodes) {
  218. const total = nodes.reduce((acc, node) => {
  219. const price = getFee(node.data.fees, 'common.totalFee');
  220. return acc += price;
  221. }, 0);
  222. return scMathUtil.roundTo(total, -2);
  223. }
  224. // 获取固定类别行的费用
  225. function getFeeByFlag(items, flag, feeFields) {
  226. const node = items.find(node => node.getFlag() === flag);
  227. return node ? getFee(node.data.fees, feeFields) : '0';
  228. }
  229. /*
  230. * 根据key获取对应的基本信息、工程特征数据
  231. * @param {Array}data
  232. * {String}key
  233. * @return {String}
  234. * @example getValueByKey(source.basicInformation, 'projectScale')
  235. * */
  236. function getValueByKey(items, key) {
  237. for (const item of items) {
  238. if (item.key === key) {
  239. return item.value;
  240. }
  241. if (item.items && item.items.length) {
  242. const value = getValueByKey(item.items, key);
  243. if (value) {
  244. return value;
  245. }
  246. }
  247. }
  248. return '';
  249. }
  250. // 获取关联材料
  251. function getRelGLJ(allGLJs, gljId) {
  252. return allGLJs.find(glj => glj.id === gljId);
  253. }
  254. // 随机生成机器信息码:CPU信息;硬盘序列号;mac地址;
  255. // 保存在localStorage中
  256. function generateHardwareId() {
  257. const hardwareCacheId = window.localStorage.getItem('hardwareId');
  258. if (hardwareCacheId) {
  259. return hardwareCacheId;
  260. }
  261. const charList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  262. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
  263. 'V', 'W', 'X', 'Y', 'Z'];
  264. function generateCpuId() {
  265. let id = '';
  266. let count = 16;
  267. while (count--) {
  268. const randomIdx = parseInt(Math.random() * 16);
  269. id += charList[randomIdx];
  270. }
  271. return id;
  272. }
  273. function generateDiskId() {
  274. let id = '';
  275. let count = 8;
  276. while (count--) {
  277. const randomIdx = parseInt(Math.random() * 36);
  278. id += charList[randomIdx];
  279. }
  280. return id;
  281. }
  282. function generateMacId() {
  283. const idList = [];
  284. let outerCount = 6;
  285. while (outerCount--) {
  286. let tempId = '';
  287. let innerCount = 2;
  288. while (innerCount--) {
  289. const randomIdx = parseInt(Math.random() * 16);
  290. tempId += charList[randomIdx];
  291. }
  292. idList.push(tempId);
  293. }
  294. return idList.join('-');
  295. }
  296. const cpuId = generateCpuId();
  297. const diskId = generateDiskId();
  298. const macId = generateMacId();
  299. const hardwareId = [cpuId, diskId, macId].join(';');
  300. window.localStorage.setItem('hardwareId', hardwareId);
  301. return hardwareId;
  302. }
  303. // 数组打平成对象
  304. function arrayToObj(arr) {
  305. const rst = {};
  306. for (const data of arr) {
  307. rst[data.key] = data.value;
  308. }
  309. return rst;
  310. }
  311. /*
  312. * 检测层数是否有效
  313. * @param {Number}maxDepth(最大深度)
  314. * {Object}node(需要检测的清单树节点)
  315. * @return {Boolean}
  316. * */
  317. function validDepth(maxDepth, node) {
  318. const nodeDepth = node.depth();
  319. const allNodes = node.getPosterity();
  320. //检测相对深度
  321. for (const n of allNodes) {
  322. const relativeDepth = n.depth() - nodeDepth;
  323. if (relativeDepth > maxDepth) {
  324. return false;
  325. }
  326. }
  327. return true;
  328. }
  329. // 根据数据的NextSiblingID进行排序,返回排序后的数组
  330. function sortByNext(datas) {
  331. const target = [];
  332. const temp = {};
  333. for (const data of datas) {
  334. temp[data.ID] = { me: data, next: null, prev: null };
  335. }
  336. for (const data of datas) {
  337. const next = temp[data.NextSiblingID] || null;
  338. temp[data.ID].next = next;
  339. if (next) {
  340. next.prev = temp[data.ID];
  341. }
  342. }
  343. let first = null;
  344. for (const data of datas) {
  345. const me = temp[data.ID];
  346. if (!me.prev) {
  347. first = me;
  348. }
  349. }
  350. if (!first) {
  351. return datas;
  352. }
  353. while (first) {
  354. target.push(first.me);
  355. first = first.next;
  356. }
  357. return target;
  358. }
  359. /*
  360. * 根据粒度获取项目(不包含详细数据)数据
  361. * @param {Number}granularity 导出粒度
  362. * {Object}requestForSummaryInfo 项目表级汇总字段(建设项目、单位工程汇总)
  363. * {Number}tenderID 单位工程ID
  364. * {String}userID 用户ID
  365. * @return {Object} 返回的数据结构:{children: [{children: []}]} 最外层为建设项目,中间为单项工程,最底层为单位工程
  366. * */
  367. async function getProjectByGranularity(granularity, requestForSummaryInfo, tenderID, userID) {
  368. let projectData = _cache.projectData;
  369. // 没有数据,需要拉取
  370. if (!Object.keys(projectData).length) {
  371. projectData = await ajaxPost('/pm/api/getProjectByGranularity', { user_id: userID, tenderID, granularity, requestForSummaryInfo });
  372. _cache.projectData = projectData;
  373. }
  374. return projectData;
  375. }
  376. /*
  377. * 通过getData接口获取单位工程详细数据(带缓存功能)
  378. * @param {Number}tenderID 单位工程ID
  379. * {String}userID 用户ID
  380. * @return {Object} 跟projectObj.project的数据结构一致
  381. * */
  382. async function getTenderDetail(tenderID, userID) {
  383. // 获取单位工程详细数据
  384. let tenderDetail = _cache.tenderDetailMap[tenderID];
  385. if (!tenderDetail) {
  386. tenderDetail = PROJECT.createNew(tenderID, userID);
  387. await tenderDetail.loadDataSync();
  388. // 标记序号
  389. const count = Object.keys(_cache.tenderDetailMap).length;
  390. tenderDetail.serialNo = count + 1;
  391. _cache.tenderDetailMap[tenderID] = tenderDetail;
  392. }
  393. return tenderDetail;
  394. }
  395. // 获取普通基数: {xxx}
  396. function getNormalBase(str) {
  397. const reg = /{.+?}/g;
  398. const matchs = str.match(reg);
  399. return matchs || [];
  400. }
  401. // 获取id引用基数: @xxx-xxx-xx
  402. function getIDBase(str) {
  403. const reg = /@.{36}/g;
  404. const matchs = str.match(reg);
  405. return matchs || [];
  406. }
  407. // 转换基数表达式
  408. // 1.有子项,则取固定清单对应基数
  409. // 2.无子项,有基数,a.优先转换为行代号(不可自身) b.不能转换为行代号则找对应字典
  410. // 3.基数中有无法转换的,根据导出类型决定
  411. function transformCalcBase(exportKind, tenderDetail, node, { CalcBaseMap, FlagCalcBaseMap }) {
  412. let expr = node.data.calcBase || '';
  413. if (node.children.length) {
  414. const flag = node.getFlag();
  415. return FlagCalcBaseMap[flag] || '';
  416. }
  417. if (expr) {
  418. let illegal = false;
  419. const normalBase = getNormalBase(expr);
  420. const idBase = getIDBase(expr);
  421. // 普通基数转基数字典
  422. normalBase.forEach(base => {
  423. let replaceStr = CalcBaseMap[base];
  424. // 转换成行代号的优先级比较高,进行清单匹配
  425. const flag = FlagCalcBaseMap[base];
  426. if (flag) {
  427. const flagNode = tenderDetail.mainTree.items.find(mNode => mNode.getFlag() === flag);
  428. // 匹配到了 普通基数转换成行引用
  429. if (flagNode) {
  430. replaceStr = `F${flagNode.serialNo() + 1}`;
  431. }
  432. }
  433. // 存在无法处理的基数
  434. if (!replaceStr) {
  435. illegal = true;
  436. return;
  437. }
  438. expr = expr.replace(new RegExp(base, 'g'), replaceStr);
  439. });
  440. // id引用转行代号引用
  441. idBase.forEach(base => {
  442. const id = base.match(/[^@]+/)[0];
  443. const theNode = tenderDetail.mainTree.getNodeByID(id);
  444. const rowCode = theNode ? `F${theNode.serialNo() + 1}` : '';
  445. if (!rowCode) {
  446. illegal = true;
  447. return;
  448. }
  449. expr = expr.replace(new RegExp(base, 'g'), rowCode);
  450. });
  451. // 不合法
  452. // 在我们软件中的基数无法找到映射代号的情况下
  453. // 导出招标、控制价时,基数为空
  454. // 导出投标时,基数=综合合价/费率
  455. if (illegal) {
  456. if (exportKind === EXPORT_KIND.BID_INVITATION || exportKind === EXPORT_KIND.CONTROL) {
  457. return '';
  458. } else {
  459. const totalFee = getFee(node.data.fees, 'common.totalFee');
  460. const feeRate = node.data.feeRate;
  461. return +feeRate ? scMathUtil.roundTo(totalFee / (feeRate / 100), -2) : totalFee
  462. }
  463. }
  464. return expr;
  465. }
  466. }
  467. // 转换基数说明,根据转换后的基数处理
  468. // 1.行引用转换为对应行的名称
  469. // 2.基数字典转换为中文
  470. function transformCalcBaseState(tenderDetail, expr, CalcStateMap) {
  471. if (!expr) {
  472. return '';
  473. }
  474. expr = String(expr);
  475. // 提取基数
  476. const bases = expr.split(/[\+\-\*\/]/g);
  477. // 提取操作符
  478. const oprs = expr.match(/[\+\-\*\/]/g);
  479. // 转换后的基数
  480. const newBase = [];
  481. let illegal = false;
  482. for (const base of bases) {
  483. // 行引用转换为名称.
  484. if (/F\d+/.test(base)) {
  485. const rowCode = base.match(/\d+/)[0];
  486. const node = tenderDetail.mainTree.items[rowCode - 1];
  487. if (!node || !node.data.name) {
  488. illegal = true;
  489. break;
  490. }
  491. newBase.push(node && node.data.name ? node.data.name : '');
  492. } else if (CalcStateMap[base]) { // 字典转换为中文
  493. newBase.push(CalcStateMap[base]);
  494. } else if (/^\d+(\.\d+)?$/.test(base)) { // 金额
  495. newBase.push(base);
  496. } else {
  497. illegal = true;
  498. break;
  499. }
  500. }
  501. if (illegal) {
  502. return '';
  503. }
  504. let newExpr = '';
  505. for (let i = 0; i < newBase.length; i++) {
  506. newExpr += newBase[i];
  507. if (oprs && oprs[i]) {
  508. newExpr += oprs[i];
  509. }
  510. }
  511. return newExpr;
  512. }
  513. // 获取节点的某属性
  514. function getAttr(ele, name) {
  515. return (ele.attrs.find(attr => attr.name === name) || {}).value;
  516. }
  517. // 设置节点的某属性
  518. function setAttr(ele, name, value) {
  519. const attr = ele.attrs.find(attr => attr.name === name);
  520. if (attr) {
  521. attr.value = value;
  522. }
  523. }
  524. // 从srcEle节点中获取元素名为eleName的元素
  525. function getElementFromSrc(srcEle, eleName) {
  526. if (!srcEle || !srcEle.children || !srcEle.children.length) {
  527. return [];
  528. }
  529. return srcEle.children.filter(ele => ele.name === eleName);
  530. }
  531. /*
  532. * 设置完工程编号后,更新原始数据的工程编号
  533. * 更新原始数据前需要将编号里的特殊字符进行转换
  534. * @param {Array}exportData 提取出来的需要导出的数据
  535. * {Array}codes 工程编号表中填写的工程编号
  536. * {String}EngineeringName 单项工程元素的名称
  537. * {String}tenderName 单位工程元素的名称
  538. * {String}codeName 编号属性的名称
  539. * @return {void}
  540. * */
  541. function setupCode(exportData, codes, EngineeringName, tenderName, codeName) {
  542. // 转换xml实体字符
  543. let parsedCodes = getParsedData(codes);
  544. // 给导出数据里的单项工程、单位工程填上用户设置的工程编号
  545. exportData.forEach(orgData => {
  546. let curIdx = 0;
  547. let engs = getElementFromSrc(orgData.data, EngineeringName);
  548. engs.forEach(eng => {
  549. eng.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  550. let tenders = getElementFromSrc(eng, tenderName);
  551. tenders.forEach(tender => {
  552. tender.attrs.find(attr => attr.name === codeName).value = parsedCodes[curIdx++];
  553. });
  554. });
  555. });
  556. }
  557. // 将文本的中文提取出来
  558. function getHan(str) {
  559. if (!str) {
  560. return '';
  561. }
  562. return str
  563. .split('')
  564. .reduce((acc, cur) => {
  565. if (isHan(cur)) {
  566. acc.push(cur);
  567. }
  568. return acc;
  569. }, [])
  570. .join('');
  571. }
  572. const UTIL = Object.freeze({
  573. hasValue,
  574. setTimeoutSync,
  575. getFee,
  576. getAggregateFee,
  577. getFeeByFlag,
  578. getPlainAttrs,
  579. getValueByKey,
  580. getRelGLJ,
  581. generateHardwareId,
  582. arrayToObj,
  583. validDepth,
  584. sortByNext,
  585. getTenderDetail,
  586. getProjectByGranularity,
  587. getNormalBase,
  588. getIDBase,
  589. transformCalcBase,
  590. transformCalcBaseState,
  591. getElementFromSrc,
  592. getAttr,
  593. setAttr,
  594. getParsedData,
  595. setupCode,
  596. getHan,
  597. });
  598. // 开始标签
  599. function _startTag(ele) {
  600. let rst = `<${ele.name}`;
  601. for (const attr of ele.attrs) {
  602. rst += ` ${attr.name}="${attr.value}"`;
  603. }
  604. rst += ele.children.length > 0 ? '>' : '/>';
  605. return rst;
  606. }
  607. // 结束标签
  608. function _endTag(ele) {
  609. return `</${ele.name}>`;
  610. }
  611. // 拼接成xml字符串
  612. function _toXMLStr(eles) {
  613. let rst = '';
  614. for (const ele of eles) {
  615. rst += _startTag(ele);
  616. if (ele.children.length > 0) {
  617. rst += _toXMLStr(ele.children);
  618. rst += _endTag(ele);
  619. }
  620. }
  621. return rst;
  622. }
  623. // 格式化xml字符串
  624. function _formatXml(text) {
  625. // 去掉多余的空格
  626. text = '\n' + text.replace(/>\s*?</g, ">\n<");
  627. // 调整格式
  628. const reg = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  629. const nodeStack = [];
  630. const output = text.replace(reg, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
  631. const isClosed = (isCloseFull1 === '/') || (isCloseFull2 === '/') || (isFull1 === '/') || (isFull2 === '/');
  632. let prefix = '';
  633. if (isBegin === '!') {
  634. prefix = getPrefix(nodeStack.length);
  635. } else {
  636. if (isBegin !== '/') {
  637. prefix = getPrefix(nodeStack.length);
  638. if (!isClosed) {
  639. nodeStack.push(name);
  640. }
  641. } else {
  642. nodeStack.pop();
  643. prefix = getPrefix(nodeStack.length);
  644. }
  645. }
  646. return '\n' + prefix + all;
  647. });
  648. return output.substring(1);
  649. function getPrefix(prefixIndex) {
  650. const span = ' ';
  651. const output = [];
  652. for (let i = 0; i < prefixIndex; i++) {
  653. output.push(span);
  654. }
  655. return output.join('');
  656. }
  657. }
  658. /**
  659. * 提取要导出的数据
  660. * @param {Function} entryFunc - 提取数据的入口方法
  661. * @param {Object} requestForSummaryInfo - 项目表级汇总字段(建设项目、单位工程汇总)
  662. * @param {Number} exportKind - 导出的文件类型:1-招标、2-投标、3-控制价
  663. * @param {String} areaKey - 地区标识,如:'安徽@马鞍山'
  664. * @param {Number} tenderID - 单位工程ID
  665. * @param {String} userID - 用户ID
  666. * @return {Promise<Array>} - [{data: Object, exportKind: Number, fileName: String}]
  667. */
  668. async function extractExportData(entryFunc, requestForSummaryInfo, exportKind, areaKey, tenderID, userID) {
  669. // 默认导出投标文件
  670. if (!exportKind || ![1, 2, 3].includes(exportKind)) {
  671. exportKind = EXPORT_KIND.BID_SUBMISSION;
  672. }
  673. // 拉取标段数据:建设项目、单位工程数据(projects表数据)
  674. const projectData = await getProjectByGranularity(GRANULARITY.PROJECT, requestForSummaryInfo, tenderID, userID);
  675. if (!projectData) {
  676. throw '获取项目数据错误';
  677. }
  678. // 单位工程按照树结构数据进行排序,这样导出才的单位工程顺序才是对的
  679. projectData.children = sortByNext(projectData.children);
  680. // 先获取需要导出的单位工程的详细数据
  681. const tenderDetailMap = getItem('tenderDetailMap');
  682. for (const tenderItem of projectData.children) {
  683. if (!tenderDetailMap[tenderItem.ID]) {
  684. await setTimeoutSync(() => { }, TIMEOUT_TIME); // 需要请求项目详细数据的时候,间隔一段时间再初始单位工程数据,减少服务器压力
  685. }
  686. // 获取单位工程详细数据
  687. await getTenderDetail(tenderItem.ID, userID);
  688. }
  689. // 提取相关项目的详细导出数据
  690. return await entryFunc(areaKey, exportKind, projectData, tenderDetailMap);
  691. }
  692. /**
  693. * 根据各自费用定额的文件结构,导出文件
  694. * 每个费用定额可能导出的结果文件都不同
  695. * 比如广东18需要将一个建设项目文件,多个单位工程文件打包成一个zip文件。重庆18就没这种要求
  696. * @param {Array} extractData - 提取的数据
  697. * @param {Function} saveAsFunc - 各自费用定额的导出方法,适应不同接口需要不同的最终文件形式
  698. */
  699. async function exportFile(extractData, saveAsFunc) {
  700. // 获取文件数据
  701. const fileData = extractData.map(extractObj => {
  702. // 转换成xml字符串
  703. let xmlStr = _toXMLStr([extractObj.data]);
  704. // 加上xml声明
  705. xmlStr = `<?xml version="1.0" encoding="utf-8"?>${xmlStr}`;
  706. // 格式化
  707. xmlStr = _formatXml(xmlStr);
  708. const blob = new Blob([xmlStr], { type: 'text/plain;charset=utf-8' });
  709. return {
  710. blob: blob,
  711. exportKind: extractObj.exportKind,
  712. fileName: extractObj.fileName
  713. };
  714. });
  715. if (!saveAsFunc) {
  716. return fileData;
  717. }
  718. // 导出
  719. await saveAsFunc(fileData);
  720. }
  721. /**
  722. * 默认的通用导出文件方法:一个文件数据对应一个xml文件(变更后缀)
  723. * @param {Array} fileData - 默认的通用导出文件方法:一个文件数据对应一个xml文件(变更后缀)
  724. * @return {Void}
  725. */
  726. async function defaultSaveAs(fileData) {
  727. fileData.forEach(fileItem => saveAs(fileItem.blob, fileItem.fileName));
  728. }
  729. return {
  730. CONFIG,
  731. CACHE,
  732. UTIL,
  733. Element,
  734. extractExportData,
  735. defaultSaveAs,
  736. exportFile,
  737. };
  738. })();