useListPage.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { reactive, ref, Ref, unref } from 'vue';
  2. import { merge } from 'lodash-es';
  3. import { DynamicProps } from '/#/utils';
  4. import { BasicTableProps, TableActionType, useTable } from '/@/components/Table';
  5. import { ColEx } from '/@/components/Form/src/types';
  6. import { FormActionType } from '/@/components/Form';
  7. import { useMessage } from '/@/hooks/web/useMessage';
  8. import { useMethods } from '/@/hooks/system/useMethods';
  9. import { useDesign } from '/@/hooks/web/useDesign';
  10. import { filterObj } from '/@/utils/common/compUtils';
  11. const { handleExportXls, handleImportXls, handleExportXlsPost } = useMethods();
  12. // 定义 useListPage 方法所需参数
  13. interface ListPageOptions {
  14. // 样式作用域范围
  15. designScope?: string;
  16. // 【必填】表格参数配置
  17. tableProps: TableProps;
  18. // 分页
  19. pagination?: boolean;
  20. // 导出配置
  21. exportConfig?: {
  22. url: string | (() => string);
  23. // 导出文件名
  24. name?: string | (() => string);
  25. //导出参数
  26. params?: object;
  27. };
  28. // 导入配置
  29. importConfig?: {
  30. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  31. url: string | (() => string);
  32. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  33. // 导出成功后的回调
  34. success?: (fileInfo?: any) => void;
  35. };
  36. }
  37. interface IDoRequestOptions {
  38. // 是否显示确认对话框,默认 true
  39. confirm?: boolean;
  40. // 是否自动刷新表格,默认 true
  41. reload?: boolean;
  42. // 是否自动清空选择,默认 true
  43. clearSelection?: boolean;
  44. }
  45. /**
  46. * listPage页面公共方法
  47. *
  48. * @param options
  49. */
  50. export function useListPage(options: ListPageOptions) {
  51. const $message = useMessage();
  52. let $design = {} as ReturnType<typeof useDesign>;
  53. if (options.designScope) {
  54. $design = useDesign(options.designScope);
  55. }
  56. const tableContext = useListTable(options.tableProps);
  57. const [, { getForm, reload, setLoading }, { selectedRowKeys }] = tableContext;
  58. // 导出 excel
  59. async function onExportXls(selectForm?) {
  60. //update-begin---author:wangshuai ---date:20220411 for:导出新增自定义参数------------
  61. const { url, name, params } = options?.exportConfig ?? {};
  62. const realUrl = typeof url === 'function' ? url() : url;
  63. if (realUrl) {
  64. const title = typeof name === 'function' ? name() : name;
  65. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  66. let paramsForm: any = {};
  67. try {
  68. if (selectForm) {
  69. paramsForm = selectForm;
  70. } else {
  71. paramsForm = await getForm().validate();
  72. }
  73. } catch (e) {
  74. console.error(e);
  75. }
  76. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  77. //update-begin-author:liusq date:20230410 for:[/issues/409]导出功能没有按排序结果导出,设置导出默认排序,创建时间倒序
  78. if (!paramsForm?.column) {
  79. Object.assign(paramsForm, { column: 'createTime', order: 'desc' });
  80. }
  81. //update-begin-author:liusq date:20230410 for: [/issues/409]导出功能没有按排序结果导出,设置导出默认排序,创建时间倒序
  82. //如果参数不为空,则整合到一起
  83. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  84. if (params) {
  85. Object.keys(params).map((k) => {
  86. const temp = (params as object)[k];
  87. if (temp) {
  88. paramsForm[k] = unref(temp);
  89. }
  90. });
  91. }
  92. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  93. if (selectedRowKeys.value && selectedRowKeys.value.length > 0) {
  94. paramsForm['selections'] = selectedRowKeys.value.join(',');
  95. }
  96. console.log();
  97. return handleExportXls(title as string, realUrl, filterObj(paramsForm));
  98. //update-end---author:wangshuai ---date:20220411 for:导出新增自定义参数--------------
  99. } else {
  100. $message.createMessage.warn('没有传递 exportConfig.url 参数');
  101. return Promise.reject();
  102. }
  103. }
  104. async function onExportXlsPost(selectForm?) {
  105. //update-begin---author:wangshuai ---date:20220411 for:导出新增自定义参数------------
  106. const { url, name, params } = options?.exportConfig ?? {};
  107. const realUrl = typeof url === 'function' ? url() : url;
  108. if (realUrl) {
  109. const title = typeof name === 'function' ? name() : name;
  110. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  111. let paramsForm: any = {};
  112. try {
  113. if (selectForm) {
  114. paramsForm = selectForm;
  115. } else {
  116. paramsForm = await getForm().validate();
  117. }
  118. } catch (e) {
  119. console.error(e);
  120. }
  121. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出报错,原因未知-
  122. //update-begin-author:liusq date:20230410 for:[/issues/409]导出功能没有按排序结果导出,设置导出默认排序,创建时间倒序
  123. if (!paramsForm?.column) {
  124. Object.assign(paramsForm, { column: 'createTime', order: 'desc' });
  125. }
  126. //update-begin-author:liusq date:20230410 for: [/issues/409]导出功能没有按排序结果导出,设置导出默认排序,创建时间倒序
  127. //如果参数不为空,则整合到一起
  128. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  129. if (params) {
  130. Object.keys(params).map((k) => {
  131. const temp = (params as object)[k];
  132. if (temp) {
  133. paramsForm[k] = unref(temp);
  134. }
  135. });
  136. }
  137. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导出动态设置mainId
  138. if (selectedRowKeys.value && selectedRowKeys.value.length > 0) {
  139. paramsForm['selections'] = selectedRowKeys.value.join(',');
  140. }
  141. console.log();
  142. return handleExportXlsPost(title as string, realUrl, filterObj(paramsForm));
  143. //update-end---author:wangshuai ---date:20220411 for:导出新增自定义参数--------------
  144. } else {
  145. $message.createMessage.warn('没有传递 exportConfig.url 参数');
  146. return Promise.reject();
  147. }
  148. }
  149. // 导入 excel
  150. function onImportXls(file) {
  151. const { url, success } = options?.importConfig ?? {};
  152. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  153. const realUrl = typeof url === 'function' ? url() : url;
  154. if (realUrl) {
  155. return handleImportXls(file, realUrl, success || reload);
  156. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  157. } else {
  158. $message.createMessage.warn('没有传递 importConfig.url 参数');
  159. return Promise.reject();
  160. }
  161. }
  162. /**
  163. * 通用请求处理方法,可自动刷新表格,自动清空选择
  164. * @param api 请求api
  165. * @param options 是否显示确认框
  166. */
  167. function doRequest(api: () => Promise<any>, options?: IDoRequestOptions) {
  168. return new Promise((resolve, reject) => {
  169. const execute = async () => {
  170. try {
  171. setLoading(true);
  172. const res = await api();
  173. if (options?.reload ?? true) {
  174. reload();
  175. }
  176. if (options?.clearSelection ?? true) {
  177. selectedRowKeys.value = [];
  178. }
  179. resolve(res);
  180. } catch (e) {
  181. reject(e);
  182. } finally {
  183. setLoading(false);
  184. }
  185. };
  186. if (options?.confirm ?? true) {
  187. $message.createConfirm({
  188. iconType: 'warning',
  189. title: '删除',
  190. content: '确定要删除吗?',
  191. onOk: () => execute(),
  192. onCancel: () => reject(),
  193. });
  194. } else {
  195. execute();
  196. }
  197. });
  198. }
  199. /** 执行单个删除操作 */
  200. function doDeleteRecord(api: () => Promise<any>) {
  201. return doRequest(api, { confirm: false, clearSelection: false });
  202. }
  203. return {
  204. ...$design,
  205. ...$message,
  206. onExportXls,
  207. onExportXlsPost,
  208. onImportXls,
  209. doRequest,
  210. doDeleteRecord,
  211. tableContext,
  212. };
  213. }
  214. // 定义表格所需参数
  215. type TableProps = Partial<DynamicProps<BasicTableProps>>;
  216. type UseTableMethod = TableActionType & {
  217. getForm: () => FormActionType;
  218. };
  219. /**
  220. * useListTable 列表页面标准表格参数
  221. *
  222. * @param tableProps 表格参数
  223. */
  224. export function useListTable(tableProps: TableProps): [
  225. (instance: TableActionType, formInstance: UseTableMethod) => void,
  226. TableActionType & {
  227. getForm: () => FormActionType;
  228. },
  229. {
  230. rowSelection: any;
  231. selectedRows: Ref<Recordable[]>;
  232. selectedRowKeys: Ref<any[]>;
  233. },
  234. ] {
  235. // 自适应列配置
  236. const adaptiveColProps: Partial<ColEx> = {
  237. xs: 24, // <576px
  238. sm: 12, // ≥576px
  239. md: 12, // ≥768px
  240. lg: 8, // ≥992px
  241. xl: 8, // ≥1200px
  242. xxl: 6, // ≥1600px
  243. };
  244. const defaultTableProps: TableProps = {
  245. rowKey: 'id',
  246. // 使用查询条件区域
  247. useSearchForm: true,
  248. // 查询条件区域配置
  249. formConfig: {
  250. // 紧凑模式
  251. compact: true,
  252. // label默认宽度
  253. // labelWidth: 120,
  254. // 按下回车后自动提交
  255. autoSubmitOnEnter: true,
  256. // 默认 row 配置
  257. rowProps: { gutter: 8 },
  258. // 默认 col 配置
  259. baseColProps: {
  260. ...adaptiveColProps,
  261. },
  262. labelCol: {
  263. xs: 24,
  264. sm: 8,
  265. md: 6,
  266. lg: 8,
  267. xl: 6,
  268. xxl: 6,
  269. },
  270. wrapperCol: {},
  271. // 是否显示 展开/收起 按钮
  272. showAdvancedButton: true,
  273. // 超过指定列数默认折叠
  274. autoAdvancedCol: 3,
  275. // 操作按钮配置
  276. actionColOptions: {
  277. ...adaptiveColProps,
  278. style: { textAlign: 'left' },
  279. },
  280. },
  281. // 斑马纹
  282. striped: false,
  283. // 是否可以自适应高度
  284. canResize: true,
  285. // 表格最小高度
  286. minHeight: 500,
  287. // 点击行选中
  288. clickToRowSelect: false,
  289. // 是否显示边框
  290. bordered: true,
  291. // 是否显示序号列
  292. showIndexColumn: false,
  293. // 显示表格设置
  294. showTableSetting: true,
  295. // 表格全屏设置
  296. tableSetting: {
  297. fullScreen: false,
  298. },
  299. // 是否显示操作列
  300. showActionColumn: true,
  301. // 操作列
  302. actionColumn: {
  303. width: 120,
  304. title: '操作',
  305. //是否锁定操作列取值 right ,left,false
  306. fixed: false,
  307. dataIndex: 'action',
  308. slots: { customRender: 'action' },
  309. },
  310. };
  311. // 合并用户个性化配置
  312. if (tableProps) {
  313. // merge 方法可深度合并对象
  314. merge(defaultTableProps, tableProps);
  315. }
  316. // 发送请求之前调用的方法
  317. function beforeFetch(params) {
  318. // 默认以 createTime 降序排序
  319. return Object.assign({ column: 'createTime' }, params);
  320. }
  321. // 合并方法
  322. Object.assign(defaultTableProps, { beforeFetch });
  323. if (typeof tableProps.beforeFetch === 'function') {
  324. defaultTableProps.beforeFetch = function (params) {
  325. params = beforeFetch(params);
  326. // @ts-ignore
  327. tableProps.beforeFetch(params);
  328. return params;
  329. };
  330. }
  331. // 当前选择的行
  332. const selectedRowKeys = ref<any[]>([]);
  333. // 选择的行记录
  334. const selectedRows = ref<Recordable[]>([]);
  335. // 表格选择列配置
  336. const rowSelection: any = tableProps?.rowSelection ?? {};
  337. const defaultRowSelection = reactive({
  338. ...rowSelection,
  339. type: rowSelection.type ?? 'checkbox',
  340. // 选择列宽度,默认 50
  341. columnWidth: rowSelection.columnWidth ?? 50,
  342. selectedRows: selectedRows,
  343. selectedRowKeys: selectedRowKeys,
  344. onChange(...args) {
  345. selectedRowKeys.value = args[0];
  346. selectedRows.value = args[1];
  347. if (typeof rowSelection.onChange === 'function') {
  348. rowSelection.onChange(...args);
  349. }
  350. },
  351. });
  352. delete defaultTableProps.rowSelection;
  353. return [
  354. ...useTable(defaultTableProps),
  355. {
  356. selectedRows,
  357. selectedRowKeys,
  358. rowSelection: defaultRowSelection,
  359. },
  360. ];
  361. }