You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB

  1. import { atomWithMutation, atomWithQuery, queryClientAtom } from 'jotai-tanstack-query'
  2. import systemServ from '@/service/system.ts'
  3. import { IApiResult, IPage } from '@/types'
  4. import { IDepartment } from '@/types/department'
  5. import { atom, createStore } from 'jotai'
  6. import { t } from 'i18next'
  7. import { message } from 'antd'
  8. const store = createStore()
  9. const departPageAtom = atom<IPage>({})
  10. const defaultDepart = {
  11. id: 0,
  12. parent_id: 0,
  13. name: '',
  14. manager_user_id: 0,
  15. phone: '',
  16. sort: 0,
  17. } as IDepartment
  18. const batchIdsAtom = atom<number[]>([])
  19. const selectedDepartAtom = atom<IDepartment>({} as IDepartment)
  20. const departTreeAtom = atomWithQuery(() => {
  21. return {
  22. queryKey: [ 'departTree' ],
  23. queryFn: async () => {
  24. return await systemServ.dept.tree()
  25. },
  26. select: (res) => {
  27. return res.data.tree ?? []
  28. }
  29. }
  30. })
  31. const saveOrUpdateDepartAtom = atomWithMutation<IApiResult, IDepartment>((get) => {
  32. return {
  33. mutationKey: [ 'saveOrUpdateDepart', get(selectedDepartAtom) ],
  34. mutationFn: async (data: IDepartment) => {
  35. if (data.id) {
  36. return await systemServ.dept.update(data)
  37. }
  38. return await systemServ.dept.add(data)
  39. },
  40. onSuccess: (res) => {
  41. const isAdd = !!res.data?.id
  42. message.success(t(isAdd ? 'message.saveSuccess' : 'message.editSuccess', '保存成功'))
  43. store.set(selectedDepartAtom, prev => ({
  44. ...prev,
  45. ...(isAdd ? res.data : {})
  46. }))
  47. get(queryClientAtom).invalidateQueries({ queryKey: [ 'departTree', get(departPageAtom) ] }).then()
  48. }
  49. }
  50. })
  51. const deleteDepartAtom = atomWithMutation<IApiResult, number[]>((get) => {
  52. return {
  53. mutationKey: [ 'deleteDepart', get(batchIdsAtom) ],
  54. mutationFn: async (ids: number[]) => {
  55. return await systemServ.dept.batchDelete(ids)
  56. },
  57. onSuccess: () => {
  58. message.success(t('message.deleteSuccess', '删除成功'))
  59. store.set(batchIdsAtom, [])
  60. get(queryClientAtom).invalidateQueries({ queryKey: [ 'departTree', get(departPageAtom) ] }).then()
  61. }
  62. }
  63. })
  64. export const useDepartStore = () => ({
  65. defaultDepart,
  66. departPageAtom,
  67. selectedDepartAtom,
  68. departTreeAtom,
  69. deleteDepartAtom,
  70. batchIdsAtom,
  71. saveOrUpdateDepartAtom,
  72. })