LuckySheet.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import React from 'react';
  2. import { message } from 'antd';
  3. import exportExcel 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. if(version.flow_id) {
  113. option.authority = {
  114. sheet: true,
  115. hintText: '当前处于审批节点,禁止编辑!'
  116. }
  117. } else if(version.audit_status != 0) {
  118. option.authority = {
  119. sheet: true,
  120. hintText: '当前清单不可编辑!'
  121. }
  122. }
  123. } else if (data && data.length > 0) {
  124. option.data = JSON.parse(JSON.stringify(data));
  125. option.data.forEach(item => {
  126. if (item.celldata) {
  127. item.celldata.forEach(cell => {
  128. // 生成uuid
  129. if (!cell.v.cid) cell.v.cid = this.getUUID();
  130. });
  131. }
  132. // 默认禁止编辑
  133. // item.config.authority = { sheet: true, hintText };
  134. });
  135. } else {
  136. // 默认sheet页数据
  137. data.data = [
  138. {
  139. name: 'sheet1',
  140. // config: {
  141. // authority: { sheet: true, hintText },
  142. // },
  143. },
  144. ];
  145. }
  146. this.luckysheet.destroy();
  147. this.luckysheet.create(option);
  148. }
  149. // componentDidUpdate(prevProps) {
  150. // const { data } = this.props;
  151. // if (prevProps.data != data) {
  152. // this.renderSheet(data);
  153. // }
  154. // }
  155. handleLoad() {
  156. const { version } = this.props;
  157. let contentWindow = this.sheetRef.current.contentWindow;
  158. this.luckysheet = contentWindow.luckysheet;
  159. // this.luckysheet = this.luckysheet;
  160. // version存在 则需调用render
  161. if (version) {
  162. this.renderSheet();
  163. }
  164. // onLoad && onLoad();
  165. }
  166. selectCell(row, col, order) {
  167. this.luckysheet.setRangeShow({ row: [row, row], column: [col, col] }, { order });
  168. }
  169. toggleSheet(order) {
  170. this.luckysheet.setSheetActive(order);
  171. }
  172. getSheetJson() {
  173. let data = JSON.parse(JSON.stringify(this.luckysheet.toJson()));
  174. data.data.forEach(sheet => {
  175. let allCell = {},
  176. unknowCid = [];
  177. // 将cell以cid为界分别存储
  178. (sheet.celldata || []).forEach(cell => {
  179. if (!cell.v.cid) {
  180. unknowCid.push(cell);
  181. } else {
  182. allCell[cell.v.cid] = cell;
  183. }
  184. // 清除比对样式
  185. if (cell.v.bg == DIFF_COLOR || cell.v.bg == ADD_COLOR) {
  186. delete cell.v.bg;
  187. }
  188. });
  189. unknowCid.forEach(cell => {
  190. // 根据坐标生成唯一key,重复则增加后缀直至不重复
  191. let key = `${cell.r}-${cell.c}`;
  192. while (allCell[key]) {
  193. key += '|c';
  194. }
  195. cell.v.cid = key;
  196. allCell[key] = cell;
  197. });
  198. sheet.celldata = Object.values(allCell);
  199. });
  200. return data;
  201. }
  202. // 切换编辑状态
  203. toggleEdit(edit) {
  204. let luckysheet = this.luckysheet;
  205. if (edit) {
  206. let config = luckysheet.getConfig();
  207. luckysheet.setConfig({
  208. ...config,
  209. authority: { sheet: !edit, hintText },
  210. });
  211. } else {
  212. luckysheet.exitEditMode();
  213. }
  214. }
  215. // 切换比对状态
  216. toggleCompare(isCompare, compareData, callback) {
  217. let luckysheet = this.luckysheet;
  218. let diff = [];
  219. let add = [];
  220. const { onCompareSuccess } = this.props;
  221. // 判断dom是否加载完成
  222. if (!luckysheet) {
  223. setTimeout(() => {
  224. this.toggleCompare(isCompare, compareData, callback);
  225. }, 300);
  226. return;
  227. }
  228. if (isCompare) {
  229. // let currentData = this.luckysheet.toJson();
  230. let currentData = JSON.parse(JSON.stringify(this.props.data));
  231. currentData.forEach((sheet, index) => {
  232. let celldata1 = sheet.celldata;
  233. let celldata2 = compareData[index]?.celldata || [];
  234. celldata1.forEach(item => {
  235. // 不判断空字符串
  236. if (this.isEmpty(item)) return;
  237. var d2Item = celldata2.find(item2 => item2.v.cid == item.v.cid);
  238. if (d2Item && !this.isEmpty(d2Item)) {
  239. // v.ct.s相同,不做处理
  240. if (item.v.ct?.s && JSON.stringify(item.v.ct?.s) == JSON.stringify(d2Item.v.ct?.s))
  241. return;
  242. // v.v相同,不做处理
  243. if (d2Item.v.v == item.v.v) return;
  244. // 内容不同,标记diff颜色
  245. diff.push({
  246. ...item,
  247. sheetOrder: index,
  248. });
  249. item.v.bg = DIFF_COLOR;
  250. // luckysheet.setCellFormat(item.r, item.c, 'bg', DIFF_COLOR);
  251. } else {
  252. // 找不到同cid的单元格,标记add颜色
  253. add.push({
  254. ...item,
  255. sheetOrder: index,
  256. });
  257. item.v.bg = ADD_COLOR;
  258. // luckysheet.setCellFormat(item.r, item.c, 'bg', ADD_COLOR);
  259. }
  260. });
  261. });
  262. // console.log(currentData);
  263. this.renderSheet(currentData);
  264. // luckysheet.refresh()
  265. } else {
  266. this.renderSheet(this.props.data);
  267. }
  268. this.updateCell = {
  269. diff,
  270. add,
  271. };
  272. callback && callback(this.updateCell);
  273. }
  274. isEmpty(item) {
  275. return (item?.v?.v ?? '') === '' && !item?.v?.ct?.s;
  276. }
  277. mergeExcl(updateCell = {}) {
  278. const { diff = [], add = [] } = updateCell;
  279. let currentData = this.luckysheet.toJson().data;
  280. let luckysheet = this.luckysheet;
  281. console.log(updateCell);
  282. diff.forEach(item => {
  283. let sheet = currentData[item.sheetOrder];
  284. let d1Item = sheet.celldata.find(item2 => item2.v.cid == item.v.cid);
  285. // 将差异项覆盖至当前文档
  286. d1Item.v = {
  287. ...item.v,
  288. bg: undefined,
  289. };
  290. });
  291. add.forEach(item => {
  292. // 将新增项添加至当前文档
  293. let sheet = currentData[item.sheetOrder];
  294. let d1Item = sheet.celldata.find(item2 => item2.r == item.r && item2.c == item.c);
  295. if (d1Item) {
  296. d1Item.v = {
  297. ...item.v,
  298. bg: undefined,
  299. };
  300. } else {
  301. sheet.celldata.push({
  302. ...item,
  303. sheetOrder: undefined,
  304. });
  305. }
  306. });
  307. currentData.forEach(sheet => {
  308. delete sheet.data;
  309. });
  310. this.renderSheet(currentData);
  311. // currentData.data.forEach((sheet, index) => {
  312. // if (!mergeData[index]) return;
  313. // let celldata1 = sheet.celldata;
  314. // let celldata2 = mergeData[index].celldata;
  315. // celldata2.forEach(item => {
  316. // let bg = item.v?.bg;
  317. // let d1Item;
  318. // if (bg == DIFF_COLOR) {
  319. // delete item.v.bg;
  320. // d1Item = celldata1.find(item2 => item2.v.cid == item.v.cid);
  321. // // 将差异项覆盖至当前文档
  322. // d1Item.v = item.v;
  323. // // luckysheet.setCellValue(d1Item.r, d1Item.c, item.v);
  324. // } else if (bg == ADD_COLOR) {
  325. // delete item.v.bg;
  326. // // 将新增项添加至当前文档
  327. // // luckysheet.setCellValue(item.r, item.c, item.v);
  328. // d1Item = celldata1.find(item2 => item2.r == item.r && item2.c == item.c);
  329. // if (d1Item) {
  330. // d1Item.v = item.v;
  331. // } else {
  332. // celldata1.push(item);
  333. // }
  334. // }
  335. // });
  336. // });
  337. // this.renderSheet(currentData);
  338. }
  339. /**
  340. * 导入excl
  341. * @param {*} files input:file的evt.target.files
  342. * @returns
  343. */
  344. uploadExcel(files, callback) {
  345. if (files == null || files.length == 0) {
  346. return;
  347. }
  348. let name = files[0].name;
  349. let suffixArr = name.split('.'),
  350. suffix = suffixArr[suffixArr.length - 1];
  351. if (suffix != 'xlsx') {
  352. alert('Currently only supports the import of xlsx files');
  353. message.error('只支持xlsx格式的文件!');
  354. return;
  355. }
  356. LuckyExcel.transformExcelToLucky(files[0], (exportJson, luckysheetfile) => {
  357. if (exportJson.sheets == null || exportJson.sheets.length == 0) {
  358. message.error('读取xlsx文件失败!');
  359. return;
  360. }
  361. // this.luckysheet.destroy();
  362. // 同步当前文档内容
  363. let data = this.props.data;
  364. exportJson.sheets.forEach((sheet, index) => {
  365. if (!data || !data[index]) return;
  366. sheet.celldata.forEach(cell => {
  367. if (this.isEmpty(cell)) return;
  368. // return (item.v.v ?? '') === '' && !item.v.ct?.s;
  369. let dCell = (data[index].celldata || []).find(dCell => {
  370. return dCell.r == cell.r && dCell.c == cell.c;
  371. });
  372. if (this.isEmpty(dCell)) return;
  373. // 判断v.ct是否相同
  374. // if (cell?.v?.ct?.s && dCell.v.ct?.s && cell.v.ct?.s.join('') != dCell.v.ct?.s.join('')) return;
  375. if (cell?.v?.ct?.s && dCell.v.ct?.s) {
  376. if (cell.v.ct?.s.join('') != dCell.v.ct?.s.join('')) return;
  377. let cellS = cell.v.ct.s;
  378. let dCellS = dCell.v.ct.s;
  379. let isEqul = cellS.every((cur, idx) => {
  380. return JSON.stringify(cur) === JSON.stringify(dCellS[idx]);
  381. });
  382. if (!isEqul) return;
  383. }
  384. // 判断v.v是否相同
  385. if (cell?.v?.v && dCell.v.v != cell.v.v) return;
  386. // 内容相同则复制cid
  387. cell.cid = dCell.cid;
  388. });
  389. });
  390. this.renderSheet(exportJson.sheets);
  391. callback && callback();
  392. });
  393. }
  394. // 根据url导入excl
  395. // selectExcel(item) {
  396. // const {value,name} = item
  397. // if (value == '') {
  398. // return;
  399. // }
  400. // LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
  401. // if (exportJson.sheets == null || exportJson.sheets.length == 0) {
  402. // alert(
  403. // 'Failed to read the content of the excel file, currently does not support xls files!'
  404. // );
  405. // return;
  406. // }
  407. // this.luckysheet.destroy();
  408. // this.luckysheet.create({
  409. // container: 'luckysheet', //luckysheet is the container id
  410. // showinfobar: false,
  411. // data: exportJson.sheets,
  412. // title: exportJson.info.name,
  413. // userInfo: exportJson.info.name.creator,
  414. // });
  415. // });
  416. // }
  417. downloadExcel(checkValue) {
  418. let resultList = [];
  419. console.log(this.luckysheet.getAllSheets());
  420. let currentData = this.luckysheet.getAllSheets();
  421. currentData.forEach(sheet => {
  422. let data = sheet.data;
  423. let celldata = sheet.celldata;
  424. //获取当前导出列的数组
  425. let colList = [];
  426. data[0]?.forEach((rowOneItem, colIdx) => {
  427. if (rowOneItem && checkValue.indexOf(rowOneItem.v) !== -1) {
  428. colList.indexOf(colIdx) == -1 ? colList.push(colIdx) : true;
  429. }
  430. });
  431. //处理data
  432. const newData = [];
  433. data.forEach(item => {
  434. if (item !== null) {
  435. let arr = item.filter((cur, idx) => {
  436. return item && colList.includes(idx);
  437. });
  438. // let len = item.length - arr.length
  439. // let nullList = new Array(len).fill(null);
  440. // let rowList = arr.concat(nullList);
  441. newData.push(arr);
  442. }
  443. });
  444. sheet.data = newData;
  445. //消除空列后都列下标
  446. let newColIdxList = colList.map((cur, idx) => {
  447. return idx;
  448. });
  449. //处理celldata
  450. const newCellData = [];
  451. celldata.forEach(item => {
  452. let idx = colList.indexOf(item.c);
  453. if (idx !== -1) {
  454. item.c = newColIdxList[idx];
  455. newCellData.push(item);
  456. }
  457. });
  458. sheet.celldata = newCellData;
  459. });
  460. exportExcel(currentData, '下载');
  461. }
  462. render() {
  463. return (
  464. <iframe
  465. onLoad={e => {
  466. this.handleLoad(e);
  467. }}
  468. ref={this.sheetRef}
  469. src="/luckysheet.html"
  470. ></iframe>
  471. );
  472. }
  473. }
  474. export default LuckySheet;