import {otherIn, otherInGetStockInfo} from '@apis'; import {yupResolver} from '@hookform/resolvers/yup'; import {GetOtherInGetStockInfoParams, OtherStockInParams} from '@models'; import {userStore} from '@stores'; import {useMutation} from '@tanstack/react-query'; import {message} from 'antd'; import {FormEvent} from 'react'; import {useForm} from 'react-hook-form'; import {number, object, string} from 'yup'; type FormState = { /** 物料编号 */ materialCode: string; /** 所属公司 */ accountSleeve: string; /** wbs */ wbs: string; /** 数量 */ num: number; /** 库位信息 */ storageLocationCode: string; /** 仓库信息 */ warehouse: string; }; async function submitQuery(params: GetOtherInGetStockInfoParams & {amount: string}) { const data = await otherInGetStockInfo(params); if (data.msg === '200') { /** * 获取库存信息 * 如果有库存使用第一个库存入库 * 如果没有库存传入库位信息进行新增入库 */ const {department} = userStore.getState(); const inParams: OtherStockInParams = { ...params, departmentId: department, id: data.list.length > 0 ? data.list[0].id : null, producDate: '', }; const result = await otherIn(inParams); return result; } return data; } const validate = object({ materialCode: string().required('请输入物料编号'), accountSleeve: string().required('请选择公司'), wbs: string().required('请输入WBS编号'), num: number().typeError('请输入数字').required('请输入数量').min(1, '数量不能小于1个'), storageLocationCode: string().required('请选择入库库位'), warehouse: string().required('请选择入库仓库'), }); export function useFormState() { const {control, clearErrors, reset, handleSubmit, watch} = useForm({ resolver: yupResolver(validate), defaultValues: { materialCode: '', accountSleeve: '', wbs: '', num: 1, storageLocationCode: '', warehouse: '', }, }); const {isLoading, mutate} = useMutation({ mutationFn: submitQuery, onSuccess({msg}) { if (msg === '200') { message.success('入库成功'); clearErrors(); reset(); } }, }); const onSubmit = handleSubmit(function ({ wbs, storageLocationCode, materialCode, accountSleeve, num, }) { mutate({ wllbCode: materialCode, accountSleeve, wbs, storageLocationCode, amount: String(num), }); }); function onReset(e: FormEvent) { e.preventDefault(); reset(); } return [ {control, isLoading}, {onSubmit, watch, onReset}, ] as const; }