exportStdInterfaceBase.js 32 KB

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