base.js 27 KB

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