2026-08-10 f9e6eb6fc2c2e0c2a2b17238b817fcbfcb6bab56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<script lang="ts" setup>
import type { FormType } from '../data';
 
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import type { ErpSaleReturnApi } from '#/api/erp/sale/return';
 
import { computed, ref } from 'vue';
 
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
 
import { message } from 'ant-design-vue';
 
import { useVbenForm } from '#/adapter/form';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getSaleOrderItemListByOrderId, getSaleOrderPage } from '#/api/erp/sale/order';
import {
  createSaleReturn,
  getSaleReturn,
  updateSaleReturn,
} from '#/api/erp/sale/return';
 
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
import SaleOrderSelect from './sale-order-select.vue';
 
const emit = defineEmits(['success']);
const formData = ref<
  ErpSaleReturnApi.SaleReturn & {
    accountId?: number;
    customerId?: number;
    discountPercent?: number;
    order?: ErpSaleOrderApi.SaleOrder;
    orderId?: number;
    orderNo?: string;
  }
>({
  id: undefined,
  no: undefined,
  accountId: undefined,
  returnTime: undefined,
  remark: undefined,
  discountPercent: 0,
  customerId: undefined,
  discountPrice: 0,
  totalPrice: 0,
  otherPrice: 0,
  items: [],
});
const formType = ref<FormType>('create'); // 表单类型:'create' | 'edit' | 'detail'
const itemFormRef = ref<InstanceType<typeof ItemForm>>();
const orderItems = ref<ErpSaleOrderApi.SaleOrderItem[]>([]);
 
const getTitle = computed(() => {
  if (formType.value === 'create') {
    return $t('ui.actionTitle.create', ['销售退货']);
  } else if (formType.value === 'edit') {
    return $t('ui.actionTitle.edit', ['销售退货']);
  } else {
    return '销售退货详情';
  }
});
 
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 120,
  },
  wrapperClass: 'grid-cols-3',
  layout: 'vertical',
  schema: useFormSchema(formType.value),
  showDefaultActions: false,
  handleValuesChange: (values, changedFields) => {
    // 目的:同步到 item-form 组件,触发整体的价格计算
    if (formData.value) {
      if (changedFields.includes('otherPrice')) {
        formData.value.otherPrice = values.otherPrice;
      }
      if (changedFields.includes('discountPercent')) {
        formData.value.discountPercent = values.discountPercent;
      }
    }
  },
});
 
/** 更新销售退货项 */
function handleUpdateItems(items: ErpSaleReturnApi.SaleReturnItem[]) {
  formData.value.items = items;
  formApi.setValues({
    items,
  });
}
 
/** 更新其他费用 */
function handleUpdateOtherPrice(otherPrice: number) {
  formApi.setValues({
    otherPrice,
  });
}
 
/** 更新优惠金额 */
function handleUpdateDiscountPrice(discountPrice: number) {
  formApi.setValues({
    discountPrice,
  });
}
 
/** 更新总金额 */
function handleUpdateTotalPrice(totalPrice: number) {
  formApi.setValues({
    totalPrice,
  });
}
 
/** 选择销售订单 */
async function handleUpdateOrder(order: ErpSaleOrderApi.SaleOrder) {
  formData.value = {
    ...formData.value,
    orderId: order.id,
    orderNo: order.no!,
    customerId: order.customerId!,
    accountId: order.accountId!,
    remark: order.remark!,
    discountPercent: order.discountPercent!,
  };
  // 加载关联销售订单的物料列表
  const items = await getSaleOrderItemListByOrderId(order.id!);
  orderItems.value = items;
  // 将订单项转换为退货单项(仅保留可退货数量 > 0 的项)
  const returnItems: ErpSaleReturnApi.SaleReturnItem[] = [];
  for (const item of items) {
    const returnCount = (item as { returnCount?: number }).returnCount ?? 0;
    const remainingCount = (item.count ?? 0) - returnCount;
    if (remainingCount <= 0) continue;
 
    returnItems.push({
      orderItemId: item.id,
      productId: item.productId,
      productName: item.productName || '',
      productPrice: item.productPrice || 0,
      productUnitId: item.productUnitId,
      productUnitName: item.productUnitName,
      productBarCode: item.productBarCode,
      totalCount: item.count,
      count: remainingCount,
      taxPercent: item.taxPercent || 0,
      remark: item.remark || '',
      totalProductPrice: 0,
      taxPrice: 0,
      totalPrice: 0,
    });
  }
  formData.value.items = returnItems;
  formApi.setValues(formData.value, false);
}
 
