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
89 lines
2.4 KiB
import { atomWithMutation, atomWithQuery, queryClientAtom } from 'jotai-tanstack-query'
|
|
import systemServ from '@/service/system.ts'
|
|
import { IApiResult, IPage } from '@/types'
|
|
import { IDepartment } from '@/types/department'
|
|
import { atom, createStore } from 'jotai'
|
|
import { t } from 'i18next'
|
|
import { message } from 'antd'
|
|
|
|
|
|
const store = createStore()
|
|
|
|
const departPageAtom = atom<IPage>({})
|
|
|
|
const defaultDepart = {
|
|
id: 0,
|
|
parent_id: 0,
|
|
name: '',
|
|
manager_user_id: 0,
|
|
phone: '',
|
|
sort: 0,
|
|
} as IDepartment
|
|
|
|
const batchIdsAtom = atom<number[]>([])
|
|
|
|
const selectedDepartAtom = atom<IDepartment>({} as IDepartment)
|
|
|
|
const departTreeAtom = atomWithQuery(() => {
|
|
|
|
return {
|
|
queryKey: [ 'departTree' ],
|
|
queryFn: async () => {
|
|
return await systemServ.dept.tree()
|
|
},
|
|
select: (res) => {
|
|
return res.data.tree ?? []
|
|
}
|
|
}
|
|
})
|
|
|
|
const saveOrUpdateDepartAtom = atomWithMutation<IApiResult, IDepartment>((get) => {
|
|
|
|
return {
|
|
mutationKey: [ 'saveOrUpdateDepart', get(selectedDepartAtom) ],
|
|
mutationFn: async (data: IDepartment) => {
|
|
if (data.id) {
|
|
return await systemServ.dept.update(data)
|
|
}
|
|
return await systemServ.dept.add(data)
|
|
},
|
|
onSuccess: (res) => {
|
|
const isAdd = !!res.data?.id
|
|
message.success(t(isAdd ? 'message.saveSuccess' : 'message.editSuccess', '保存成功'))
|
|
store.set(selectedDepartAtom, prev => ({
|
|
...prev,
|
|
...(isAdd ? res.data : {})
|
|
}))
|
|
get(queryClientAtom).invalidateQueries({ queryKey: [ 'departTree', get(departPageAtom) ] }).then()
|
|
}
|
|
}
|
|
|
|
})
|
|
|
|
|
|
const deleteDepartAtom = atomWithMutation<IApiResult, number[]>((get) => {
|
|
|
|
return {
|
|
mutationKey: [ 'deleteDepart', get(batchIdsAtom) ],
|
|
mutationFn: async (ids: number[]) => {
|
|
return await systemServ.dept.batchDelete(ids)
|
|
},
|
|
onSuccess: () => {
|
|
message.success(t('message.deleteSuccess', '删除成功'))
|
|
store.set(batchIdsAtom, [])
|
|
get(queryClientAtom).invalidateQueries({ queryKey: [ 'departTree', get(departPageAtom) ] }).then()
|
|
|
|
}
|
|
}
|
|
|
|
})
|
|
|
|
export const useDepartStore = () => ({
|
|
defaultDepart,
|
|
departPageAtom,
|
|
selectedDepartAtom,
|
|
departTreeAtom,
|
|
deleteDepartAtom,
|
|
batchIdsAtom,
|
|
saveOrUpdateDepartAtom,
|
|
})
|