sen
2026-03-25 7b08397d1113044b626f5fba14383b2324a9ba5b
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
<template>
  <el-dialog v-model="visible" title="账单认领" width="1150px" destroy-on-close :close-on-click-modal="false">
    <div style="text-align: right;margin-bottom: 10px;">
      <el-button type="warning" v-if="isViewMode" plain icon="Download" @click="handleExport"
        v-hasPermi="['cwgl:fundFlowClaimDetail:export']">导出
      </el-button>
      <!-- <el-button type="primary" @click="handleFinalSubmit">确 定</el-button> -->
    </div>
    <div class="claim-wrapper">
      <!-- <div class="section-header">流水详细信息</div> -->
      <el-descriptions :column="3" border class="mb-20">
        <el-descriptions-item label="id">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="银行流水号">{{ detail.bankFlowNo }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detail.company }}</el-descriptions-item>
 
        <el-descriptions-item label="本方账号">{{ detail.ourAccount }}</el-descriptions-item>
        <el-descriptions-item label="本方账户开户行">{{ detail.ourBankName }}</el-descriptions-item>
        <el-descriptions-item label="收支标识">
          {{ dictFormat(sys_income_expenses, detail.incomeExpenseFlag) }}
        </el-descriptions-item>
 
        <el-descriptions-item label="交易金额">
          <span class="amount-text">{{ detail.transactionAmount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="交易币种">{{ detail.currency }}</el-descriptions-item>
        <el-descriptions-item label="对方账号">{{ detail.counterpartyAccount }}</el-descriptions-item>
 
        <el-descriptions-item label="对方户名">{{ detail.counterpartyName }}</el-descriptions-item>
        <el-descriptions-item label="交易日期">{{ detail.transactionDate }}</el-descriptions-item>
        <el-descriptions-item label="用途">{{ detail.purpose }}</el-descriptions-item>
 
        <el-descriptions-item label="摘要" :span="1">{{ detail.summary }}</el-descriptions-item>
        <el-descriptions-item label="附言" :span="1">{{ detail.remarks }}</el-descriptions-item>
        <el-descriptions-item label="已认领金额">{{ detail.claimedAmount || 0 }}</el-descriptions-item>
 
        <el-descriptions-item label="待认领金额">
          <span class="text-danger font-bold">{{ remainingAmountDr }}</span>
        </el-descriptions-item v-if="isViewMode">
        <el-descriptions-item label="关联账单类型">
          <span v-if="detail.incomeExpenseFlag == 0">
            客户
          </span>
          <span v-if="detail.incomeExpenseFlag == 1">
            供应商
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="" :span="1"></el-descriptions-item>
      </el-descriptions>
 
      <div class="section-header">{{ isViewMode ? '账单认领明细' : '账单认领' }}</div>
 
      <div v-if="!isViewMode" class="type-selection-bar mb-20">
        <span class="required-label">关联账单类型</span>
        <el-radio-group v-model="detail.incomeExpenseFlag" disabled @change="handleTypeChange">
          <el-radio :label="0">应收账单</el-radio>
          <el-radio :label="1">应付账单</el-radio>
        </el-radio-group>
      </div>
 
      <div v-if="!isViewMode" class="mb-10">
        <el-button type="primary" icon="Plus" @click="handleAddRow">新增</el-button>
      </div>
 
      <el-table :data="detail.claimDetails" border stripe>
        <el-table-column label="账单编号" min-width="220">
          <template #default="{ row, $index }">
            <el-input v-model="row.billNo" @click="openReceivableDialog($index)" :disabled="!row.$edit" readonly
              placeholder="点击选择账单">
              <template v-if="row.$edit" #append>
                <el-button icon="Search" @click="openReceivableDialog($index)" :disabled="!row.$edit" />
              </template>
            </el-input>
          </template>
        </el-table-column>
 
        <el-table-column label="关联企业类型" width="120">
          <template #default="{ row }">
            <span>{{ row.relatedCompanyType }}</span>
          </template>
        </el-table-column>
 
        <el-table-column label="关联企业名称" width="150">
          <template #default="{ row }">
            <span>{{ row.relatedCompanyName }}</span>
          </template>
        </el-table-column>
 
        <el-table-column label="账单金额" width="120">
          <template #default="{ row }">
            <span>{{ row.billAmount || 0 }}</span>
          </template>
        </el-table-column>
 
        <el-table-column label="账单待结算金额" width="130">
          <template #default="{ row }">
            <span>{{ row.billPendingAmount || 0 }}</span>
          </template>
        </el-table-column>
 
        <el-table-column label="认领金额" width="150">
          <template #default="{ row }">
            <el-input-number v-model="row.claimAmount" :precision="2" :controls="false" :disabled="!row.$edit" :min="0"
              style="width: 100%" placeholder="输入金额" @change="(val) => handleAmountChange(val, row)" />
          </template>
        </el-table-column>
 
        <el-table-column label="认领日期" width="200"> <template #default="{ row }">
            <el-date-picker v-model="row.claimDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
              :disabled="!row.$edit" style="width: 100%" placeholder="选择日期时间" />
          </template>
        </el-table-column>
 
        <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" :disabled="!row.$edit" placeholder="备注信息" />
          </template>
        </el-table-column>
 
        <el-table-column label="操作" v-if="!isViewMode" width="120" fixed="right" align="center">
          <template #default="{ row, $index }">
            <template v-if="row.$edit">
              <el-button type="primary" link @click="handleSaveRow(row)">确定</el-button>
            </template>
            <template v-else>
              <!-- <el-button type="primary" link @click="row.$edit = true">修改</el-button> -->
              <el-button type="danger" link @click="handleDeleteRow(row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
 
      <pagination v-show="total > 10" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
 
    </div>
 
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="handleCancel">关 闭</el-button>
        <!-- <el-button type="primary" @click="handleFinalSubmit">确 定</el-button> -->
      </div>
    </template>
  </el-dialog>
 
  <receivableBillManagementDialog :default-status="-1" v-model:visible="receivablIshow"
    :default-selected-id="detail.invoiceManageId" @confirm="receivablForm" />
 
  <AccountsPayableManagementDialog :default-status="-1" v-model:visible="accountsIshow"
    :default-selected-id="detail.invoiceManageId" @confirm="accountsForm" />
</template>
 
<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import useCurrentInstance from "@/utils/useCurrentInstance";
import receivableBillManagementDialog from "../receivableBillManagementDialog/index.vue";
import AccountsPayableManagementDialog from "../AccountsPayableManagementDialog/index.vue";
import { addFundFlowClaimDetailClaim } from "@/api/cwgl/fundFlow";
import { delFundFlowClaimDetail, } from "@/api/cwgl/fundFlowClaimDetail";
import { listFundFlowClaimDetail } from "@/api/cwgl/fundFlowClaimDetail";
import { getFundFlow, } from "@/api/cwgl/fundFlow";
 
const { proxy } = useCurrentInstance();
const { sys_income_expenses } = proxy.useDict('sys_income_expenses');
 
const dictFormat = (dict: any, value: any) => proxy.selectDictLabel(dict, value);
const emit = defineEmits(['submit']);
const visible = ref(false);
const detail = ref<any>({
  claimDetails: []
});
const billType = ref('');
 
// 1. 【待认领金额计算】: 交易金额 - 已认领金额 )
const remainingAmountDr = computed(() => {
  const total = parseFloat(detail.value.transactionAmount) || 0;
  const alreadyClaimed = parseFloat(detail.value.claimedAmount) || 0;
  const res = total - alreadyClaimed;
  return res.toFixed(2);
});
 
// 1. 实时计算待认领池子(剩余总额)
const remainingAmount = computed(() => {
  const total = parseFloat(detail.value.transactionAmount) || 0; // 流水总额
  const historicClaimed = parseFloat(detail.value.claimedAmount) || 0; // 历史已认领
 
  // 累加当前表格中所有行填写的金额
  const currentTableTotal = (detail.value.claimDetails || []).reduce((sum, item) => {
    return sum + (parseFloat(item.claimAmount) || 0);
  }, 0);
 
  const res = total - historicClaimed - currentTableTotal;
  return res.toFixed(2);
});
 
// 修正后的函数
const handleAmountChange = (val: number | null, row: any) => {
  if (val === null) return;
 
  // 1. 获取池子剩余(需要加回当前行金额)
  const currentRemaining = parseFloat(remainingAmount.value) || 0;
  const currentLineAmount = val || 0;
  // 计算此时如果没填这一行,池子有多少钱
  // 注意:这里因为 val 已经改变了,remainingAmount 已经减去了新的 val
  // 所以池子可用总量 = remainingAmount + val
  const totalAvailablePool = currentRemaining + currentLineAmount;
 
  // 2. 确定两个上限
  const limitByBill = row.billAmount || 0; // 账单上限
  const limitByPool = totalAvailablePool;         // 流水上限
 
  // 3. 校验并修正
  if (val > limitByBill) {
    ElMessage.warning(`认领金额不能超过账单金额 (${limitByBill})`);
    row.claimAmount = limitByBill;
  } else if (val > limitByPool) {
    ElMessage.warning(`认领金额不能超过流水待认领金额 (${limitByPool.toFixed(2)})`);
    // row.claimAmount = parseFloat(limitByPool.toFixed(2));
  }
};
 
// 建议保留 getMaxClaimAmount 作为一个保险上限,或者直接删除它
const getMaxClaimAmount = (row: any) => {
  // 为了不干扰输入过程,这里返回一个极大的安全值,或者流水总金额
  return parseFloat(detail.value.transactionAmount) || 99999999;
};
// 重置表单和数据
const resetForm = () => {
  // 1. 清空明细表格
  detail.value = {
    claimDetails: [],
    // 如果有其他需要清空的流水基础信息,也可以在这里初始化
    transactionAmount: 0,
    claimedAmount: 0
  };
 
  // 2. 清空选择的账单类型
  billType.value = '';
 
  // 3. 重置索引和弹窗控制变量
  currentRowIndex.value = null;
  receivablIshow.value = false;
  accountsIshow.value = false;
};
// 取消按钮点击事件
const handleCancel = () => {
  visible.value = false;
  resetForm();
};
const isViewMode = ref(false); // 新增:模式控制
 
// --- 新增:分页与搜索相关的响应式变量 ---
const total = ref(0);
const loading = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  fundFlowId: null as any // 关联的流水ID
});
 
