LuckySheet.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import React from 'react';
  2. import { message } from 'antd';
  3. import exportExcel, { getExcelBolob } from '@/utils/exportExcl';
  4. import LuckyExcel from 'luckyexcel';
  5. import { getToken } from '@/utils/utils';
  6. const hintText = '禁止编辑!请先点击编辑按钮。';
  7. const DIFF_COLOR = '#ff0000';
  8. const ADD_COLOR = '#00ff00';
  9. class LuckySheet extends React.Component {
  10. constructor(props) {
  11. super(props);
  12. this.sheetRef = React.createRef();
  13. this.luckysheet = null;
  14. this.updateCell = {
  15. add: [],
  16. diff: [],
  17. };
  18. this.renderTimer = null;
  19. this.chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  20. }
  21. componentWillUnmount() {
  22. this.luckysheet?.destroy();
  23. }
  24. componentDidUpdate(prveProps) {
  25. const prevVersion = prveProps.version || {};
  26. const curVersion = this.props.version || {};
  27. if (prevVersion?.id != curVersion?.id || prevVersion?.flow_id != curVersion.flow_id) {
  28. console.log(prevVersion, curVersion);
  29. this.renderSheet();
  30. }
  31. }
  32. getUUID(len = 8, radix = 16) {
  33. var chars = this.chars;
  34. var uuid = [],
  35. i;
  36. radix = radix || chars.length;
  37. if (len) {
  38. // Compact form
  39. for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  40. } else {
  41. // rfc4122, version 4 form
  42. var r;
  43. // rfc4122 requires these characters
  44. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  45. uuid[14] = '4';
  46. // Fill in random data. At i==19 set the high bits of clock sequence as
  47. // per rfc4122, sec. 4.1.5
  48. for (i = 0; i < 36; i++) {
  49. if (!uuid[i]) {
  50. r = 0 | (Math.random() * 16);
  51. uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
  52. }
  53. }
  54. }
  55. return uuid.join('');
  56. }
  57. renderSheet(currentData) {
  58. const { onClickCell, version, getUser, onUpdate, templateId } = this.props;
  59. const data = currentData || this.props.data;
  60. if (!this.luckysheet) {
  61. clearTimeout(this.renderTimer);
  62. this.renderTimer = setTimeout(() => {
  63. this.renderSheet(currentData);
  64. }, 300);
  65. return;
  66. }
  67. let token = getToken();
  68. let option = {
  69. lang: 'zh',
  70. showinfobar: false,
  71. showstatisticBar: false,
  72. hook: {
  73. cellMousedown: (cell, position, sheet) => {
  74. onClickCell && onClickCell(cell, position, sheet);
  75. },
  76. cellPasteBefore: cell => {
  77. console.log(cell);
  78. if (!cell) return;
  79. if (cell.cid) delete cell.cid;
  80. if (cell.bg == DIFF_COLOR || cell.bg == ADD_COLOR) {
  81. delete cell.bg;
  82. }
  83. },
  84. updated(operate) {
  85. console.log(operate);
  86. onUpdate && onUpdate();
  87. },
  88. },
  89. };
  90. if (version) {
  91. option = {
  92. ...option,
  93. allowUpdate: true,
  94. gridKey: version.id,
  95. templateId: templateId,
  96. // flowId: version.flow_id,
  97. loadUrl: `/api/v1/purchase/record/sheet?gridKey=${version.id}&JWT-TOKEN=${token}`,
  98. updateUrl: `ws://47.96.12.136:8896/api/v1/ws?id=${version.id}&sid=${templateId}&JWT-TOKEN=${token}`,
  99. authorityUrl: `/api/v1/purchase/bom/user/excel/col?depId=${localStorage.depId}&JWT-TOKEN=${token}`,
  100. getUser,
  101. // workbookCreateBefore(luckysheet) {
  102. // console.log('===============================', luckysheet);
  103. // let oldConfig = JSON.parse(JSON.stringify(luckysheet.getConfig()));
  104. // setTimeout(() => {
  105. // luckysheet.setConfig({
  106. // ...oldConfig,
  107. // authority: { sheet: true, hintText },
  108. // });
  109. // }, 300);
  110. // },
  111. };
  112. console.log(version);
  113. if (version.flow_id) {
  114. option.authority = {
  115. sheet: true,
  116. hintText: '当前处于审批节点,禁止编辑!',
  117. };
  118. } else if (version.audit_status != 0 || version.status == 1) {
  119. option.authority = {
  120. sheet: true,
  121. hintText: '当前清单不可编辑!',
  122. };
  123. }
  124. } else if (data && data.length > 0) {
  125. option.data = JSON.parse(JSON.stringify(data));
  126. option.data.forEach(item => {
  127. if (item.celldata) {
  128. item.celldata.forEach(cell => {
  129. // 生成uuid
  130. if (!cell.v.cid) cell.v.cid = this.getUUID();
  131. });
  132. }
  133. // 默认禁止编辑
  134. // item.config.authority = { sheet: true, hintText };
  135. });
  136. } else {
  137. // 默认sheet页数据
  138. data.data = [
  139. {
  140. name: 'sheet1',
  141. // config: {
  142. // authority: { sheet: true, hintText },
  143. // },
  144. },
  145. ];
  146. }
  147. this.luckysheet.destroy();
  148. this.luckysheet.create(option);
  149. }
  150. // componentDidUpdate(prevProps) {
  151. // const { data } = this.props;
  152. // if (prevProps.data != data) {
  153. // this.renderSheet(data);
  154. // }
  155. // }
  156. handleLoad() {
  157. const { version } = this.props;
  158. let contentWindow = this.sheetRef.current.contentWindow;
  159. this.luckysheet = contentWindow.luckysheet;
  160. // this.luckysheet = this.luckysheet;
  161. // version存在 则需调用render
  162. if (version) {
  163. this.renderSheet();
  164. }
  165. // onLoad && onLoad();
  166. }
  167. selectCell(row, col, order) {
  168. this.luckysheet.setRangeShow({ row: [row, row], column: [col, col] }, { order });
  169. }
  170. toggleSheet(order) {
  171. this.luckysheet.setSheetActive(order);
  172. }
  173. getSheetJson() {
  174. let data = JSON.parse(JSON.stringify(this.luckysheet.toJson()));
  175. data.data.forEach(sheet => {
  176. let allCell = {},
  177. unknowCid = [];
  178. // 将cell以cid为界分别存储
  179. (sheet.celldata || []).forEach(cell => {
  180. if (!cell.v.cid) {
  181. unknowCid.push(cell);
  182. } else {
  183. allCell[cell.v.cid] = cell;
  184. }
  185. // 清除比对样式
  186. if (cell.v.bg == DIFF_COLOR || cell.v.bg == ADD_COLOR) {
  187. delete cell.v.bg;
  188. }
  189. });
  190. unknowCid.forEach(cell => {
  191. // 根据坐标生成唯一key,重复则增加后缀直至不重复
  192. let key = `${cell.r}-${cell.c}`;
  193. while (allCell[key]) {
  194. key += '|c';
  195. }
  196. cell.v.cid = key;
  197. allCell[key] = cell;
  198. });
  199. sheet.celldata = Object.values(allCell);
  200. });
  201. return data;
  202. }
  203. // 切换编辑状态
  204. toggleEdit(edit) {
  205. let luckysheet = this.luckysheet;
  206. if (edit) {
  207. let config = luckysheet.getConfig();
  208. luckysheet.setConfig({
  209. ...config,
  210. authority: { sheet: !edit, hintText },
  211. });
  212. } else {
  213. luckysheet.exitEditMode();
  214. }
  215. }
  216. // 切换比对状态
  217. toggleCompare(isCompare, compareData, callback) {
  218. let luckysheet = this.luckysheet;
  219. let diff = [];
  220. let add = [];
  221. const { onCompareSuccess } = this.props;
  222. // 判断dom是否加载完成
  223. if (!luckysheet) {
  224. setTimeout(() => {
  225. this.toggleCompare(isCompare, compareData, callback);
  226. }, 300);
  227. return;
  228. }
  229. if (isCompare) {
  230. // let currentData = this.luckysheet.toJson();
  231. let currentData = JSON.parse(JSON.stringify(this.props.data));
  232. currentData.forEach((sheet, index) => {
  233. let celldata1 = sheet.celldata;
  234. let celldata2 = compareData[index]?.celldata || [];
  235. celldata1.forEach(item => {
  236. // 不判断空字符串
  237. if (this.isEmpty(item)) return;
  238. var d2Item = celldata2.find(item2 => item2.v.cid == item.v.cid);
  239. if (d2Item && !this.isEmpty(d2Item)) {
  240. // v.ct.s相同,不做处理
  241. if (item.v.ct?.s && JSON.stringify(item.v.ct?.s) == JSON.stringify(d2Item.v.ct?.s))
  242. return;
  243. // v.v相同,不做处理
  244. if (d2Item.v.v == item.v.v) return;
  245. // 内容不同,标记diff颜色
  246. diff.push({
  247. ...item,
  248. sheetOrder: index,
  249. });
  250. item.v.bg = DIFF_COLOR;
  251. // luckysheet.setCellFormat(item.r, item.c, 'bg', DIFF_COLOR);
  252. } else {
  253. // 找不到同cid的单元格,标记add颜色
  254. add.push({
  255. ...item,
  256. sheetOrder: index,
  257. });
  258. item.v.bg = ADD_COLOR;
  259. // luckysheet.setCellFormat(item.r, item.c, 'bg', ADD_COLOR);
  260. }
  261. });
  262. });
  263. // console.log(currentData);
  264. this.renderSheet(currentData);
  265. // luckysheet.refresh()
  266. } else {
  267. this.renderSheet(this.props.data);
  268. }
  269. this.updateCell = {
  270. diff,
  271. add,
  272. };
  273. callback && callback(this.updateCell);
  274. }
  275. isEmpty(item) {
  276. return (item?.v?.v ?? '') === '' && !item?.v?.ct?.s;
  277. }
  278. mergeExcl(updateCell = {}) {
  279. const { diff = [], add = [] } = updateCell;
  280. let currentData = this.luckysheet.toJson().data;
  281. let luckysheet = this.luckysheet;
  282. console.log(updateCell);
  283. diff.forEach(item => {
  284. let sheet = currentData[item.sheetOrder];
  285. let d1Item = sheet.celldata.find(item2 => item2.v.cid == item.v.cid);
  286. // 将差异项覆盖至当前文档
  287. d1Item.v = {
  288. ...item.v,
  289. bg: undefined,
  290. };
  291. });
  292. add.forEach(item => {
  293. // 将新增项添加至当前文档
  294. let sheet = currentData[item.sheetOrder];
  295. let d1Item = sheet.celldata.find(item2 => item2.r == item.r && item2.c == item.c);
  296. if (d1Item) {
  297. d1Item.v = {
  298. ...item.v,
  299. bg: undefined,
  300. };
  301. } else {
  302. sheet.celldata.push({
  303. ...item,
  304. sheetOrder: undefined,
  305. });
  306. }
  307. });
  308. currentData.forEach(sheet => {
  309. delete sheet.data;
  310. });
  311. this.renderSheet(currentData);
  312. // currentData.data.forEach((sheet, index) => {
  313. // if (!mergeData[index]) return;
  314. // let celldata1 = sheet.celldata;
  315. // let celldata2 = mergeData[index].celldata;
  316. // celldata2.forEach(item => {
  317. // let bg = item.v?.bg;
  318. // let d1Item;
  319. // if (bg == DIFF_COLOR) {
  320. // delete item.v.bg;
  321. // d1Item = celldata1.find(item2 => item2.v.cid == item.v.cid);
  322. // // 将差异项覆盖至当前文档
  323. // d1Item.v = item.v;
  324. // // luckysheet.setCellValue(d1Item.r, d1Item.c, item.v);
  325. // } else if (bg == ADD_COLOR) {
  326. // delete item.v.bg;
  327. // // 将新增项添加至当前文档
  328. // // luckysheet.setCellValue(item.r, item.c, item.v);
  329. // d1Item = celldata1.find(item2 => item2.r == item.r && item2.c == item.c);
  330. // if (d1Item) {
  331. // d1Item.v = item.v;
  332. // } else {
  333. // celldata1.push(item);
  334. // }
  335. // }
  336. // });
  337. // });
  338. // this.renderSheet(currentData);
  339. }
  340. /**
  341. * 导入excl
  342. * @param {*} files input:file的evt.target.files
  343. * @returns
  344. */
  345. uploadExcel(files, callback) {
  346. if (files == null || files.length == 0) {
  347. return;
  348. }
  349. let name = files[0].name;
  350. let suffixArr = name.split('.'),
  351. suffix = suffixArr[suffixArr.length - 1];
  352. if (suffix != 'xlsx') {
  353. alert('Currently only supports the import of xlsx files');
  354. message.error('只支持xlsx格式的文件!');
  355. return;
  356. }
  357. LuckyExcel.transformExcelToLucky(files[0], (exportJson, luckysheetfile) => {
  358. if (exportJson.sheets == null || exportJson.sheets.length == 0) {
  359. message.error('读取xlsx文件失败!');
  360. return;
  361. }
  362. // this.luckysheet.destroy();
  363. // 同步当前文档内容
  364. let data = this.props.data;
  365. exportJson.sheets.forEach((sheet, index) => {
  366. if (!data || !data[index]) return;
  367. sheet.celldata.forEach(cell => {
  368. if (this.isEmpty(cell)) return;
  369. // return (item.v.v ?? '') === '' && !item.v.ct?.s;
  370. let dCell = (data[index].celldata || []).find(dCell => {
  371. return dCell.r == cell.r && dCell.c == cell.c;
  372. });
  373. if (this.isEmpty(dCell)) return;
  374. // 判断v.ct是否相同
  375. // if (cell?.v?.ct?.s && dCell.v.ct?.s && cell.v.ct?.s.join('') != dCell.v.ct?.s.join('')) return;
  376. if (cell?.v?.ct?.s && dCell.v.ct?.s) {
  377. if (cell.v.ct?.s.join('') != dCell.v.ct?.s.join('')) return;
  378. let cellS = cell.v.ct.s;
  379. let dCellS = dCell.v.ct.s;
  380. let isEqul = cellS.every((cur, idx) => {
  381. return JSON.stringify(cur) === JSON.stringify(dCellS[idx]);
  382. });
  383. if (!isEqul) return;
  384. }
  385. // 判断v.v是否相同
  386. if (cell?.v?.v && dCell.v.v != cell.v.v) return;
  387. // 内容相同则复制cid
  388. cell.cid = dCell.cid;
  389. });
  390. });
  391. this.renderSheet(exportJson.sheets);
  392. callback && callback();
  393. });
  394. }
  395. // 根据url导入excl
  396. // selectExcel(item) {
  397. // const {value,name} = item
  398. // if (value == '') {
  399. // return;
  400. // }
  401. // LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
  402. // if (exportJson.sheets == null || exportJson.sheets.length == 0) {
  403. // alert(
  404. // 'Failed to read the content of the excel file, currently does not support xls files!'
  405. // );
  406. // return;
  407. // }
  408. // this.luckysheet.destroy();
  409. // this.luckysheet.create({
  410. // container: 'luckysheet', //luckysheet is the container id
  411. // showinfobar: false,
  412. // data: exportJson.sheets,
  413. // title: exportJson.info.name,
  414. // userInfo: exportJson.info.name.creator,
  415. // });
  416. // });
  417. // }
  418. getExcelData(checkValue = null) {
  419. let resultList = [];
  420. console.log(this.luckysheet.getAllSheets());
  421. let currentData = this.luckysheet.getAllSheets();
  422. currentData.forEach(sheet => {
  423. let data = sheet.data;
  424. let celldata = sheet.celldata;
  425. let colList = [];
  426. data[0]?.forEach((rowOneItem, colIdx) => {
  427. if (rowOneItem) {
  428. if (!checkValue || checkValue.indexOf(rowOneItem.v) !== -1) {
  429. colList.indexOf(colIdx) == -1 ? colList.push(colIdx) : true;
  430. }
  431. }
  432. });
  433. const newData = [];
  434. data.forEach(item => {
  435. if (item !== null) {
  436. let arr = item.filter((cur, idx) => {
  437. return item && colList.includes(idx);
  438. });
  439. newData.push(arr);
  440. }
  441. });
  442. sheet.data = newData;
  443. //消除空列后都列下标
  444. let newColIdxList = colList.map((cur, idx) => {
  445. return idx;
  446. });
  447. //处理celldata
  448. const newCellData = [];
  449. celldata.forEach(item => {
  450. let idx = colList.indexOf(item.c);
  451. if (idx !== -1) {
  452. item.c = newColIdxList[idx];
  453. newCellData.push(item);
  454. }
  455. });
  456. sheet.celldata = newCellData;
  457. });
  458. return currentData;
  459. }
  460. getExcelBolb() {
  461. let currentData = this.getExcelData();
  462. return getExcelBolob(currentData);
  463. }
  464. downloadExcel(checkValue) {
  465. let currentData = this.getExcelData(checkValue);
  466. exportExcel(currentData, '下载');
  467. }
  468. render() {
  469. return (
  470. <iframe
  471. onLoad={e => {
  472. this.handleLoad(e);
  473. }}
  474. ref={this.sheetRef}
  475. src="/luckysheet.html"
  476. ></iframe>
  477. );
  478. }
  479. }
  480. export default LuckySheet;