hooks.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {otherOut} from '@apis';
  2. import {yupResolver} from '@hookform/resolvers/yup';
  3. import {userStore} from '@stores';
  4. import {useMutation} from '@tanstack/react-query';
  5. import {message} from 'antd';
  6. import {FormEvent} from 'react';
  7. import {useForm} from 'react-hook-form';
  8. import {number, object, string} from 'yup';
  9. import {useStore} from 'zustand';
  10. type FormState = {
  11. wllbCode: string;
  12. storageLocationCode: string;
  13. num: number;
  14. wbs: string;
  15. accountSleeve: string;
  16. warehouse: string;
  17. };
  18. const validate = object({
  19. wllbCode: string().required('请输入物料编号'),
  20. warehouse: string().required('请选择出库仓库'),
  21. storageLocationCode: string().required('请选择出库库位'),
  22. wbs: string().required('请输入wbs编号'),
  23. accountSleeve: string().required('请选择所属公司'),
  24. num: number().typeError('请输入出库数量').min(1, '出库数量不能小于1个'),
  25. });
  26. export function useFormState() {
  27. const {control, reset, handleSubmit, clearErrors, watch} = useForm<FormState>({
  28. resolver: yupResolver(validate),
  29. defaultValues: {
  30. wllbCode: '',
  31. storageLocationCode: '',
  32. num: 1,
  33. warehouse: '',
  34. wbs: '',
  35. accountSleeve: '',
  36. },
  37. });
  38. function onReset(e: FormEvent) {
  39. e.preventDefault();
  40. reset();
  41. }
  42. const {mutate, isLoading} = useMutation({
  43. mutationFn: otherOut,
  44. onSuccess({msg}) {
  45. if (msg === '200') {
  46. reset();
  47. clearErrors();
  48. message.success('出库成功');
  49. }
  50. },
  51. });
  52. const {userId, department} = useStore(userStore, state => ({
  53. userId: String(state.id),
  54. department: state.department,
  55. }));
  56. const onSubmit = handleSubmit(function ({
  57. wllbCode,
  58. storageLocationCode,
  59. num,
  60. wbs,
  61. accountSleeve,
  62. }) {
  63. mutate({
  64. userId,
  65. department,
  66. wllbCode,
  67. storageLocationCode,
  68. num: String(num),
  69. wbs,
  70. accountSleeve,
  71. });
  72. });
  73. return [
  74. {isLoading, control},
  75. {onSubmit, onReset, watch},
  76. ] as const;
  77. }