// --- 新增:获取列表数据的方法 ---
const getList = async () => {
  if (!detail.value.id) return;
 
  loading.value = true;
  try {
    const res = await listFundFlowClaimDetail({
      ...queryParams.value,
      fundFlowId: detail.value.id
    });
    if (res.code === 200) {
      detail.value.claimDetails = res.rows;
      detail.value.claimDetails.forEach((item: any) => {
        if (item.$edit === undefined) {
          item.$edit = false;
        }
      });
      total.value = res.total;
    }
  } catch (error) {
    console.error("获取明细列表失败", error);
  } finally {
    loading.value = false;
  }
};
const handleExport = () => {
  proxy.download("/cwgl/fundFlowClaimDetail/export", { ...queryParams.value })
}
 
// 打开弹窗
const open = (rowData: any, mode: 'view' | 'edit' = 'edit') => {
  // 1. 先重置一次,防止上次残留
  resetForm();
  isViewMode.value = mode === 'view'; // 设置模式
  // 2. 浅拷贝基础数据
  detail.value = {
    ...rowData,
  };
 
  // 3. 处理 billType 的自动回显逻辑
  if (detail.value.claimDetails && detail.value.claimDetails.length > 0) {
    // 取出第一条明细的关联企业类型
    const firstCompanyType = detail.value.claimDetails[0].relatedCompanyType;
 
    // 确保已有的数据行不会变成编辑模式
    getList()
  }
 
  visible.value = true;
};
// 关联账单类型切换逻辑
const handleTypeChange = (val: string) => {
  if (detail.value.claimDetails && detail.value.claimDetails.length > 0) {
    ElMessageBox.confirm('切换账单类型将清空当前已添加的认领明细,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      detail.value.claimDetails = [];
      ElMessage.success('已清空明细');
    }).catch(() => {
      billType.value = val === 'RECEIVABLE' ? 'PAYABLE' : 'RECEIVABLE';
    });
  }
};
 
