/** * useForecastOrderForm — 预测单表单 Composition Hook * T028: 提取表单校验逻辑 * * 封装表单提交、草稿保存、客户/产品选择回填等逻辑, * 统一管理 errors 和 submitting 状态。 */ import { ref } from 'vue' import { useI18n } from 'vue-i18n' import { ElMessage, ElMessageBox } from 'element-plus' import { useForecastOrderFormStore } from '@/store/modules/forecast-order/forecastOrderFormStore' export function useForecastOrderForm() { const { t } = useI18n() const store = useForecastOrderFormStore() const errors = ref>({}) const submitting = ref(false) /** * 完整校验(必填 + 提前期) * @returns 是否通过校验 */ function validateSubmit(): boolean { // 同步 store 中的 errors const valid = store.validateSubmit() errors.value = { ...store.errors } return valid } /** * 保存草稿(不校验必填) */ async function handleSaveDraft(): Promise { if (submitting.value) return false submitting.value = true try { const result = await store.saveDraftAction() return !!result } catch { return false } finally { submitting.value = false } } /** * 提交(校验 + MOQ 确认) */ async function handleSubmit(): Promise { if (submitting.value) return false submitting.value = true try { // 1. 校验 if (!validateSubmit()) { const errorKeys = Object.keys(errors.value) if (errorKeys.length > 0) { ElMessage.warning(errors.value[errorKeys[0]]) } return false } // 2. MOQ 二次确认 const moqCheck = store.checkMoq() if (!moqCheck.valid) { try { await ElMessageBox.confirm(moqCheck.message, t('forecast-order.confirm.tip'), { confirmButtonText: t('forecast-order.common.confirm'), cancelButtonText: t('forecast-order.common.cancel'), type: 'warning', }) } catch { return false } } // 3. 提交 const result = store.hasForecastOrderNo ? await store.updateDraftAction() : await store.submitAction() return !!result } catch { return false } finally { submitting.value = false } } /** * 回填客户信息 */ function handleCustSelect(customer: { customerCode: string customerName: string groupCustomerCode?: string groupCustomerName?: string tradeType?: string }) { store.onCustomerSelected(customer) // 清除相关错误 if (errors.value.customerCode) { delete errors.value.customerCode } } /** * 回填产品信息 */ function handleProdSelect(product: { productCode: string productName: string productCategory: string materialLevel?: string standardization?: string minOrderQty?: number }) { store.onProductSelected(product) // 清除相关错误 if (errors.value.productCode) { delete errors.value.productCode } } return { // 状态 errors, submitting, // 方法 validateSubmit, handleSaveDraft, handleSubmit, handleCustSelect, handleProdSelect, // Store 引用(供组件直接使用) store, } }