main.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. /**
  2. * Created by Syusuke on 2017/3/17.
  3. */
  4. //转换excel相关
  5. //Excel中人材机的数据不存在合并列
  6. const TransferExcel = (function () {
  7. const $transferModal = $('#transfer');
  8. const $file = $('#transfer-file');
  9. const $transfer = $('#transferConfirm');
  10. const $exportSpread = $('#exportSpread');
  11. let exportSpread = null;
  12. let transferData = [];
  13. //--以防需要可配置的情况
  14. const fixedCount = 4; //固定列数(顺序号、项目、单位、代号)
  15. const beginCol = 0;//起始的列
  16. //固定的这几列的列号映射是动态的,因为有一些子表,这些列进行了合并列的处理
  17. let colMapping = {
  18. serialNo: 0,
  19. name: 1,
  20. unit: 2,
  21. code: 3,
  22. consumeAmt: 4, //消耗量开始的列
  23. };
  24. //---
  25. function isUnDef(v) {
  26. return typeof v === 'undefined' || v === null;
  27. }
  28. //取消所有空格
  29. function trimAll(v) {
  30. return typeof v === 'string' ? v.replace(/\s/g, '') : v;
  31. }
  32. //单元格是否有数据
  33. function cellHasData(cell) {
  34. return cell && cell.value;
  35. }
  36. //行是否有数据
  37. //@param {Object}rowData(行数据) {Array}deduct(排除的列)
  38. function rowHasData(rowData, deduct = null) {
  39. for (let col in rowData) {
  40. if (deduct && deduct.includes(col)) {
  41. continue;
  42. }
  43. let cell = rowData[col];
  44. if (cell && cell.value) {
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50. //行为列头行 //第一列为数值,且后面其他列有数据(不单纯认为是第二列,因为怕有合并序号列)
  51. function headerRow(rowData) {
  52. return rowData[0] && rowData[0].value && /^\d+$/.test(rowData[0].value) && rowHasData(rowData, ['0']);
  53. }
  54. //去除定额子表数组中的空行(有的表格是在 单位:xx 下面还跟着一些垃圾数据,导致subRation的range范围判定变大了,但是四列后面的数据是空的)
  55. function simplifyRationTable(arr) {
  56. let target = [];
  57. for (let subArr of arr) {
  58. let emptyRow = subArr.every(function (ele) {
  59. return ele === null;
  60. });
  61. if (emptyRow) {
  62. continue;
  63. }
  64. target.push(subArr);
  65. }
  66. return target;
  67. }
  68. //将二维数组转换成每个元素都有值的二维数据(去没值元素,因为前四列有可能合并列)
  69. function simplifyGljTable(arr) {
  70. let target = [];
  71. for (let subArr of arr) {
  72. let subTarget = [];
  73. for (let ele of subArr) {
  74. if (ele !== null) {
  75. subTarget.push(ele);
  76. }
  77. }
  78. target.push(subTarget);
  79. }
  80. return target;
  81. }
  82. //获取前固定四列的动态列映射(解决这几列可能有合并列的问题)
  83. function getColMapping(rowData, colCount) {
  84. function getUndefinedField(obj) {
  85. let needFields = ['serialNo', 'name', 'unit', 'code', 'consumeAmt'];
  86. for (let field of needFields) {
  87. if (!obj.hasOwnProperty(field)) {
  88. return field;
  89. }
  90. }
  91. return null;
  92. }
  93. //假定序号列为第一列
  94. let mapping = {serialNo: 0};
  95. for (let i = 1; i < colCount; i++) {
  96. let col = beginCol + i,
  97. cell = rowData[col];
  98. //还没设置的字段(必须要有的是serialNo, name, unit, code, consumeAmt)
  99. if (cell && cell.value) {
  100. let field = getUndefinedField(mapping);
  101. if (field) {
  102. mapping[field] = col;
  103. }
  104. if (typeof mapping.consumeAmt !== 'undefined') {
  105. return mapping;
  106. }
  107. }
  108. }
  109. return null;
  110. }
  111. //获取表头定额名称数据(最后一行为定额末位编码)
  112. //合并的单元格处理:为了更好的让定额获得对应的定额名称,将合并单元格做填值处理, eg: [a]['合并'] = [a][a]
  113. //@param {Object}dataTable {Object}range(表头的范围,row, col, rowCount, colCount) {Array}spans(spread解析Excel后的合并数组)
  114. //@return {Array}
  115. function getSubRationTable(dataTable, range, spans) {
  116. let subTable = [];
  117. for (let i = 0; i < range.rowCount; i++) {
  118. subTable.push(Array(range.colCount).fill(null));
  119. }
  120. //获取合并的单元格填充数据
  121. let fillArr = [];
  122. for (let i = 0; i < range.rowCount; i++) {
  123. let row = range.row + i;
  124. if (!dataTable[row]) {
  125. continue;
  126. }
  127. for (let j = 0; j < range.colCount; j++) {
  128. let col = range.col + j;
  129. let cell = dataTable[row][col];
  130. //只有有值的单元格,判断合并才有意义,有值且合并列的单元格,每列的值认为都是一样的
  131. if (cellHasData(cell)) {
  132. //是否合并了单元格
  133. let span = spans.find(function (data) {
  134. return data.row === row && data.col === col;
  135. });
  136. //这个fillData给subData填值用
  137. let fillData = {value: trimAll(cell.value), range: {row: i, col: j}};
  138. if (span) {
  139. fillData.range.rowCount = span.rowCount;
  140. fillData.range.colCount = span.colCount;
  141. } else {
  142. fillData.range.rowCount = 1;
  143. fillData.range.colCount = 1;
  144. }
  145. fillArr.push(fillData);
  146. }
  147. }
  148. }
  149. //将数据填充到subData中
  150. for (let fillData of fillArr) {
  151. //合并行不需要向下填值(否则会重复)
  152. let row = fillData.range.row;
  153. //合并列需要向右填值
  154. for (let j = 0; j < fillData.range.colCount; j++) {
  155. let col = fillData.range.col + j;
  156. subTable[row][col] = trimAll(fillData.value);
  157. }
  158. }
  159. return simplifyRationTable(subTable);
  160. }
  161. //获取工料机子表数据(序号至最末消耗量)
  162. //@param {Object}dataTable {Object}range(工料机子表的范围,row, col, rowCount, colCount)
  163. //@return {Array}
  164. function getSubGljTable(dataTable, range) {
  165. let gljTable = [];
  166. for (let i = 0; i < range.rowCount; i++) {
  167. gljTable.push(Array(range.colCount).fill(null));
  168. }
  169. for (let i = 0; i < range.rowCount; i++) {
  170. let row = range.row + i;
  171. if (!dataTable[row]) {
  172. continue;
  173. }
  174. for (let j = 0; j < range.colCount; j++) {
  175. let col = range.col + j;
  176. let cell = dataTable[row][col];
  177. if (cellHasData(cell)) {
  178. gljTable[i][j] = cell.value;
  179. }
  180. }
  181. }
  182. //工料机数据每个单元格应该都有值,没有的为合并列造成,这里将没值的单元格去除
  183. return simplifyGljTable(gljTable);
  184. }
  185. /*
  186. * 从原本的excel中提取数据
  187. * 需要的数据结构:eg: [{code: '1-1-1', name: '伐树', unit: '表列单位', subTable: [{subGlj: [], subRation: []}]}]
  188. * subTable为定额数据对应的子表数据,其中有定额名称子表、工料机子表
  189. * */
  190. function extractDataFromExcel(sheetData) {
  191. let dataTable = sheetData.data.dataTable,
  192. spans = sheetData.spans;
  193. //行数据是定额行 eg: 1-1-1 人工挖土方
  194. //@param {Number}row
  195. //@return {Object || Null} eg: {code: '1-1-1', name: '人工挖土方'}
  196. function rationRow(row) {
  197. let cell = dataTable[row][beginCol];
  198. if (!cell || !cell.value || typeof cell.value !== 'string') {
  199. return false;
  200. }
  201. let v = trimAll(cell.value);
  202. //[\-,—,一] 这里是因为pdf转出来的excel(需要转换的excel)会吧"-"显示成各种奇怪的横杆
  203. //第一数值限制在3位以内,防止有: 2019-05-01等日期干扰
  204. let reg = /^(\d{1,3}[\-,_,—,一]{1}\d+[\-,_,—,一]{1}\d+)(\w{0,}[\u4e00-\u9fa5]{1,})/;
  205. let match = reg.exec(v);
  206. if (match && match.length === 3 && match[0] && match[1] && match[2]) {
  207. return {code: match[1].replace(/[_,—,一]/g, '-'), name: match[2]};
  208. }
  209. return null;
  210. }
  211. //单位数据行 eg: 单位:表列单位
  212. //@return {String || Null} eg: '表列单位'
  213. function unitRow(row) {
  214. let cell = dataTable[row][beginCol];
  215. if (!cell || !cell.value || typeof cell.value !== 'string') {
  216. return false;
  217. }
  218. let v = trimAll(cell.value);
  219. let reg = /单位[\:, :]([\w+, \u4e00-\u9fa5]{0,})/;
  220. let match = reg.exec(v);
  221. if (match && match.length === 2 && match[0] && match[1]) {
  222. return match[1];
  223. }
  224. return null;
  225. }
  226. //行数据是人材机数据行
  227. //表头后,某行第一列为数值,第二列有值,则该行为紧接着表头的人材机数据行
  228. //@return {Boolean}
  229. function rowIsGlj(rowData) {
  230. let numberCell = rowData[colMapping.serialNo],
  231. valueCell = rowData[colMapping.name];
  232. return numberCell && numberCell.value && /^\d+$/.test(numberCell.value) && valueCell && Boolean(valueCell.value);
  233. }
  234. //连续有数据的列数(每个子表格中工料机的数据列数)
  235. //由于序号、项目、单位、代号可能存在合并列,因此从消耗量列(消耗量列不会合并列,消耗量对应的列号已在getColMapping获取)开始统计
  236. function getDataCount(row) {
  237. let consumeAmtCol = colMapping.consumeAmt;
  238. for (let col = consumeAmtCol; col < sheetData.columnCount; col++) {
  239. let cell = dataTable[row][col];
  240. if (!cell || !cell.value) {
  241. return col;
  242. }
  243. }
  244. return sheetData.columnCount;
  245. }
  246. //获取表格的子表范围(定额名称表头范围、工料机数据范围)
  247. //遇到单位:xx行rowA后,获取紧跟其后的表格,该表格最少要有一行工料机数据行rowB,表头范围则为rowA至rowB
  248. //@param {Number}beginRow
  249. function getTableRange(beginRow) {
  250. let hasTHead = false,
  251. hasTable = false,
  252. hasMapping = false; //是否获取过固定列映射
  253. let range = {
  254. subRation: {},
  255. subGlj: {},
  256. };
  257. for (let row = beginRow; row < sheetData.rowCount; row++) {
  258. if (!dataTable[row]) {
  259. continue;
  260. }
  261. //第一个有数据的行,为表头第一行
  262. if (rowHasData(dataTable[row]) && !hasTHead) {
  263. hasTHead = true;
  264. range.subRation.row = row;
  265. }
  266. //获取当前子表的固定列映射
  267. if (hasTHead && !hasTable && !hasMapping && headerRow(dataTable[row])) {
  268. hasMapping = true;
  269. colMapping = getColMapping(dataTable[row], sheetData.columnCount);
  270. if (!colMapping) {
  271. return null;
  272. }
  273. }
  274. //第一条工料机数据行
  275. if (hasTHead && !hasTable && colMapping && rowIsGlj(dataTable[row])) {
  276. hasTable = true;
  277. range.subGlj.row = row;
  278. range.subGlj.col = 0;
  279. range.subRation.col = colMapping.consumeAmt;
  280. range.subRation.rowCount = range.subGlj.row - range.subRation.row;
  281. range.subGlj.colCount = getDataCount(row);
  282. range.subRation.colCount = range.subGlj.colCount - colMapping.consumeAmt;
  283. }
  284. if (hasTable && !rowIsGlj(dataTable[row])) {
  285. range.subGlj.rowCount = row - range.subGlj.row;
  286. return range;
  287. }
  288. if (hasTable && (row === sheetData.rowCount - 1 || !dataTable[row + 1])) {
  289. range.subGlj.rowCount = row - range.subGlj.row + 1;
  290. return range;
  291. }
  292. }
  293. return null;
  294. }
  295. //分析整个表
  296. let extractData = [];
  297. //定额行后必须要跟着单位行
  298. let hasUnit = false;
  299. for (let row = 0; row < sheetData.rowCount; row++) {
  300. if (!dataTable[row] || !rowHasData(dataTable[row])) {
  301. continue;
  302. }
  303. let rationData = rationRow(row);
  304. if (rationData) {
  305. if (!hasUnit) {
  306. extractData.pop();
  307. }
  308. hasUnit = false;
  309. //转换数据数组的每个元素,为定额基本数据:不完整的code、不完整的name、unit、和子表门构成
  310. //subTable: [{subRation: [], subGlj: []}],subRation为每个子表表头数据(排除掉了顺序号至代号),
  311. //subGlj为每个子表工料机数据
  312. let basicData = {
  313. code: rationData.code,
  314. name: rationData.name,
  315. unit: null,
  316. subTable: []
  317. };
  318. extractData.push(basicData);
  319. }
  320. let unitData = unitRow(row);
  321. if (unitData) {
  322. hasUnit = true;
  323. let thisBasicData = extractData[extractData.length - 1];
  324. if (thisBasicData) {
  325. if (!thisBasicData.unit) {
  326. thisBasicData.unit = unitData;
  327. }
  328. //获取表格数据
  329. let range = getTableRange(row + 1);
  330. if (range) {
  331. let subRationTable = getSubRationTable(dataTable, range.subRation, spans),
  332. subGljTable = getSubGljTable(dataTable, range.subGlj);
  333. thisBasicData.subTable.push({subRation: subRationTable, subGlj: subGljTable});
  334. //跳过其中的行
  335. row = range.subGlj.row + range.subGlj.rowCount - 1;
  336. }
  337. }
  338. }
  339. }
  340. return extractData;
  341. }
  342. /*
  343. * 转换数据,将提取出来的数据转换成另外一种数据结构,便于转化Excel的结构
  344. * 需要的数据结构: eg: [{code: '1-1-1-1', name: '伐树xxx', unit: '表列单位', gljList: [{code,name,unit,comsumeAmt}]}]
  345. * */
  346. function transferDataFromExtract(extractData) {
  347. //从一个提取的数据(1定额数据及其子表数据)中获取一份转换数据
  348. function transfer(source) {
  349. //以完整定额编码为属性,因为1个定额可能会有多张子表,且完整定额编码相同,子工料机不同,方便直接添加后续的工料机
  350. let temp = {},
  351. target = [];
  352. let basicCode = source.code,
  353. basicName = source.name,
  354. basicUnit = source.unit;
  355. //处理消耗量,可能有(3.5) 和 - 的情况, 处理:(3.5) => 3.5 - => 0
  356. function handleConsumeAmt(consumeAmt) {
  357. if (typeof consumeAmt === 'string') {
  358. consumeAmt = trimAll(consumeAmt);
  359. consumeAmt = consumeAmt.replace(/[\-,_,—,一,\(,\),(,)]/g, '');
  360. if (!consumeAmt) {
  361. return 0;
  362. }
  363. }
  364. return consumeAmt;
  365. }
  366. //从工料机子表中获取工料机数据, index为定额编码对应的下标索引
  367. function getGljList(gljTable, index) {
  368. let gljList = [];
  369. //获取的工料机对应列
  370. let gljColMapping = {
  371. name: 1,
  372. unit: 2,
  373. code: 3,
  374. consumeAmtCol: fixedCount + index
  375. };
  376. for (let rowData of gljTable) {
  377. //工料机数据必须要有名称、单位、编码
  378. if (!rowData[gljColMapping.name] ||
  379. !rowData[gljColMapping.unit] ||
  380. !rowData[gljColMapping.code]) {
  381. continue;
  382. }
  383. let consumeAmt = isUnDef(rowData[gljColMapping.consumeAmtCol]) ? 0 : handleConsumeAmt(rowData[gljColMapping.consumeAmtCol]);
  384. gljList.push({
  385. name: rowData[gljColMapping.name],
  386. unit: rowData[gljColMapping.unit],
  387. code: rowData[gljColMapping.code],
  388. consumeAmt: consumeAmt,
  389. });
  390. }
  391. return gljList;
  392. }
  393. //拼接定额工料机数据
  394. for (let table of source.subTable) {
  395. let rationTable = table.subRation;
  396. if (!rationTable || rationTable.length === 0) {
  397. continue;
  398. }
  399. let lastRationCodes = rationTable.pop(); //定额子表,最后一行是末位定额编码
  400. for (let i = 0; i < lastRationCodes.length; i++) {
  401. let lastCode = lastRationCodes[i];
  402. //拼接定额编码
  403. let compleCode = `${basicCode}-${lastCode}`,
  404. gljList = getGljList(table.subGlj, i);
  405. if (!temp[compleCode]) { //该定额不存在
  406. temp[compleCode] = {
  407. code: compleCode,
  408. unit: basicUnit,
  409. name: basicName,
  410. gljList: gljList
  411. };
  412. } else { //该定额已存在,则追加工料机
  413. temp[compleCode].gljList = temp[compleCode].gljList.concat(gljList);
  414. }
  415. //拼接定额名称
  416. for (let rationNameRow of rationTable) {
  417. if (rationNameRow[i]) {
  418. temp[compleCode].name += ` ${rationNameRow[i]}`;
  419. }
  420. }
  421. }
  422. }
  423. //将temp对象转换为数据
  424. for (let code in temp) {
  425. target.push(temp[code]);
  426. }
  427. return target;
  428. }
  429. let transferData = [];
  430. for (let data of extractData) {
  431. let unitTargetData = transfer(data);
  432. transferData = transferData.concat(unitTargetData);
  433. }
  434. return transferData;
  435. }
  436. //导入Excel
  437. function exportToExcel(transferData, fileName) {
  438. $.bootstrapLoading.start();
  439. setTimeout(function () {
  440. if (exportSpread) {
  441. exportSpread.destroy();
  442. }
  443. exportSpread = new GC.Spread.Sheets.Workbook($exportSpread[0], {sheetCount: 1});
  444. let sheet = exportSpread.getSheet(0);
  445. sheet.suspendPaint();
  446. sheet.suspendEvent();
  447. //往表格填值
  448. let curRow = 0,
  449. fillCol = {
  450. code: 1,
  451. name: 2,
  452. unit: 3,
  453. consumeAmt: 4
  454. };
  455. function getRowCount() {
  456. let count = 0;
  457. for (let data of transferData) {
  458. count += 1 + data.gljList.length;
  459. }
  460. return count;
  461. }
  462. sheet.setRowCount(getRowCount());
  463. for (let data of transferData) {
  464. sheet.setValue(curRow, 0, '定额');
  465. sheet.setValue(curRow, fillCol.code, data.code);
  466. sheet.setValue(curRow, fillCol.name, data.name);
  467. sheet.setValue(curRow, fillCol.unit, data.unit);
  468. curRow++;
  469. for (let glj of data.gljList) {
  470. sheet.setValue(curRow, fillCol.code, glj.code);
  471. sheet.setValue(curRow, fillCol.name, glj.name);
  472. sheet.setValue(curRow, fillCol.unit, glj.unit);
  473. sheet.setValue(curRow, fillCol.consumeAmt, glj.consumeAmt);
  474. curRow++;
  475. }
  476. }
  477. sheet.resumeEvent();
  478. sheet.resumePaint();
  479. let json = exportSpread.toJSON();
  480. let excelIo = new GC.Spread.Excel.IO();
  481. excelIo.save(json, function(blob) {
  482. saveAs(blob, fileName);
  483. $.bootstrapLoading.end();
  484. $transferModal.modal('hide');
  485. }, function(e) {
  486. $.bootstrapLoading.end();
  487. $transferModal.modal('hide');
  488. console.log(e);
  489. });
  490. }, 200);
  491. }
  492. function eventListener() {
  493. $transferModal.on('hidden.bs.modal', function () {
  494. $file.val('');
  495. transferData = [];
  496. });
  497. //导入excel,提取并转换定额数据
  498. $file.change(function () {
  499. $transfer.addClass('disabled');
  500. let file = $(this)[0];
  501. let excelFile = file.files[0];
  502. if(excelFile) {
  503. let xlsReg = /xls$/g;
  504. if(excelFile.name && xlsReg.test(excelFile.name)){
  505. alert('请选择xlsx文件');
  506. $(this).val('');
  507. return;
  508. }
  509. $.bootstrapLoading.start();
  510. $('#loadingPage').css('z-index', '2000');
  511. //前端解析excel数据
  512. let excelIo = new GC.Spread.Excel.IO();
  513. let sDate = +new Date();
  514. excelIo.open(excelFile, function (json) {
  515. console.log(json);
  516. let extractData = extractDataFromExcel(json.sheets.Sheet1);
  517. transferData = transferDataFromExtract(extractData);
  518. console.log(`解析Excel文件时间:${+new Date() - sDate}`);
  519. $.bootstrapLoading.end();
  520. $transfer.removeClass('disabled');
  521. }, function (e) {
  522. $.bootstrapLoading.end();
  523. $transfer.removeClass('disabled');
  524. alert(e.errorMessage);
  525. });
  526. }
  527. });
  528. //确认转换,导出转换的Excel
  529. $transfer.click(function () {
  530. if (!transferData || transferData.length === 0) {
  531. //没有转换数据
  532. alert('没有转换数据');
  533. return;
  534. }
  535. let fileName = '转换数据.xlsx';
  536. if ($file[0].files && $file[0].files[0] && $file[0].files[0].name) {
  537. fileName = '转换数据' + $file[0].files[0].name;
  538. }
  539. exportToExcel(transferData, fileName);
  540. });
  541. }
  542. return {eventListener}
  543. })();
  544. $(function () {
  545. TransferExcel.eventListener();
  546. let dispNameArr;
  547. let preDeleteId = null;
  548. let deleteCount = 0;
  549. let selCompilationId,
  550. compilationsArr = [];
  551. $('#del').on('hidden.bs.modal', function () {
  552. deleteCount = 0;
  553. });
  554. getAllRationLib(function (dispNames) {
  555. dispNameArr = dispNames;
  556. //添加
  557. $('#addBtn').click(function () {
  558. let compilationName = $('#compilationSels option:selected').text();
  559. let compilationId = $('#compilationSels option:selected').val();
  560. let gljLibName = $('#gljLibSels option:selected').text();
  561. let gljLibId = $('#gljLibSels option:selected').val();
  562. let libName = $('#libNameTxt').val();
  563. if(libName.trim().length === 0){
  564. alert('名称不可为空!');
  565. $('#libNameTxt').val('')
  566. }
  567. else if(dispNames.indexOf(libName) !== -1){
  568. alert('此定额库已存在!');
  569. $('#libNameTxt').val('')
  570. }
  571. else if(compilationName.trim().length === 0){
  572. alert('编办不可为空!');
  573. }
  574. else if(gljLibName.trim().length === 0){
  575. alert("请选择工料机库!");
  576. }
  577. else{
  578. let newRationLib = {};
  579. newRationLib.dispName = libName;
  580. newRationLib.compilationId = compilationId;
  581. newRationLib.compilationName = compilationName;
  582. newRationLib.gljLib = gljLibId;
  583. newRationLib.creator = userAccount;
  584. newRationLib.appType = "建筑";
  585. $('#libNameTxt').val('');
  586. createRationLib(newRationLib, dispNameArr);
  587. }
  588. });
  589. //重命名
  590. $("#showArea").on("click", "[data-target = '#edit']", function(){
  591. let renameId = $(this).parent().parent().attr("id");
  592. $('#renameText').val($(this).parent().parent().find('td:first-child').text());
  593. $("#renameA").attr("renameId", renameId);
  594. });
  595. $("#renameA").click(function(){
  596. let newName = $("#renameText").val();
  597. let libId = $(this).attr("renameId");
  598. let jqSel = "#" + libId + " td:first" + " a";
  599. let orgName = $(jqSel).text();
  600. if(newName.trim().length === 0){
  601. alert("名称不可为空!");
  602. $("#renameText").val('');
  603. }
  604. else if(dispNameArr.indexOf(newName) !== -1){
  605. alert("该定额库已存在!");
  606. $("#renameText").val('');
  607. }
  608. else{
  609. renameRationLib({ID: libId, newName: newName, orgName: orgName}, dispNameArr);
  610. }
  611. });
  612. $('#edit').on('shown.bs.modal', function () {
  613. setTimeout(function () {
  614. $('#renameText').focus();
  615. }, 100);
  616. });
  617. $('#add').on('shown.bs.modal', function () {
  618. setTimeout(function () {
  619. $('#libNameTxt').focus();
  620. }, 100);
  621. });
  622. $('#add').on('hidden.bs.modal', function () {
  623. $('#libNameTxt').val('');
  624. });
  625. //删除
  626. $("#showArea").on("click", "[data-target = '#del']", function(){
  627. let deleteId = $(this).parent().parent().attr("id");
  628. $("#deleteA").attr("deleteId", deleteId);
  629. let delLibName = $(`#${deleteId}`).find('td:first').text();
  630. $('#del').find('.modal-body h5').text(`准备删除 “${delLibName}”,会导致已引用此库的地方出错,确定要删除吗?`);
  631. });
  632. $("#deleteA").click(function(){
  633. let deleteId = $(this).attr("deleteId");
  634. if(preDeleteId && preDeleteId !== deleteId){
  635. deleteCount = 0;
  636. }
  637. preDeleteId = deleteId;
  638. deleteCount++;
  639. let jqSel = "#" + deleteId + " td:first" + " a";
  640. let libName = $(jqSel).text();
  641. if(deleteCount === 3){
  642. deleteCount = 0;
  643. removeRationLib({libId: deleteId, libName: libName}, dispNameArr);
  644. $('#del').modal('hide');
  645. }
  646. });
  647. //全部计算
  648. $("#showArea").on("click", "[data-target = '#reCalcAll']", function(){
  649. let recalcId = $(this).parent().parent().attr("id");
  650. $("#reCalcConfirm").attr("recalcId", recalcId);
  651. });
  652. $("#reCalcConfirm").click(function(){
  653. $('#reCalcConfirm').addClass('disabled');
  654. $.bootstrapLoading.start();
  655. let recalcId = $(this).attr("recalcId");
  656. CommonAjax.post('/rationRepository/api/reCalcAll', {rationRepId: recalcId}, function (rstData) {
  657. $.bootstrapLoading.end();
  658. $('#reCalcAll').modal('hide');
  659. $('#reCalcConfirm').removeClass('disabled');
  660. }, function () {
  661. $.bootstrapLoading.end();
  662. $('#reCalcAll').modal('hide');
  663. $('#reCalcConfirm').removeClass('disabled')
  664. });
  665. });
  666. });
  667. getCompilationList(function (data) {
  668. compilationsArr = data.compilation;
  669. });
  670. // 导入原始数据按钮
  671. let rationRepId = 0;
  672. $("#showArea").on("click", ".import-source", function () {
  673. let id = $(this).data("id");
  674. id = parseInt(id);
  675. if (isNaN(id) || id <= 0) {
  676. return false;
  677. }
  678. rationRepId = id;
  679. $("#import").modal("show");
  680. });
  681. // 导入内部数据
  682. $("#showArea").on("click", ".import-data", function () {
  683. let id = $(this).data("id");
  684. id = parseInt(id);
  685. if (isNaN(id) || id <= 0) {
  686. return false;
  687. }
  688. rationRepId = id;
  689. $("#import2").modal("show");
  690. });
  691. // 导入原始数据确认
  692. $("#source-import,#data-import").click(function() {
  693. $.bootstrapLoading.start();
  694. const self = $(this);
  695. const type = self.is("#source-import") ? 'source_file' : 'import_data';
  696. const dialog = type === 'source_file' ? $("#import") : $("#import2");
  697. try {
  698. let formData = new FormData();
  699. let file = $("input[name='"+ type +"']")[0];
  700. if (file.files.length <= 0) {
  701. throw '请选择文件!';
  702. }
  703. formData.append('file', file.files[0]);
  704. // 获取定额库id
  705. if (rationRepId <= 0) {
  706. return false;
  707. }
  708. formData.append('rationRepId', rationRepId);
  709. formData.append('type', type);
  710. $.ajax({
  711. url: '/rationRepository/api/upload',
  712. type: 'POST',
  713. data: formData,
  714. cache: false,
  715. contentType: false,
  716. processData: false,
  717. beforeSend: function() {
  718. self.attr('disabled', 'disabled');
  719. self.text('上传中...');
  720. },
  721. success: function(response){
  722. self.removeAttr('disabled');
  723. self.text('确定导入');
  724. if (response.err === 0) {
  725. $.bootstrapLoading.end();
  726. const message = response.msg !== undefined ? response.msg : '';
  727. if (message !== '') {
  728. alert(message);
  729. }
  730. // 成功则关闭窗体
  731. dialog.modal("hide");
  732. } else {
  733. $.bootstrapLoading.end();
  734. const message = response.msg !== undefined ? response.msg : '上传失败!';
  735. alert(message);
  736. }
  737. },
  738. error: function(){
  739. $.bootstrapLoading.end();
  740. alert("与服务器通信发生错误");
  741. self.removeAttr('disabled');
  742. self.text('确定导入');
  743. }
  744. });
  745. } catch(error) {
  746. alert(error);
  747. }
  748. });
  749. // 导出数据
  750. $("#showArea").on("click", ".export", function () {
  751. let id = $(this).data("id");
  752. id = parseInt(id);
  753. if (isNaN(id) || id <= 0) {
  754. return false;
  755. }
  756. window.location.href = '/rationRepository/api/export?rationRepId=' + id;
  757. });
  758. //设置补充定额库章节树模板
  759. $("#showArea").on("click", ".set-comple", function () {
  760. let id = $(this).data("id");
  761. id = parseInt(id);
  762. if (isNaN(id) || id <= 0) {
  763. return false;
  764. }
  765. rationRepId = id;
  766. $('#templateA').addClass('disabled');
  767. $('#template').modal('show');
  768. $('#compilations').empty();
  769. for (let data of compilationsArr) {
  770. let $opt = $(`<option value="${data._id}">${data.name}</option>`);
  771. $('#compilations').append($opt);
  772. }
  773. $('#compilations').change();
  774. });
  775. $('#compilations').change(function () {
  776. selCompilationId = $(this).select().val();
  777. CommonAjax.get(`api/sectionTemplateCount/${selCompilationId}`, function (rstData) {
  778. rstData.data.count > 0 ?
  779. $('#templateText').text('该费用定额下已有定额章节树模板数据,是否确认覆盖数据?') :
  780. $('#templateText').text('确认是否将此库的章节树设置成该费用定额下补充定额章节树模板?');
  781. $('#templateA').removeClass('disabled');
  782. });
  783. });
  784. $('#templateA').click(function () {
  785. if (rationRepId <= 0 && selCompilationId) {
  786. return false;
  787. }
  788. $.bootstrapLoading.start();
  789. CommonAjax.post('api/initSectionTemplate', {rationLibId: rationRepId, compilationId: selCompilationId}, function () {
  790. $.bootstrapLoading.end();
  791. $('#template').modal('hide');
  792. }, function () {
  793. $.bootstrapLoading.end();
  794. $('#template').modal('hide');
  795. });
  796. });
  797. });
  798. function getAllRationLib(callback){
  799. $.ajax({
  800. type: 'post',
  801. url: 'api/getRationDisplayNames',
  802. dataType: 'json',
  803. success: function (result) {
  804. let dispNames = [];
  805. if(result.data.length > 0){
  806. for(let i = 0; i < result.data.length; i++){
  807. storageUtil.setSessionCache("RationGrp","repositoryID_" + result.data[i].ID, result.data[i].dispName);
  808. if(result.data[i].gljLib){
  809. storageUtil.setSessionCache("gljLib","repositoryID_" + result.data[i].ID, result.data[i].gljLib);
  810. }
  811. let id = result.data[i].ID;
  812. let libName = result.data[i].dispName;
  813. let createDate = result.data[i].createDate.split(' ')[0];
  814. let compilationName = result.data[i].compilationName;
  815. dispNames.push(result.data[i].dispName);
  816. $("#showArea").append(
  817. "<tr id='"+id+"'>" +
  818. "<td><a href='/rationRepository/ration?repository=" + id +"'>"+libName+"</a></td>" +
  819. "<td>"+compilationName+" </td>" +
  820. "<td>"+createDate+" </td>" +
  821. "<td><a href='javascript:void(0);' data-toggle='modal' data-target='#edit' title='编辑'>" +
  822. "<i class='fa fa-pencil-square-o'></i></a> <a href='javascript:void(0);' data-toggle='modal' data-target='#del' class='text-danger' title='删除'>" +
  823. "<i class='fa fa-remove'></i></a>" +
  824. " <a href='javascript:void(0);' data-toggle='modal' data-target='#reCalcAll' title='全部计算'><i class='fa fa-calculator'></i></a></td>"+
  825. "<td><a class='btn btn-secondary btn-sm import-source' href='javacript:void(0);' data-id='"+ id +"' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
  826. "<td><a class='btn btn-success btn-sm export' href='javacript:void(0);' data-toggle='modal' data-id='"+ id +"' data-target='#emport' title='导出内部数据'><i class='fa fa-sign-out fa-rotate-270'></i>导出</a> " +
  827. "<a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入内部数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
  828. "<td><a class='btn btn-secondary btn-sm transfer-excel' data-toggle='modal' data-target='#transfer' href='javacript:void(0);' data-id='"+ id +"' title='转换Excel'><i class='fa fa-sign-in fa-rotate-90'></i>转换</a></td>" +
  829. "<td><a class='btn btn-secondary btn-sm set-comple' href='javacript:void(0);' data-id='"+ id +"' title='将章节树设为补充模板数据'><i class='fa fa-sign-in fa-rotate-90'></i>设置</a></td>" +
  830. "</tr>");
  831. $("#tempId").attr("id", id);
  832. }
  833. }
  834. callback(dispNames);
  835. }
  836. });
  837. }
  838. function getCompilationList(callback){
  839. $.ajax({
  840. type: 'post',
  841. url: 'api/getCompilationList',
  842. dataType: 'json',
  843. success: function (result) {
  844. //addoptions
  845. for(let i = 0; i < result.data.compilation.length; i++){
  846. let $option = $("<option >"+ result.data.compilation[i].name +"</option>");
  847. $option.val( result.data.compilation[i]._id);
  848. $('#compilationSels').append($option);
  849. }
  850. //初始工料机库选项
  851. if(result.data.compilation.length > 0 && result.data.gljLibs.length > 0){
  852. let compilationId = result.data.compilation[0]._id;
  853. //console.log(compilationId);
  854. let gljLibOps = getGljLibOps(compilationId, result.data.gljLibs);
  855. for(let i = 0; i < gljLibOps.length; i++){
  856. let $option = $("<option >"+ gljLibOps[i].dispName +"</option>");
  857. $option.val(gljLibOps[i].ID);
  858. $('#gljLibSels').append($option);
  859. }
  860. }
  861. $('#compilationSels').on("change", function () {
  862. //刷新工料机库选项
  863. $('#gljLibSels').children().remove();
  864. let newGljLibOps = getGljLibOps(this.selectedOptions[0].value, result.data.gljLibs);
  865. for(let i = 0; i < newGljLibOps.length; i++){
  866. let $option = $("<option >"+ newGljLibOps[i].dispName +"</option>");
  867. $option.val(newGljLibOps[i].ID);
  868. $('#gljLibSels').append($option);
  869. }
  870. });
  871. callback(result.data);
  872. }
  873. });
  874. }
  875. function getGljLibOps(compilationId, gljLibs){
  876. let rst = [];
  877. for(let i = 0; i < gljLibs.length; i++){
  878. if(gljLibs[i]){
  879. if(compilationId === gljLibs[i].compilationId){
  880. rst.push(gljLibs[i]);
  881. }
  882. }
  883. }
  884. return rst;
  885. }
  886. function createRationLib(rationObj, dispNamesArr){
  887. $.ajax({
  888. type: 'post',
  889. url: 'api/addRationRepository',
  890. data: {rationRepObj: JSON.stringify(rationObj)},
  891. dataType: 'json',
  892. success: function (result) {
  893. if(result.data){
  894. storageUtil.setSessionCache("RationGrp","repositoryID_" + result.data.ID, result.data.dispName);
  895. if(result.data.gljLib){
  896. storageUtil.setSessionCache("gljLib","repositoryID_" + result.data.ID, result.data.gljLib);
  897. }
  898. let id = result.data.ID;
  899. let libName = result.data.dispName;
  900. let createDate = result.data.createDate.split(' ')[0];
  901. let compilationName = result.data.compilationName;
  902. dispNamesArr.push(libName);
  903. $("#showArea").append(
  904. "<tr id='"+id+"'>" +
  905. "<td><a href='/rationRepository/ration?repository=" + id +"'>"+libName+"</a></td>" +
  906. "<td>"+compilationName+" </td>" +
  907. "<td>"+createDate+" </td>" +
  908. "<td><a href='javascript:void(0);' data-toggle='modal' data-target='#edit' title='编辑'>" +
  909. "<i class='fa fa-pencil-square-o'></i></a> <a href='javascript:void(0);' data-toggle='modal' data-target='#del' class='text-danger' title='删除'>" +
  910. "<i class='fa fa-remove'></i></a>" +
  911. " <a href='javascript:void(0);' data-toggle='modal' data-target='#reCalcAll' title='全部计算'><i class='fa fa-calculator'></i></a>"+
  912. "<td><a class='btn btn-secondary btn-sm import-source' href='javacript:void(0);' data-id='"+ id +"' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
  913. "<td><a class='btn btn-success btn-sm export' href='javacript:void(0);' data-toggle='modal' data-id='"+ id +"' data-target='#emport' title='导出内部数据'><i class='fa fa-sign-out fa-rotate-270'></i>导出</a> " +
  914. "<a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入内部数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
  915. "<td><a class='btn btn-secondary btn-sm transfer-excel' data-toggle='modal' data-target='#transfer' href='javacript:void(0);' data-id='"+ id +"' title='转换Excel'><i class='fa fa-sign-in fa-rotate-90'></i>转换</a></td>" +
  916. "<td><a class='btn btn-secondary btn-sm set-comple' href='javacript:void(0);' data-id='"+ id +"' title='将章节树设为补充模板数据'><i class='fa fa-sign-in fa-rotate-90'></i>设置</a></td>" +
  917. "</tr>");
  918. }
  919. $('#cancelBtn').click();
  920. }
  921. })
  922. }
  923. function renameRationLib(renameObj, dispNames){
  924. $.ajax({
  925. type: 'post',
  926. url: 'api/editRationLibs',
  927. data: {oprtor: userAccount, renameObj: JSON.stringify(renameObj)},
  928. dataType: 'json',
  929. success: function (result) {
  930. if(!result.error){
  931. let jqSel = "#" + renameObj.ID + " td:first" + " a";
  932. $(jqSel).text(renameObj.newName);
  933. let index = dispNames.indexOf(renameObj.orgName);
  934. dispNames.splice(index, 1);
  935. dispNames.splice(index, 0, renameObj.newName);
  936. }
  937. $('#editCancelBtn').click();
  938. $('#renameText').val('');
  939. }
  940. })
  941. }
  942. function removeRationLib(delObj, dispNames){
  943. $.bootstrapLoading.start();
  944. $.ajax({
  945. type: 'post',
  946. url: 'api/deleteRationLibs',
  947. data: {oprtor: userAccount, libId: delObj.libId},
  948. dataType: 'json',
  949. success: function (result) {
  950. if(!result.error){
  951. var jqSel = "#"+ delObj.libId;
  952. $(jqSel).remove();
  953. let index = dispNames.indexOf(delObj.libName);
  954. dispNames.splice(index, 1);
  955. $('#delCancelBtn').click();
  956. }
  957. $.bootstrapLoading.end();
  958. },
  959. error: function () {
  960. alert('删除失败');
  961. $.bootstrapLoading.end();
  962. }
  963. })
  964. }