// 新增行
// 修改新增行逻辑
const handleAddRow = () => {
 
  const defaultCompanyType = detail.value.incomeExpenseFlag == 0 ? '客户' : '供应商';
 
  // 获取当前时间的 YYYY-MM-DD HH:mm:ss 格式
  const now = new Date();
  const formatTime = (date: Date) => {
    const pad = (num: number) => String(num).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
      `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  };
 
  detail.value.claimDetails.push({
    billNo: '',
    claimAmount: 0,
    claimDate: formatTime(now), // 使用带时分秒的默认值
    remark: '',
    relatedCompanyType: defaultCompanyType,
    relatedCompanyName: '',
    billAmount: 0,
    billPendingAmount: 0,
    $edit: true
  });
};
 
// 保存行
const handleSaveRow = (row: any) => {
  if (!row.billNo) return ElMessage.warning('请选择账单编号');
 
  // 转换数值,确保计算准确
  const currentClaim = parseFloat(row.claimAmount) || 0;
  if (currentClaim <= 0) return ElMessage.warning('认领金额必须大于0');
 
  // 1. 获取当前计算属性中的剩余额度(此时已经扣除了所有行的 claimAmount)
  const currentRemaining = parseFloat(remainingAmount.value) || 0;
 
  // 2. 【关键】计算该行实际可用的“剩余池子上限”
  // 公式:池子真实余量 = 当前显示的余额 + 该行刚才占用的额度
  const poolLimit = currentRemaining + currentClaim;
 
  // 3. 获取账单本身的上限
  const billLimit = row.billPendingAmount || row.billAmount || 0;
 
  // --- 开始拦截判定 ---
 
  // 判定 A:超过账单欠款
  if (currentClaim > billLimit) {
    return ElMessage.error(`保存失败:认领金额不能超过账单待结算金额 (${billLimit})`);
  }
 
  // 判定 B:超过流水总余量
  // 使用 0.01 容差防止 JS 浮点数计算误差
  if (currentClaim > (poolLimit + 0.01)) {
    return ElMessage.error(`保存失败:认领总额超过流水待认领金额,该行当前最大可填 ${poolLimit.toFixed(2)}`);
  }
  addFundFlowClaimDetailClaim(row, detail.value.id).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("保存成功");
      getFundFlow(detail.value.id).then((res) => {
        if (res.code == 200) {
          detail.value = res.data;
          getList(); // 使用统一的 getList 方法
 
        }
      });
    }
  })
};
 
const handleDeleteRow = (row: any) => {
  proxy.$modal.confirm('是否确认删除账单编号为"' + row.billNo + '"?').then(function () {
    return delFundFlowClaimDetail(row.id);
  }).then((res) => {
    if (res.code == 200) {
      getFundFlow(detail.value.id).then((res) => {
        if (res.code == 200) {
          detail.value = res.data;
          getList(); // 使用统一的 getList 方法
          proxy.$modal.msgSuccess("删除成功");
        }
      });
    }
 
 
  }).catch(() => { });
};
 
const receivablIshow = ref(false);
const currentRowIndex = ref<number | null>(null);
const accountsIshow = ref(false);
 
const openReceivableDialog = (index: number) => {
  currentRowIndex.value = index;
  if (detail.value.incomeExpenseFlag == '0') {
    receivablIshow.value = true;
  } else if (detail.value.incomeExpenseFlag == '1') {
    accountsIshow.value = true;
  }
 
};
 
// 回填弹窗选中的数据
const receivablForm = (data: any) => {
  const defaultCompanyType = detail.value.incomeExpenseFlag == 0 ? '客户' : '供应商';
 
  if (currentRowIndex.value !== null && data) {
    const row = detail.value.claimDetails[currentRowIndex.value];
 
    row.billNo = data.systemNo
    row.relatedCompanyType = defaultCompanyType;
    row.relatedCompanyName = data.customerName
    row.billAmount = data.totalAmount || 0;
    row.billPendingAmount = data.pendingAmount || 0;
 
 
    currentRowIndex.value = null;
    receivablIshow.value = false;
  }
};
 
const accountsForm = (data: any) => {
  const defaultCompanyType = detail.value.incomeExpenseFlag == 0 ? '客户' : '供应商';
  if (currentRowIndex.value !== null && data) {
    const row = detail.value.claimDetails[currentRowIndex.value];
    row.billNo = data.systemNo
    row.relatedCompanyType = defaultCompanyType;
    row.relatedCompanyName = data.supplierName
    row.billAmount = data.totalAmount || 0;
    row.billPendingAmount = data.pendingAmount || 0;
    currentRowIndex.value = null;
    accountsIshow.value = false;
  }
};
 
// 确定提交
const handleFinalSubmit = () => {
  if (!billType.value) return ElMessage.warning('请选择关联账单类型');
  if (detail.value.claimDetails.length === 0) return ElMessage.warning('请添加至少一条认领明细');
 
  const hasEditing = detail.value.claimDetails.some((row: any) => row.$edit);
  if (hasEditing) return ElMessage.warning('请先保存正在编辑的明细行');
 
  if (parseFloat(remainingAmount.value) < 0) {
    return ElMessage.error('最终认领总额不能超过流水待认领金额');
  }
  emit('submit', detail.value);
  // console.log("提交数据:", detail.value);
  // ElMessage.success('操作成功');
  // visible.value = false;
};
 
defineExpose({ open, handleCancel });
</script>
 
<style scoped>
.claim-wrapper {
  padding: 0 10px;
}
 
.section-header {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0 10px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
  color: #303133;
}
 
.type-selection-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  background: #f8f9fb;
  padding: 10px 15px;
  border-radius: 4px;
}
 
.required-label {
  font-size: 14px;
  font-weight: bold;
  color: #606266;
}
 
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
 
.amount-text {
  color: #409eff;
  font-weight: bold;
}
 
.text-danger {
  color: #f56c6c;
}
 
.font-bold {
  font-weight: bold;
}
 
.mb-20 {
  margin-bottom: 20px;
}
 
.mb-10 {
  margin-bottom: 10px;
}
 
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: transparent;
  box-shadow: none;
}
 
:deep(.el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell) {
  width: 16%;
}
</style>