exportStdInterfaceBase.js 31 KB

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