exportStdInterfaceBase.js 32 KB

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