index.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /*
  2. * @Author: code4eat awesomedema@gmail.com
  3. * @Date: 2023-03-03 11:30:33
  4. * @LastEditors: code4eat awesomedema@gmail.com
  5. * @LastEditTime: 2024-09-06 13:57:10
  6. * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
  7. * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. */
  9. import KCIMPagecontainer from '@/components/KCIMPageContainer';
  10. import { KCIMTable } from '@/components/KCIMTable';
  11. import { createFromIconfontCN } from '@ant-design/icons';
  12. import { ActionType, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect, ProFormDigit } from '@ant-design/pro-components';
  13. import { ModalForm } from '@ant-design/pro-form'
  14. import { ProColumns } from '@ant-design/pro-table';
  15. import { Modal, message, Drawer, Tabs, Input, DatePicker,Popover } from 'antd';
  16. import { Key, useEffect, useRef, useState } from 'react';
  17. import * as XLSX from 'xlsx';
  18. import { saveAs } from 'file-saver';
  19. import moment from 'moment';
  20. import 'moment/locale/zh-cn';
  21. import locale from 'antd/es/date-picker/locale/zh_CN';
  22. import { addData, computeProfitReq, copyDataToSelectedType, delData, editData, getReportDataReq, getReportProjectSettingList, getResponsibleCenters, saveReportRelation } from './service';
  23. import './style.less';
  24. import TableTransfer from './transform';
  25. import React from 'react';
  26. import { cleanTree, getStringWidth } from '@/utils/tooljs';
  27. import { getDicDataBySysId } from '@/services/getDic';
  28. import { KCIMLeftList } from '@/components/KCIMLeftList';
  29. import { formatMoneyNumber } from '@/utils/format';
  30. import { useModel } from '@umijs/max';
  31. const IconFont = createFromIconfontCN({
  32. scriptUrl: '',
  33. });
  34. let currentRow: any = undefined;
  35. function findAllParents(tree: any[]) {
  36. let parents: any[] = [];
  37. // 递归函数来遍历树并找到所有父节点
  38. function traverse(nodes: any[]) {
  39. for (const node of nodes) {
  40. // 检查节点是否有子节点
  41. if (node.children && node.children.length > 0) {
  42. parents.push(node); // 添加到父节点列表
  43. traverse(node.children); // 递归遍历子节点
  44. }
  45. }
  46. }
  47. traverse(tree); // 开始遍历树
  48. return parents; // 返回所有父节点的数组
  49. }
  50. function countLeafNodes(trees:any[]) {
  51. let leafCount = 0;
  52. // 遍历集合中的每棵树
  53. for (let i = 0; i < trees.length; i++) {
  54. leafCount += countLeafNodesRecursive(trees[i]);
  55. }
  56. return leafCount;
  57. }
  58. function countLeafNodesRecursive(node:any) {
  59. // 如果当前节点没有子节点,说明它是一个叶子节点
  60. if (!node.children || node.children.length === 0) {
  61. return 1;
  62. }
  63. let leafCount = 0;
  64. // 递归计算每个子节点的叶子节点数
  65. for (let i = 0; i < node.children.length; i++) {
  66. leafCount += countLeafNodesRecursive(node.children[i]);
  67. }
  68. return leafCount;
  69. }
  70. function searchTree(tree: any[], searchTerm: string) {
  71. // 定义结果数组
  72. let results = [];
  73. // 定义递归函数来搜索匹配的节点
  74. function searchNode(node: any) {
  75. // 创建一个变量来标记当前节点或其子节点是否匹配
  76. let isMatch = false;
  77. // 检查当前节点的 name 或 code 是否包含搜索词
  78. if (node.reportName.includes(searchTerm)) {
  79. isMatch = true;
  80. }
  81. // 复制当前节点,避免修改原始数据
  82. let newNode = { ...node, children: [] };
  83. // 如果有子节点,递归搜索每个子节点
  84. if (node.children) {
  85. for (let child of node.children) {
  86. let childMatch = searchNode(child);
  87. // 如果子节点或其子树匹配,添加到新节点的子节点数组中
  88. if (childMatch) {
  89. newNode.children.push(childMatch);
  90. isMatch = true;
  91. }
  92. }
  93. }
  94. // 如果当前节点或其任何子节点匹配,返回新节点
  95. // 如果children为空,则不包含children属性
  96. if (isMatch) {
  97. if (newNode.children.length === 0) {
  98. delete newNode.children;
  99. }
  100. return newNode;
  101. } else {
  102. return null;
  103. }
  104. }
  105. // 遍历树的每个顶级节点
  106. for (let node of tree) {
  107. let result = searchNode(node);
  108. if (result) {
  109. results.push(result);
  110. }
  111. }
  112. return results;
  113. }
  114. function processTree(originalData: any[]) {
  115. return originalData.map(node => {
  116. // 深复制当前节点
  117. const newNode = JSON.parse(JSON.stringify(node));
  118. // 如果当前节点有profitList,处理它
  119. if (newNode.profitList && Array.isArray(newNode.profitList)) {
  120. newNode.profitList.forEach((profit: any) => {
  121. // 添加新的键值对到新节点
  122. newNode[`${profit.reportId}`] = formatMoneyNumber(profit.value);
  123. });
  124. // 如果不需要保留profitList,可以删除
  125. // delete newNode.profitList;
  126. }
  127. // 如果节点有子节点,递归处理子节点
  128. if (node.child && Array.isArray(node.child)) {
  129. newNode.children = processTree(node.child);
  130. }
  131. return newNode;
  132. });
  133. }
  134. // 递归函数,用于处理多层级标题
  135. function generateColumns(item: any, titleIndex = 0) {
  136. const column: any = {
  137. title: item.reportName,
  138. dataIndex: `${item.reportId}`,
  139. key: `${item.reportId}`,
  140. // align: 'center',
  141. };
  142. if (item.childTitle && Array.isArray(item.childTitle) && item.childTitle.length > 0) {
  143. column.children = item.childTitle.map((a: any, aindex: number) => generateColumns(a, titleIndex + 1));
  144. }
  145. return column;
  146. }
  147. // 主函数,生成表格列
  148. const generateTableColumns = (title: any[]) => {
  149. return title.map((item: any, titleIndex: number) => generateColumns(item, titleIndex));
  150. };
  151. export default function DepartmentCostCalc() {
  152. const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>({ reportType: 0 });
  153. const tableRef = useRef<ActionType>();
  154. const formRef = useRef<ProFormInstance>();
  155. const [tabs, set_tabs] = useState<any[]>([]);
  156. const { initialState,setInitialState } = useModel('@@initialState');
  157. const [computeDate, set_computeDate] = useState<string>(initialState?initialState.computeDate:'');
  158. const [responsibleCenters, set_responsibleCenters] = useState<any[]>([]);
  159. const [currentTabKey, set_currentTabKey] = useState<any | undefined>(undefined);
  160. const [currentTab, set_currentTab] = useState<any | undefined>(undefined);
  161. const [currentSelectedRespon, set_currentSelectedRespon] = useState<any | undefined>(undefined);
  162. const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  163. const [allParentsKeys, set_allParentsKeys] = useState<Key[]>([]);
  164. const [drawerTableVisible, set_drawerTableVisible] = useState(false);
  165. const [dataSource, set_dataSource] = useState<any[]>([]);
  166. const [tableColumns, set_tableColumns] = useState<any[]>([]);
  167. const columns: ProColumns[] = [
  168. {
  169. title: '报表项目名称',
  170. dataIndex: 'reportName',
  171. width: '50%',
  172. renderText(text, record, index, action) {
  173. const {description} = record;
  174. return description?<Popover content={description}><span style={{cursor:'pointer'}}>{text}</span><IconFont className="hover-icon" style={{fontSize:16,color:'#17181a',paddingLeft:4,position:'relative',top:1}} type={'iconshuoming'} /></Popover>:text
  175. },
  176. },
  177. {
  178. title: '金额(元)',
  179. align:'right',
  180. dataIndex: 'amount',
  181. renderText(num,record) {
  182. if (record.children) {
  183. return <React.Fragment></React.Fragment>
  184. }else{
  185. return formatMoneyNumber(num);
  186. }
  187. },
  188. },
  189. {
  190. title: '占比',
  191. align:'right',
  192. dataIndex: 'percent',
  193. renderText(num,record) {
  194. if (record.children) {
  195. return <React.Fragment></React.Fragment>
  196. }else{
  197. return `${((num * 100).toFixed(2))}%`
  198. }
  199. },
  200. },
  201. ]
  202. const getTableData = async (params: any) => {
  203. const { responsibilityCode, filter = undefined } = params;
  204. if (!responsibilityCode) return []
  205. const resp = await getReportProjectSettingList({ ...params });
  206. if (resp) {
  207. if (filter) {
  208. const filterData = searchTree(resp, filter);
  209. const allParents = findAllParents(filterData);
  210. set_allParentsKeys([...(allParents.map((a: any) => a.id))])
  211. return {
  212. data: filterData,
  213. success: true,
  214. }
  215. }
  216. const allParents = findAllParents(resp);
  217. set_allParentsKeys([...(allParents.map((a: any) => a.id))])
  218. return {
  219. data: resp,
  220. success: true,
  221. }
  222. }
  223. return []
  224. }
  225. const onTabChanged = (key: Key) => {
  226. set_currentTabKey(key);
  227. const needItem = tabs.filter((a) => a.key == key);
  228. if (needItem.length > 0) set_currentTab(needItem[0])
  229. }
  230. const getTabs = async () => {
  231. const { systemId } = JSON.parse((localStorage.getItem('currentSelectedTab')) as string)
  232. const resp = await getDicDataBySysId(systemId, 'PROFIT_REPORT_TYPE');
  233. if (resp) {
  234. const { dataVoList } = resp;
  235. const tempArr = dataVoList.map((a: any) => ({ label: a.name, key: Number(a.code), value: a.value }));
  236. const arr = (tempArr.filter((a: any) => a.value != '2'));
  237. set_tabs([...arr]);
  238. set_currentTabKey(arr[0].key);
  239. set_currentTab(arr[0]);
  240. }
  241. }
  242. const getResponsibleCenterList = async (reportType: string) => {
  243. const resp = await getResponsibleCenters(reportType);
  244. if (resp) {
  245. set_responsibleCenters(resp);
  246. }
  247. }
  248. const onLeftChange = (currentSelected: any) => {
  249. set_currentSelectedRespon(currentSelected);
  250. }
  251. const tableDataSearchHandle = (paramName: string) => {
  252. set_tableDataFilterParams({
  253. ...tableDataFilterParams,
  254. [`${paramName}`]: tableDataSearchKeywords
  255. })
  256. }
  257. const computeProfitHandle = async () => {
  258. Modal.confirm({
  259. title: '注意',
  260. content: '计算操作会覆盖当月已计算的数据,是否继续操作?',
  261. okText: '确定',
  262. cancelText: '取消',
  263. onOk: async (...args) => {
  264. const resp = await computeProfitReq(computeDate, currentTabKey);
  265. if (resp) {
  266. message.success('操作成功!');
  267. tableRef.current?.reload();
  268. }
  269. },
  270. })
  271. }
  272. const openTableDataDrawer = async () => {
  273. set_drawerTableVisible(true);
  274. const resp = await getReportDataReq(currentTabKey, computeDate);
  275. if (resp) {
  276. const { title = [], data = [] } = resp;
  277. const defaultColumns = [{
  278. title: '科室名称',
  279. dataIndex: 'responsibilityName',
  280. key: 'responsibilityName',
  281. width: 220,
  282. fixed: 'left'
  283. }];
  284. const tableColumns = generateTableColumns(title);
  285. const dataSource = processTree(data);
  286. set_tableColumns([...defaultColumns, ...tableColumns]);
  287. set_dataSource(dataSource);
  288. // console.log({ columns: [...defaultColumns, ...tableColumns], dataSource })
  289. }
  290. }
  291. const getHeaderRows = (columns: any[], level = 0, headerRows:any[] = [], maxLevel = 0) => {
  292. headerRows[level] = headerRows[level] || [];
  293. columns.forEach((col: { title: any; children: any; }) => {
  294. const colSpan = getColSpan(col);
  295. headerRows[level].push({ title: col.title, colSpan, rowSpan: col.children ? 1 : maxLevel - level });
  296. if (col.children) {
  297. getHeaderRows(col.children, level + 1, headerRows, maxLevel);
  298. } else {
  299. // 填充空白单元格
  300. for (let i = level + 1; i < maxLevel; i++) {
  301. headerRows[i] = headerRows[i] || [];
  302. headerRows[i].push({ title: '', colSpan: 1, rowSpan: 1 });
  303. }
  304. }
  305. });
  306. return headerRows;
  307. };
  308. const getColSpan:any = (col: { children: any[]; }) => {
  309. if (!col.children) return 1;
  310. return col.children.reduce((sum, child) => sum + getColSpan(child), 0);
  311. };
  312. const getMaxLevel = (col: any) => {
  313. if (!col.children) return 1;
  314. return 1 + Math.max(...col.children.map(getMaxLevel));
  315. };
  316. const extractLeafColumns = (columns: any[]) => {
  317. let leafColumns: any[] = [];
  318. columns.forEach(col => {
  319. if (col.children) {
  320. leafColumns = leafColumns.concat(extractLeafColumns(col.children));
  321. } else {
  322. leafColumns.push(col);
  323. }
  324. });
  325. return leafColumns;
  326. };
  327. const addRowWithIndentation = (record: any, level: number, leafColumns: any[], worksheetData: any[]) => {
  328. const row = leafColumns.map(col => record[col.dataIndex] ?? '');
  329. row[0] = ' '.repeat(level * 4) + row[0]; // 在第一列前添加缩进空格以表示层级
  330. worksheetData.push(row);
  331. if (record.children) {
  332. record.children.forEach((child: any) => addRowWithIndentation(child, level + 1, leafColumns, worksheetData));
  333. }
  334. };
  335. const handleExport = () => {
  336. try {
  337. const workbook = XLSX.utils.book_new();
  338. const worksheetData: any[] = [];
  339. // 获取最大层级
  340. const maxLevel = tableColumns.reduce((max, col) => Math.max(max, getMaxLevel(col)), 0);
  341. // 生成多层级表头
  342. const headerRows = getHeaderRows(tableColumns, 0, [], maxLevel);
  343. // 构建表头行
  344. headerRows.forEach((row: any, rowIndex) => {
  345. const rowData: string[] = [];
  346. row.forEach((cell: { title: any; colSpan: number; rowSpan: number; }) => {
  347. rowData.push(cell.title);
  348. for (let i = 1; i < cell.colSpan; i++) {
  349. rowData.push('');
  350. }
  351. });
  352. worksheetData.push(rowData);
  353. });
  354. // 填充单层表头的空白行
  355. if (maxLevel > 1) {
  356. const numColumns = headerRows[0].reduce((sum: any, cell: { colSpan: any; }) => sum + cell.colSpan, 0);
  357. for (let i = 1; i < maxLevel; i++) {
  358. while (worksheetData[i].length < numColumns) {
  359. worksheetData[i].push('');
  360. }
  361. }
  362. }
  363. // 提取最内层表头列
  364. const leafColumns = extractLeafColumns(tableColumns);
  365. // 添加数据并处理树结构
  366. dataSource.forEach(record => addRowWithIndentation(record, 0, leafColumns, worksheetData));
  367. const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
  368. // 初始化合并单元格数组
  369. worksheet['!merges'] = worksheet['!merges'] || [];
  370. // 合并单元格
  371. headerRows.forEach((row: any, rowIndex) => {
  372. let colIndex = 0;
  373. row.forEach((cell: { colSpan: number; rowSpan: number; }) => {
  374. if (cell.colSpan > 1 || cell.rowSpan > 1) {
  375. worksheet['!merges'].push({
  376. s: { r: rowIndex, c: colIndex },
  377. e: { r: rowIndex + cell.rowSpan - 1, c: colIndex + cell.colSpan - 1 }
  378. });
  379. }
  380. colIndex += cell.colSpan;
  381. });
  382. });
  383. // 设置单元格对齐方式
  384. Object.keys(worksheet).forEach(cell => {
  385. if (cell[0] !== '!') {
  386. worksheet[cell].s = {
  387. alignment: { vertical: 'center', horizontal: 'center' }
  388. };
  389. }
  390. });
  391. XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  392. const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
  393. const s2ab = (s: string) => {
  394. const buf = new ArrayBuffer(s.length);
  395. const view = new Uint8Array(buf);
  396. for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
  397. return buf;
  398. };
  399. saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), currentTab ? `${currentTab.label}.xlsx` : 'table_data.xlsx');
  400. } catch (error) {
  401. console.error('Export failed:', error);
  402. }
  403. };
  404. useEffect(() => {
  405. if (computeDate && currentTabKey != undefined) {
  406. getResponsibleCenterList(currentTabKey);
  407. }
  408. }, [computeDate, currentTabKey]);
  409. useEffect(() => {
  410. if (currentSelectedRespon) {
  411. set_tableDataFilterParams({
  412. ...tableDataFilterParams,
  413. responsibilityCode: currentSelectedRespon.responsibilityCode,
  414. reportType: currentTabKey,
  415. computeDate: computeDate
  416. })
  417. }
  418. }, [currentSelectedRespon])
  419. useEffect(() => {
  420. getTabs();
  421. }, [])
  422. return (
  423. <KCIMPagecontainer className='DepartmentCostCalc' title={false}>
  424. <Drawer className='drawerTable' contentWrapperStyle={{}} bodyStyle={{ padding: 16 }} title={false} open={drawerTableVisible} width={1000} headerStyle={{ display: 'none' }}>
  425. <div className='header'>
  426. <div className='title'>{currentTab ? currentTab.label : ''}(单位:元)</div>
  427. <div className='btns'>
  428. <span onClick={() => set_drawerTableVisible(false)}>关闭</span>
  429. <span className='close' onClick={() => handleExport()}>导出</span>
  430. </div>
  431. </div>
  432. <KCIMTable loading={dataSource.length == 0} expandable={{ defaultExpandAllRows: true }} className='departmentCostCalcReportTable' dataSource={dataSource} bordered pagination={false} scroll={{ x:countLeafNodes(tableColumns) * 120, y:`calc(100vh - 198px)` }} columns={tableColumns as ProColumns[]} rowKey='responsibilityCode' />
  433. </Drawer>
  434. <div className='header'>
  435. <div className="search">
  436. <span>核算年月:</span>
  437. <DatePicker
  438. onChange={(data, dateString) => {
  439. set_computeDate(dateString);
  440. setInitialState((s:any)=>({...s,computeDate: dateString,}))
  441. set_tableDataFilterParams({
  442. ...tableDataFilterParams,
  443. computeDate: dateString,
  444. });
  445. }}
  446. picker="month"
  447. locale={locale}
  448. defaultValue={moment(computeDate, 'YYYY-MM')}
  449. format="YYYY-MM"
  450. placeholder="选择年月"
  451. />
  452. </div>
  453. </div>
  454. <div className='content'>
  455. <Tabs
  456. defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
  457. items={tabs}
  458. key={'key'}
  459. onChange={(key) => onTabChanged(key)}
  460. />
  461. <div className='inner'>
  462. <div className='left'>
  463. <KCIMLeftList
  464. fieldNames={{ title: 'responsibilityName', key: 'responsibilityCode', children: 'children' }}
  465. rowKey={'responsibilityCode'}
  466. dataSource={responsibleCenters} searchKey={'responsibilityName'}
  467. onChange={onLeftChange}
  468. contentH={`100%`}
  469. // placeholder={leftListSearchPlaceHolder}
  470. listType={'tree'}
  471. />
  472. </div>
  473. <div className='right'>
  474. <div className='toolBar'>
  475. <div className='filterItem' style={{ width: 228 }}>
  476. <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索:</span>
  477. <Input placeholder={'报表项目代码/名称'} allowClear
  478. suffix={
  479. <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('filter')} />
  480. }
  481. onChange={(e) => {
  482. set_tableDataSearchKeywords(e.target.value);
  483. if (e.target.value.length == 0) {
  484. set_tableDataFilterParams({
  485. ...tableDataFilterParams,
  486. filter: ''
  487. });
  488. }
  489. }}
  490. onPressEnter={(e) => {
  491. set_tableDataFilterParams({
  492. ...tableDataFilterParams,
  493. filter: ((e.target) as HTMLInputElement).value
  494. });
  495. }}
  496. />
  497. </div>
  498. <div className='btnGroup'>
  499. <span className='btn' onClick={() => openTableDataDrawer()}>报表数据</span>
  500. <span className='calc' onClick={() => computeProfitHandle()}>计算</span>
  501. </div>
  502. </div>
  503. <KCIMTable pagination={false}
  504. rowClassName={(record) => (record.children ? 'has-children hover-row' : 'hover-row')}
  505. expandable={{
  506. defaultExpandAllRows: true, expandedRowKeys: allParentsKeys,
  507. onExpand(expanded, record) {
  508. const { id } = record;
  509. if (!expanded) {
  510. const expandedKeys = allParentsKeys.filter(a => a != id);
  511. set_allParentsKeys([...expandedKeys]);
  512. } else {
  513. set_allParentsKeys([...allParentsKeys, id]);
  514. }
  515. },
  516. }} columns={columns as ProColumns[]} scroll={{ y: `calc(100vh - 302px)` }} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
  517. </div>
  518. </div>
  519. </div>
  520. </KCIMPagecontainer>
  521. )
  522. }