useListPage.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 } = 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. // 导入 excel
  105. function onImportXls(file) {
  106. const { url, success } = options?.importConfig ?? {};
  107. //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  108. const realUrl = typeof url === 'function' ? url() : url;
  109. if (realUrl) {
  110. return handleImportXls(file, realUrl, success || reload);
  111. //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
  112. } else {
  113. $message.createMessage.warn('没有传递 importConfig.url 参数');
  114. return Promise.reject();
  115. }
  116. }
  117. /**
  118. * 通用请求处理方法,可自动刷新表格,自动清空选择
  119. * @param api 请求api
  120. * @param options 是否显示确认框
  121. */
  122. function doRequest(api: () => Promise<any>, options?: IDoRequestOptions) {
  123. return new Promise((resolve, reject) => {
  124. const execute = async () => {
  125. try {
  126. setLoading(true);
  127. const res = await api();
  128. if (options?.reload ?? true) {
  129. reload();
  130. }
  131. if (options?.clearSelection ?? true) {
  132. selectedRowKeys.value = [];
  133. }
  134. resolve(res);
  135. } catch (e) {
  136. reject(e);
  137. } finally {
  138. setLoading(false);
  139. }
  140. };
  141. if (options?.confirm ?? true) {
  142. $message.createConfirm({
  143. iconType: 'warning',
  144. title: '删除',
  145. content: '确定要删除吗?',
  146. onOk: () => execute(),
  147. onCancel: () => reject(),
  148. });
  149. } else {
  150. execute();
  151. }
  152. });
  153. }
  154. /** 执行单个删除操作 */
  155. function doDeleteRecord(api: () => Promise<any>) {
  156. return doRequest(api, { confirm: false, clearSelection: false });
  157. }
  158. return {
  159. ...$design,
  160. ...$message,
  161. onExportXls,
  162. onImportXls,
  163. doRequest,
  164. doDeleteRecord,
  165. tableContext,
  166. };
  167. }
  168. // 定义表格所需参数
  169. type TableProps = Partial<DynamicProps<BasicTableProps>>;
  170. type UseTableMethod = TableActionType & {
  171. getForm: () => FormActionType;
  172. };
  173. /**
  174. * useListTable 列表页面标准表格参数
  175. *
  176. * @param tableProps 表格参数
  177. */
  178. export function useListTable(tableProps: TableProps): [
  179. (instance: TableActionType, formInstance: UseTableMethod) => void,
  180. TableActionType & {
  181. getForm: () => FormActionType;
  182. },
  183. {
  184. rowSelection: any;
  185. selectedRows: Ref<Recordable[]>;
  186. selectedRowKeys: Ref<any[]>;
  187. }
  188. ] {
  189. // 自适应列配置
  190. const adaptiveColProps: Partial<ColEx> = {
  191. xs: 24, // <576px
  192. sm: 12, // ≥576px
  193. md: 12, // ≥768px
  194. lg: 8, // ≥992px
  195. xl: 8, // ≥1200px
  196. xxl: 6, // ≥1600px
  197. };
  198. const defaultTableProps: TableProps = {
  199. rowKey: 'id',
  200. // 使用查询条件区域
  201. useSearchForm: true,
  202. // 查询条件区域配置
  203. formConfig: {
  204. // 紧凑模式
  205. compact: true,
  206. // label默认宽度
  207. // labelWidth: 120,
  208. // 按下回车后自动提交
  209. autoSubmitOnEnter: true,
  210. // 默认 row 配置
  211. rowProps: { gutter: 8 },
  212. // 默认 col 配置
  213. baseColProps: {
  214. ...adaptiveColProps,
  215. },
  216. labelCol: {
  217. xs: 24,
  218. sm: 8,
  219. md: 6,
  220. lg: 8,
  221. xl: 6,
  222. xxl: 6,
  223. },
  224. wrapperCol: {},
  225. // 是否显示 展开/收起 按钮
  226. showAdvancedButton: true,
  227. // 超过指定列数默认折叠
  228. autoAdvancedCol: 3,
  229. // 操作按钮配置
  230. actionColOptions: {
  231. ...adaptiveColProps,
  232. style: { textAlign: 'left' },
  233. },
  234. },
  235. // 斑马纹
  236. striped: false,
  237. // 是否可以自适应高度
  238. canResize: true,
  239. // 表格最小高度
  240. minHeight: 500,
  241. // 点击行选中
  242. clickToRowSelect: false,
  243. // 是否显示边框
  244. bordered: true,
  245. // 是否显示序号列
  246. showIndexColumn: false,
  247. // 显示表格设置
  248. showTableSetting: true,
  249. // 表格全屏设置
  250. tableSetting: {
  251. fullScreen: false,
  252. },
  253. // 是否显示操作列
  254. showActionColumn: true,
  255. // 操作列
  256. actionColumn: {
  257. width: 120,
  258. title: '操作',
  259. //是否锁定操作列取值 right ,left,false
  260. fixed: false,
  261. dataIndex: 'action',
  262. slots: { customRender: 'action' },
  263. },
  264. };
  265. // 合并用户个性化配置
  266. if (tableProps) {
  267. // merge 方法可深度合并对象
  268. merge(defaultTableProps, tableProps);
  269. }
  270. // 发送请求之前调用的方法
  271. function beforeFetch(params) {
  272. // 默认以 createTime 降序排序
  273. return Object.assign({ column: 'createTime'}, params);
  274. }
  275. // 合并方法
  276. Object.assign(defaultTableProps, { beforeFetch });
  277. if (typeof tableProps.beforeFetch === 'function') {
  278. defaultTableProps.beforeFetch = function (params) {
  279. params = beforeFetch(params);
  280. // @ts-ignore
  281. tableProps.beforeFetch(params);
  282. return params;
  283. };
  284. }
  285. // 当前选择的行
  286. const selectedRowKeys = ref<any[]>([]);
  287. // 选择的行记录
  288. const selectedRows = ref<Recordable[]>([]);
  289. // 表格选择列配置
  290. const rowSelection: any = tableProps?.rowSelection ?? {};
  291. const defaultRowSelection = reactive({
  292. ...rowSelection,
  293. type: rowSelection.type ?? 'checkbox',
  294. // 选择列宽度,默认 50
  295. columnWidth: rowSelection.columnWidth ?? 50,
  296. selectedRows: selectedRows,
  297. selectedRowKeys: selectedRowKeys,
  298. onChange(...args) {
  299. selectedRowKeys.value = args[0];
  300. selectedRows.value = args[1];
  301. if (typeof rowSelection.onChange === 'function') {
  302. rowSelection.onChange(...args);
  303. }
  304. },
  305. });
  306. delete defaultTableProps.rowSelection;
  307. return [
  308. ...useTable(defaultTableProps),
  309. {
  310. selectedRows,
  311. selectedRowKeys,
  312. rowSelection: defaultRowSelection,
  313. },
  314. ];
  315. }