5 天以前 91c82965b2d987452ca276e3a03b48c8dcda2ae9
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
<script lang="ts" setup>
import type { ErpFinancePaymentApi } from '#/api/erp/finance/payment';
 
import { computed, nextTick, ref, watch } from 'vue';
 
import { ErpBizType } from '@vben/constants';
import { erpPriceInputFormatter } from '@vben/utils';
 
import { Input, InputNumber } from 'ant-design-vue';
 
import { useVbenVxeGrid } from '#/adapter/vxe-table';
 
import { useFormItemColumns } from '../data';
 
interface InvoiceForItem {
  id?: number;
  no?: string;
  price?: number;
  remainingInvoicePrice?: number;
}
 
interface Props {
  items?: ErpFinancePaymentApi.FinancePaymentItem[];
  supplierId?: number;
  disabled?: boolean;
  discountPrice?: number;
  invoice?: InvoiceForItem;
}
 
const props = withDefaults(defineProps<Props>(), {
  items: () => [],
  supplierId: undefined,
  disabled: false,
  discountPrice: 0,
  invoice: undefined,
});
 
const emit = defineEmits([
  'update:items',
  'update:totalPrice',
  'update:paymentPrice',
]);
 
/** 输入时不补零,失焦后仍按金额格式保留两位小数 */
const paymentPriceFormatter = (
  value: number | string | undefined,
  info: { input: string; userTyping: boolean },
) => {
  return info.userTyping ? info.input : erpPriceInputFormatter(value);
};
 
const tableData = ref<ErpFinancePaymentApi.FinancePaymentItem[]>([]); // 表格数据
 
/** 已根据该来票生成的明细,避免重复生成 */
const generatedInvoiceId = ref<number | undefined>();
 
/** 获取表格合计数据 */
const summaries = computed(() => {
  return {
    totalPrice: tableData.value.reduce(
      (sum, item) => sum + (item.totalPrice || 0),
      0,
    ),
    paidPrice: tableData.value.reduce(
      (sum, item) => sum + (item.paidPrice || 0),
      0,
    ),
    paymentPrice: tableData.value.reduce(
      (sum, item) => sum + (item.paymentPrice || 0),
      0,
    ),
  };
});
 
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useFormItemColumns(),
    data: tableData.value,
    minHeight: 250,
    autoResize: true,
    border: true,
    rowConfig: {
      keyField: 'seq',
      isHover: true,
    },
    pagerConfig: {
      enabled: false,
    },
    toolbarConfig: {
      enabled: false,
    },
  },
});
 
/** 监听外部传入的列数据 */
watch(
  () => props.items,
  async (items) => {
    if (!items) {
      return;
    }
    tableData.value = [...items];
    // 编辑回显时,标记已根据当前来票生成过,避免重复生成
    generatedInvoiceId.value = props.invoice?.id;
    await nextTick(); // 特殊:保证 gridApi 已经初始化
    await gridApi.grid.reloadData(tableData.value);
  },
  {
    immediate: true,
  },
);
 
/** 关联来票变化时,自动生成唯一的付款明细(付款基于来票) */
watch(
  () => props.invoice?.id,
  async (newId) => {
    if (!newId || !props.invoice) {
      return;
    }
    if (generatedInvoiceId.value === newId) {
      return;
    }
    generatedInvoiceId.value = newId;
    const invoice = props.invoice;
    const price = invoice.price ?? 0;
    const remaining = invoice.remainingInvoicePrice ?? price;
    tableData.value = [
      {
        bizId: invoice.id ?? 0,
        bizType: ErpBizType.PURCHASE_INVOICE,
        bizNo: invoice.no ?? '',
        totalPrice: price,
        paidPrice: price - remaining,
        paymentPrice: remaining,
        remark: '',
      },
    ];
    await nextTick();
    await gridApi.grid.reloadData(tableData.value);
    emit('update:items', [...tableData.value]);
  },
);
 
/** 计算 totalPrice、paymentPrice 价格 */
watch(
  () => [tableData.value, props.discountPrice],
  () => {
    if (!tableData.value || tableData.value.length === 0) {
      return;
    }
    const totalPrice = tableData.value.reduce(
      (prev, curr) => prev + (curr.totalPrice || 0),
      0,
    );
    const paymentPrice = tableData.value.reduce(
      (prev, curr) => prev + (curr.paymentPrice || 0),
      0,
    );
    const finalPaymentPrice = paymentPrice - (props.discountPrice || 0);
    // 通知父组件更新
    emit('update:totalPrice', totalPrice);
    emit('update:paymentPrice', finalPaymentPrice);
  },
  { deep: true },
);
 
/** 处理行数据变更 */
const handleRowChange = (row: any) => {
  const index = tableData.value.findIndex(
    (item) => item.bizId === row.bizId && item.bizType === row.bizType,
  );
  if (index === -1) {
    tableData.value.push(row);
  } else {
    tableData.value[index] = row;
  }
  emit('update:items', [...tableData.value]);
};
 
/** 表单校验 */
const validate = () => {
  // 检查是否有明细
  if (tableData.value.length === 0) {
    throw new Error('请先选择关联来票');
  }
  // 检查每行的付款金额
  for (let i = 0; i < tableData.value.length; i++) {
    const item = tableData.value[i];
    if (!item?.paymentPrice || item.paymentPrice <= 0) {
      throw new Error(`第 ${i + 1} 行:本次付款必须大于0`);
    }
  }
};
 
defineExpose({ validate });
</script>
 
<template>
  <div>
    <Grid class="w-full">
      <template #paymentPrice="{ row }">
        <InputNumber
          v-model:value="row.paymentPrice"
          :precision="2"
          :disabled="disabled"
          :formatter="paymentPriceFormatter"
          placeholder="请输入本次付款"
          @change="handleRowChange(row)"
        />
      </template>
      <template #remark="{ row }">
        <Input
          v-model:value="row.remark"
          :disabled="disabled"
          placeholder="请输入备注"
          @change="handleRowChange(row)"
        />
      </template>
 
      <template #bottom>
        <div class="mt-2 rounded border border-border bg-muted p-2">
          <div class="flex justify-between text-sm text-muted-foreground">
            <span class="font-medium text-foreground">合计:</span>
            <div class="flex space-x-4">
              <span>
                应付金额:{{ erpPriceInputFormatter(summaries.totalPrice) }}
              </span>
              <span>
                已付金额:{{ erpPriceInputFormatter(summaries.paidPrice) }}
              </span>
              <span>
                本次付款:
                {{ erpPriceInputFormatter(summaries.paymentPrice) }}
              </span>
            </div>
          </div>
        </div>
        <div
          v-if="!invoice && !disabled"
          class="mt-2 flex justify-center text-sm text-muted-foreground"
        >
          请先在上方表单选择关联来票,系统将自动生成付款明细
        </div>
      </template>
    </Grid>
  </div>
</template>