/** 创建或更新销售退货 */
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const itemFormInstance = Array.isArray(itemFormRef.value)
      ? itemFormRef.value[0]
      : itemFormRef.value;
    try {
      itemFormInstance.validate();
    } catch (error: any) {
      message.error(error.message || '子表单验证失败');
      return;
    }
 
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as ErpSaleReturnApi.SaleReturn;
    try {
      await (formType.value === 'create'
        ? createSaleReturn(data)
        : updateSaleReturn(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = {} as ErpSaleReturnApi.SaleReturn;
      orderItems.value = [];
      return;
    }
    const modalData = modalApi.getData<{ formType: FormType; id?: number }>();
    formType.value = modalData.formType;
 
    // 编辑/详情模式:先加载数据,再更新 schema,确保渲染时 orderNo 已就绪
    if (modalData?.id) {
      modalApi.lock();
      try {
        const apiData = await getSaleReturn(modalData.id);
        const raw = apiData as Record<string, unknown>;
 
        // 提取订单号(尝试多种可能的字段名 / 嵌套结构)
        const getOrderNo = (): string => {
          if (raw.orderNo) return raw.orderNo as string;
          if (raw.salesOrderCode) return raw.salesOrderCode as string;
          if (raw.salesOrderNo) return raw.salesOrderNo as string;
          const so = raw.salesOrder as Record<string, unknown> | undefined;
          if (so?.no) return so.no as string;
          const o = raw.order as Record<string, unknown> | undefined;
          if (o?.no) return o.no as string;
          return '';
        };
 
        // 提取订单ID(尝试多种可能的字段名 / 嵌套结构)
        const getOrderId = (): number | undefined => {
          if (raw.orderId) return raw.orderId as number;
          if (raw.salesOrderId) return raw.salesOrderId as number;
          const so = raw.salesOrder as Record<string, unknown> | undefined;
          if (so?.id) return so.id as number;
          const o = raw.order as Record<string, unknown> | undefined;
          if (o?.id) return o.id as number;
          return undefined;
        };
 
        let orderNo = getOrderNo();
        let orderId = getOrderId();
 
        // 如果有订单号但没有订单ID,通过订单号反查订单ID
        if (orderNo && !orderId) {
          const orderPage = await getSaleOrderPage({
            pageNo: 1,
            pageSize: 1,
            no: orderNo,
          } as Record<string, unknown> as never);
          const list = (orderPage as Record<string, unknown>)?.list as Array<Record<string, unknown>> | undefined;
          if (list?.length) {
            orderId = list[0].id as number;
          }
        }
 
        formData.value = { ...apiData, orderNo, orderId };
        if (orderId) {
          orderItems.value = await getSaleOrderItemListByOrderId(orderId);
        }
      } finally {
        modalApi.unlock();
      }
    }
 
    // 数据就绪后再更新 schema 和设置表单值
    formApi.setDisabled(formType.value === 'detail');
    formApi.updateSchema(useFormSchema(formType.value));
 
    if (!modalData?.id) {
      // 新增时,默认选中账户
      const accountList = await getAccountSimpleList();
      const defaultAccount = accountList.find((item) => item.defaultStatus);
      if (defaultAccount) {
        await formApi.setValues({ accountId: defaultAccount.id });
      }
      return;
    }
 
    await formApi.setValues(formData.value, false);
    if (formData.value?.attachmentList?.length) {
      const blobIds = formData.value.attachmentList.map((item) => ({
        uid: String(item.id),
        name: item.name || '',
        url: item.url || '',
        status: 'done',
        id: item.id,
      }));
      await formApi.setFieldValue('blobIds', blobIds);
    }
  },
});
</script>
 
<template>
  <Modal
    :title="getTitle"
    class="w-3/4"
    :close-on-click-modal="false"
    :show-confirm-button="formType !== 'detail'"
  >
    <Form class="mx-3">
      <template #items>
        <ItemForm
          ref="itemFormRef"
          :items="formData?.items ?? []"
          :disabled="formType === 'detail'"
          :discount-percent="formData?.discountPercent ?? 0"
          :other-price="formData?.otherPrice ?? 0"
          :order-items="orderItems"
          @update:items="handleUpdateItems"
          @update:discount-price="handleUpdateDiscountPrice"
          @update:other-price="handleUpdateOtherPrice"
          @update:total-price="handleUpdateTotalPrice"
        />
      </template>
      <template #orderNo>
        <SaleOrderSelect
          :key="formData?.orderNo ?? 'empty'"
          :order-no="formData?.orderNo"
          @update:order="handleUpdateOrder"
        />
      </template>
    </Form>
  </Modal>
</template>