priceEmpty.js 17 KB

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