priceEmpty.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // 空数据表
  2. const EMPTY_BOOK = (() => {
  3. const setting = {
  4. header: [
  5. { headerName: '主从对应码', headerWidth: 100, dataCode: 'code', dataType: 'String', hAlign: 'left', vAlign: 'center', formatter: "@" },
  6. { headerName: '别名编码', headerWidth: 70, dataCode: 'classCode', dataType: 'String', hAlign: 'left', vAlign: 'center', formatter: "@" },
  7. { headerName: '计算式', headerWidth: 100, dataCode: 'expString', dataType: 'String', hAlign: 'left', vAlign: 'center' },
  8. { headerName: '材料名称', headerWidth: 275, dataCode: 'name', dataType: 'String', hAlign: 'left', vAlign: 'center' },
  9. { headerName: '规格型号', headerWidth: 180, dataCode: 'specs', dataType: 'String', hAlign: 'left', vAlign: 'center' },
  10. { headerName: '单位', headerWidth: 80, dataCode: 'unit', dataType: 'String', hAlign: 'center', vAlign: 'center' },
  11. ],
  12. };
  13. // 初始化表格
  14. const workBookObj = {
  15. book: null,
  16. sheet: null,
  17. };
  18. const buildWorkBook = () => {
  19. workBookObj.book = initSheet($('.empty-spread')[0], setting);
  20. workBookObj.book.options.allowUserDragDrop = true;
  21. workBookObj.book.options.allowUserDragFill = true;
  22. workBookObj.book.options.allowExtendPasteRange = false;
  23. lockUtil.lockSpreads([workBookObj.book], locked);
  24. workBookObj.sheet = workBookObj.book.getSheet(0);
  25. }
  26. // 总数据(数据没合并前)
  27. let totalData = [];
  28. let totalMap = {};
  29. // 表格显示的数据(合并后)
  30. const cache = [];
  31. const getCompareKey = (item) => {
  32. const props = ['name', 'specs', 'unit'];
  33. return props.map(prop => item[prop] ? item[prop].trim() : '').join('@');
  34. }
  35. const setTotalMap = (items) => {
  36. totalMap = {};
  37. items.forEach(item => {
  38. const key = getCompareKey(item);
  39. if (totalMap[key]) {
  40. totalMap[key].push(item);
  41. } else {
  42. totalMap[key] = [item];
  43. }
  44. })
  45. }
  46. // 获取表格数据,汇总空数据,多地区可能存在相同材料,按名称规格单位做筛选,重复材料仅显示一条即可
  47. const getTableData = (items) => {
  48. const map = {};
  49. items.forEach(item => {
  50. const key = getCompareKey(item);
  51. if (!map[key]) {
  52. map[key] = { ...item };
  53. }
  54. });
  55. return Object.values(map);
  56. }
  57. // 根据表格数据,获取实际信息价数据(一对多)
  58. const getItemsFromTableItem = (item) => {
  59. const key = getCompareKey(item);
  60. return totalMap[key] || [];
  61. }
  62. // 获取材料关键字: 名称 规格
  63. const getKeyword = (item) => {
  64. // return item ? `${item.name} ${item.specs}` : '';
  65. return item ? `${item.name}` : '';
  66. }
  67. // 改变关键字
  68. const changeKeyword = (item) => {
  69. const keyword = getKeyword(item);
  70. $('#recommend-search').val(keyword);
  71. if (!keyword) {
  72. RECOMMEND_BOOK.clear();
  73. } else {
  74. RECOMMEND_BOOK.loadRecommendData(keyword);
  75. }
  76. }
  77. // 清空
  78. function clear() {
  79. cache.length = 0;
  80. workBookObj.sheet.setRowCount(0);
  81. }
  82. let curRow = 0;
  83. // 初始化数据
  84. async function initData() {
  85. clear();
  86. curRow = 0;
  87. $.bootstrapLoading.start();
  88. try {
  89. const matchAll = $('#match-all-input')[0].checked;
  90. const areaID = matchAll ? '' : AREA_BOOK.curArea?.ID;
  91. totalData = await ajaxPost('/priceInfo/getPriceEmptyData', { libID, compilationID, areaID }, 1000 * 60 * 10);
  92. setTotalMap(totalData);
  93. const tableData = getTableData(totalData);
  94. cache.push(...tableData)
  95. showData(workBookObj.sheet, cache, setting.header);
  96. changeKeyword(cache[0]);
  97. } catch (err) {
  98. clear();
  99. alert(err);
  100. } finally {
  101. $.bootstrapLoading.end();
  102. }
  103. }
  104. // 编辑处理
  105. async function handleEdit(changedCells, diffMap, needRefresh, saveAll) {
  106. const postData = []; // 请求用
  107. // 更新缓存用
  108. const updateData = [];
  109. const deleteData = [];
  110. const insertData = [];
  111. try {
  112. changedCells.forEach(({ row }) => {
  113. if (cache[row]) {
  114. const rowData = getRowData(workBookObj.sheet, row, setting.header);
  115. if (Object.keys(rowData).length) { // 还有数据,更新
  116. let diffData;
  117. if (diffMap) {
  118. diffData = diffMap[row];
  119. } else {
  120. diffData = saveAll ? getRowAllData(rowData, setting.header) : getRowDiffData(rowData, cache[row], setting.header);
  121. }
  122. if (diffData) {
  123. // 改一行, 实际可能是改多行,表格一行数据是多行合并显示的
  124. const items = getItemsFromTableItem(cache[row]);
  125. items.forEach(item => {
  126. // 只有珠海建筑才更新计算式
  127. const updateObj = { ...diffData };
  128. const area = AREA_BOOK.cache.find(areaItem => areaItem.ID === item.areaID);
  129. if (diffMap) {
  130. delete updateObj.expString;
  131. delete diffData.expString;
  132. }
  133. postData.push({ type: UpdateType.UPDATE, ID: item.ID, areaID: area.ID, compilationID, period: curLibPeriod, data: updateObj });
  134. });
  135. updateData.push({ row, data: diffData });
  136. }
  137. } else { // 该行无数据了,删除
  138. const items = getItemsFromTableItem(cache[row]);
  139. items.forEach(item => {
  140. const area = AREA_BOOK.cache.find(areaItem => areaItem.ID === item.areaID);
  141. postData.push({ type: UpdateType.DELETE, areaID: area.ID, compilationID, period: curLibPeriod, ID: item.ID });
  142. });
  143. deleteData.push(cache[row]);
  144. }
  145. }
  146. });
  147. if (postData.length) {
  148. if (!saveAll) {
  149. $.bootstrapLoading.start();
  150. }
  151. await ajaxPost('/priceInfo/editPriceData', { postData }, TIME_OUT);
  152. // 更新缓存,先更新然后删除,最后再新增,防止先新增后缓存数据的下标与更新、删除数据的下标对应不上
  153. updateData.forEach(item => {
  154. // 更新总表
  155. const curItem = cache[item.row];
  156. const compareKey = getCompareKey(curItem);
  157. const totalItems = totalMap[compareKey];
  158. if (totalItems) {
  159. const newCompareKey = getCompareKey({ ...curItem, ...item.data });
  160. totalItems.forEach(totalItem => {
  161. Object.assign(totalItem, item.data);
  162. });
  163. if (newCompareKey !== compareKey) {
  164. totalMap[newCompareKey] = totalItems;
  165. delete totalMap[compareKey];
  166. }
  167. }
  168. // 更新表格缓存
  169. Object.assign(cache[item.row], item.data);
  170. });
  171. deleteData.forEach(item => {
  172. // 更新总表
  173. const compareKey = getCompareKey(item);
  174. const totalItems = totalMap[compareKey];
  175. if (totalItems) {
  176. const totalItemIDs = totalItems.map(item => item.ID);
  177. totalData = totalData.filter(totalItem => !totalItemIDs.includes(totalItem));
  178. delete totalMap[compareKey];
  179. }
  180. // 更新表格缓存
  181. const index = cache.indexOf(item);
  182. if (index >= 0) {
  183. cache.splice(index, 1);
  184. }
  185. });
  186. insertData.forEach(item => cache.push(item));
  187. if (deleteData.length || insertData.length || needRefresh) {
  188. showData(workBookObj.sheet, cache, setting.header);
  189. }
  190. if (!saveAll) {
  191. $.bootstrapLoading.end();
  192. }
  193. CLASS_BOOK.reload();
  194. }
  195. } catch (err) {
  196. // 恢复各单元格数据
  197. showData(workBookObj.sheet, cache, setting.header);
  198. $.bootstrapLoading.end();
  199. }
  200. }
  201. // 跟新行的编号、编码编码
  202. async function updateRowCode(code, classCode, expString) {
  203. const item = cache[curRow];
  204. if (!item) {
  205. return;
  206. }
  207. const diffData = { code, classCode, expString };
  208. await handleEdit([{ row: curRow }], { [curRow]: diffData }, true);
  209. }
  210. const bindEvent = () => {
  211. workBookObj.sheet.bind(GC.Spread.Sheets.Events.ValueChanged, function (e, info) {
  212. const changedCells = [{ row: info.row }];
  213. handleEdit(changedCells);
  214. });
  215. workBookObj.sheet.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e, info) {
  216. const row = info.newSelections && info.newSelections[0] ? info.newSelections[0].row : 0;
  217. if (curRow !== row) {
  218. const item = cache[row];
  219. changeKeyword(item);
  220. }
  221. curRow = row;
  222. });
  223. workBookObj.sheet.bind(GC.Spread.Sheets.Events.RangeChanged, function (e, info) {
  224. const changedRows = [];
  225. let preRow;
  226. info.changedCells.forEach(({ row }) => {
  227. if (row !== preRow) {
  228. changedRows.push({ row });
  229. }
  230. preRow = row;
  231. });
  232. handleEdit(changedRows);
  233. });
  234. }
  235. // 将空表的表格保存至总表
  236. const saveInSummary = async () => {
  237. const documents = [];
  238. const removeIDs = [];
  239. cache.filter(item => item.code && item.classCode).forEach(item => {
  240. removeIDs.push(item.ID);
  241. documents.push({
  242. ID: uuid.v1(),
  243. code: item.code ? item.code.trim() : '',
  244. classCode: item.classCode ? item.classCode.trim() : '',
  245. expString: item.expString ? item.expString.trim() : '',
  246. name: item.name ? item.name.trim() : '',
  247. specs: item.specs ? item.specs.trim() : '',
  248. unit: item.unit ? item.unit.trim() : '',
  249. });
  250. });
  251. if (!documents.length) {
  252. alert('不存在可保存数据');
  253. return;
  254. }
  255. console.log(documents);
  256. try {
  257. $.bootstrapLoading.progressStart('保存至总表', true);
  258. $("#progress_modal_body").text('正在保存至总表,请稍后...');
  259. await ajaxPost('/priceInfoSummary/saveInSummary', { documents }, 1000 * 60 * 5);
  260. setTimeout(() => {
  261. $.bootstrapLoading.progressEnd();
  262. alert('保存成功');
  263. const filterCache = cache.filter(item => !removeIDs.includes(item.ID));
  264. cache.length = 0;
  265. cache.push(...filterCache);
  266. showData(workBookObj.sheet, cache, setting.header);
  267. }, 1000);
  268. } catch (error) {
  269. setTimeout(() => {
  270. $.bootstrapLoading.progressEnd();
  271. }, 500);
  272. console.log(error);
  273. alert(error);
  274. }
  275. }
  276. // 获取最大别名编码
  277. const getMaxClassCode = (priceInfoSummary) => {
  278. let maxClassCode = '';
  279. let maxClassNumber = 0;
  280. priceInfoSummary.forEach(item => {
  281. if (!item.classCode) {
  282. return;
  283. }
  284. const numMatch = item.classCode.match(/\d+/);
  285. if (numMatch && +numMatch[0] > maxClassNumber) {
  286. maxClassNumber = +numMatch[0];
  287. maxClassCode = item.classCode;
  288. }
  289. });
  290. // return { maxClassNumber, maxClassCode };
  291. return maxClassCode;
  292. }
  293. // 在最大别名编码基础上+1;
  294. const getNewMaxClassCode = (maxClassCode) => {
  295. const numMatch = maxClassCode.match(/\d+/);
  296. if (!numMatch) {
  297. return 1;
  298. }
  299. const maxNumber = +numMatch[0];
  300. let newMaxClassCode = String(maxNumber + 1);
  301. // 补齐的位数
  302. const pattern = numMatch[0].length - newMaxClassCode.length;
  303. if (pattern > 0) {
  304. for (let i = 0; i < pattern; i++) {
  305. newMaxClassCode = `0${newMaxClassCode}`;
  306. }
  307. }
  308. return newMaxClassCode;
  309. }
  310. const getFourCode = (code) => {
  311. if (!code) {
  312. return '';
  313. }
  314. return code.substring(0, 4);
  315. }
  316. // ai填值
  317. const aiMatch = async () => {
  318. try {
  319. // 获取信息价总表
  320. const priceInfoSummary = await ajaxPost('/priceInfoSummary/getData', {}, 1000 * 60 * 5);
  321. const summaryGroupMap = _.groupBy(priceInfoSummary, item => getFourCode(item.code));
  322. const noCodeSummary = priceInfoSummary.filter(item => !item.code);
  323. const totalRows = workBookObj.sheet.getRowCount();
  324. const changedCells = [];
  325. const noMatchRows = []; // 没有匹配、ai没有命中的行,后续需要自动生成别名编码(最大的别名编码+1)
  326. for (let i = 0; i < totalRows; i++) {
  327. const rowData = getRowData(workBookObj.sheet, i, setting.header);
  328. const code = getFourCode(rowData.code);
  329. const toMatchSummary = code ? summaryGroupMap[code] || [] : noCodeSummary;
  330. if (toMatchSummary.length) {
  331. changedCells.push({ row: i });
  332. } else {
  333. noMatchRows.push(i);
  334. }
  335. }
  336. const classCodeCol = setting.header.findIndex(h => h.dataCode === 'classCode');
  337. const expStringCol = setting.header.findIndex(h => h.dataCode === 'expString');
  338. if (!changedCells.length) {
  339. return;
  340. }
  341. const chunks = _.chunk(changedCells, 1); // 改成只能一条一条匹配,否则会很慢。经常把ai服务弄挂
  342. let percent = 0;
  343. $.bootstrapLoading.progressStart('AI填值', false);
  344. $("#progress_modal_body").text('正在进行AI填值,请稍后...');
  345. await setTimeoutSync(500);
  346. const matchResCache = {};
  347. // 分块进行ai匹配
  348. const step = 100 / (chunks.length || 1);
  349. for (let i = 0; i < chunks.length; i++) {
  350. const chunk = chunks[i];
  351. const listA = [];
  352. const listB = [];
  353. const summaryData = [];
  354. chunk.forEach(item => {
  355. const rowData = getRowData(workBookObj.sheet, item.row, setting.header);
  356. listA.push(`${rowData.name || ''} ${rowData.specs}`);
  357. const code = getFourCode(rowData.code);
  358. const toMatchSummary = code ? summaryGroupMap[code] || [] : noCodeSummary;
  359. summaryData.push(toMatchSummary);
  360. const summaryKeys = toMatchSummary.map(summary => `${summary.name || ''} ${summary.specs || ''}`);
  361. listB.push(summaryKeys)
  362. });
  363. const test = listB.map(item => item.length);
  364. console.log(test);
  365. const matchRes = matchResCache[listA[0]] ? matchResCache[listA[0]] : await ajaxPost('/priceInfoSummary/aiMatch', { listA, listB }, 1000 * 60 * 5);
  366. matchResCache[listA[0]] = matchRes;
  367. // 填匹配值到表格,不实时保存,因为需要人工核查
  368. workBookObj.sheet.suspendEvent();
  369. workBookObj.sheet.suspendPaint();
  370. matchRes.forEach((item, index) => {
  371. const firstMatch = item[0];
  372. const chunkItem = chunk[index];
  373. const summaryIndex = item[0].index;
  374. const summaryItem = summaryData[index][summaryIndex];
  375. const curUnit = cache[chunkItem.row]?.unit || '';
  376. const summaryItemUnit = summaryItem?.unit || '';
  377. // 相似度过低的不命中
  378. if (firstMatch.similarity < 70 || curUnit !== summaryItemUnit) {
  379. noMatchRows.push(chunkItem.row);
  380. return;
  381. };
  382. if (chunkItem && summaryItem) {
  383. workBookObj.sheet.setValue(chunkItem.row, classCodeCol, summaryItem.classCode);
  384. cache[chunkItem.row].classCode = summaryItem.classCode;
  385. const items = getItemsFromTableItem(cache[chunkItem.row]);
  386. items.forEach(item => {
  387. item.classCode = summaryItem.classCode;
  388. });
  389. // 如果实际行存在珠海地区的,才填计算式
  390. const tableItems = getItemsFromTableItem(cache[chunkItem.row]);
  391. const needExpString = tableItems.some(tItem => {
  392. const area = AREA_BOOK.cache.find(areaItem => areaItem.ID === tItem.areaID)
  393. return area && area.name && /珠海/.test(area.name);
  394. });
  395. if (needExpString) {
  396. workBookObj.sheet.setValue(chunkItem.row, expStringCol, summaryItem.expString);
  397. cache[chunkItem.row].expString = summaryItem.expString;
  398. items.forEach(item => {
  399. item.expString = summaryItem.expString;
  400. })
  401. }
  402. }
  403. });
  404. workBookObj.sheet.resumeEvent();
  405. workBookObj.sheet.resumePaint();
  406. percent += step;
  407. $('#progress_modal_body').text(`正在进行AI填值,请稍后${i + 1}/${chunks.length}...`);
  408. $("#progress_modal_bar").css('width', `${percent}%`);
  409. await setTimeoutSync(500);
  410. }
  411. // 没匹配到的行,自动生成别名编码
  412. workBookObj.sheet.suspendEvent();
  413. workBookObj.sheet.suspendPaint();
  414. let curMaxClassCode = getMaxClassCode(priceInfoSummary);
  415. for (const row of noMatchRows) {
  416. const newClassCode = getNewMaxClassCode(curMaxClassCode);
  417. workBookObj.sheet.setValue(row, classCodeCol, newClassCode);
  418. cache[row].classCode = newClassCode;
  419. const items = getItemsFromTableItem(cache[row]);
  420. items.forEach(item => {
  421. item.classCode = newClassCode;
  422. });
  423. curMaxClassCode = newClassCode;
  424. }
  425. workBookObj.sheet.resumeEvent();
  426. workBookObj.sheet.resumePaint();
  427. } catch (error) {
  428. console.log(error);
  429. alert(error);
  430. }
  431. await setTimeoutSync(500);
  432. $.bootstrapLoading.progressEnd();
  433. }
  434. // 保存ai填值
  435. const saveData = async () => {
  436. try {
  437. // 分批保存数据,以免数据库压力过大
  438. const totalRows = workBookObj.sheet.getRowCount();
  439. const changedCells = [];
  440. for (let i = 0; i < totalRows; i++) {
  441. changedCells.push({ row: i });
  442. }
  443. if (!changedCells.length) {
  444. return;
  445. }
  446. $.bootstrapLoading.progressStart('保存AI填值', false);
  447. $("#progress_modal_body").text('正在保存AI填值,请稍后...');
  448. await setTimeoutSync(500);
  449. const chunks = _.chunk(changedCells, 100);
  450. let percent = 0;
  451. const step = 100 / (chunks.length || 1);
  452. for (const chunk of chunks) {
  453. await handleEdit(chunk, undefined, undefined, true);
  454. percent += parseInt(`${step}`);
  455. $("#progress_modal_bar").css('width', `${percent}%`);
  456. await setTimeoutSync(200);
  457. }
  458. } catch (error) {
  459. console.log(error);
  460. alert(error);
  461. }
  462. setTimeout(() => {
  463. $.bootstrapLoading.progressEnd();
  464. }, 500);
  465. }
  466. return {
  467. buildWorkBook,
  468. bindEvent,
  469. clear,
  470. initData,
  471. workBookObj,
  472. updateRowCode,
  473. saveInSummary,
  474. aiMatch,
  475. saveData,
  476. }
  477. })();
  478. $(document).ready(() => {
  479. $('#empty-area').on('shown.bs.modal', function () {
  480. if (!EMPTY_BOOK.workBookObj.book) {
  481. EMPTY_BOOK.buildWorkBook();
  482. EMPTY_BOOK.bindEvent();
  483. }
  484. EMPTY_BOOK.initData();
  485. });
  486. $('#empty-area').on('hidden.bs.modal', function () {
  487. EMPTY_BOOK.clear();
  488. });
  489. // 保存至总表
  490. $('#save-in-summary').click(() => {
  491. EMPTY_BOOK.saveInSummary();
  492. });
  493. // AI填值
  494. $('#ai-match').click(() => {
  495. EMPTY_BOOK.aiMatch();
  496. })
  497. // 保存AI填值
  498. $('#save-data').click(() => {
  499. EMPTY_BOOK.saveData();
  500. })
  501. });