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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
<template>
  <div class="app-container">
    <el-card class="header-card" shadow="never">
      <div class="header-row">
        <div class="header-title">项目详情</div>
        <div class="header-actions">
          <el-button style="color: white;background: #002FA7;" @click="openProgressReport">进度汇报</el-button>
          <!-- <el-button type="danger" @click="openDiscussProgress">洽谈进度</el-button> -->
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>
      <el-steps v-if="steps.length > 0" :active="activeStep" align-center finish-status="success">
        <el-step v-for="(s, idx) in steps" :key="idx" :title="s" />
      </el-steps>
    </el-card>
 
    <el-card class="content-card" shadow="never" v-loading="loading">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础资料" name="base">
          <el-descriptions :column="4" border>
            <el-descriptions-item label="项目ID">{{ info.id ?? '-' }}</el-descriptions-item>
            <el-descriptions-item label="单据编号">{{ info.no || '-' }}</el-descriptions-item>
            <el-descriptions-item label="项目名称">{{ info.title || '-' }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">{{ info.clientName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="客户ID">{{ info.clientId ?? '-' }}</el-descriptions-item>
            <el-descriptions-item label="父项目">{{ parentProjectLabel }}</el-descriptions-item>
            <el-descriptions-item label="项目类型">{{ projectTypeLabel }}</el-descriptions-item>
            <el-descriptions-item label="立项日期">{{ info.establishTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="项目来源">{{ info.source || '-' }}</el-descriptions-item>
            <el-descriptions-item label="立项人">{{ info.managerName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="业务员">{{ info.salesmanName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ info.departmentName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="单据状态">
              <dict-tag :options="bill_status" :value="String(info.status ?? '')" />
            </el-descriptions-item>
            <el-descriptions-item label="审核状态">
              <dict-tag :options="project_management" :value="String(info.reviewStatus ?? '')" />
            </el-descriptions-item>
            <el-descriptions-item label="计划状态">
              <dict-tag :options="plan_status" :value="String(info.stage ?? '')" />
            </el-descriptions-item>
            <el-descriptions-item label="预计工期(天)">{{ estimatedDays }}</el-descriptions-item>
            <el-descriptions-item label="计划开始日期">{{ info.planStartTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="计划完成日期">{{ info.planEndTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="实际开始日期">{{ info.actualStartTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="实际完成日期">{{ info.actualEndTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="订单日期">{{ info.orderDate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="项目金额">{{ info.orderAmount ?? '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="4">{{ info.remark || '-' }}</el-descriptions-item>
          </el-descriptions>
 
          <div class="attachment-block" v-if="attachments.length > 0">
            <div class="attachment-title">附件</div>
            <div class="attachment-list">
              <div v-for="(att, idx) in attachments" :key="att.id || att.url || idx" class="attachment-item">
                <el-icon><Document /></el-icon>
                <span class="attachment-name">{{ att.name || att.fileName || att.url || '附件' }}</span>
                <el-button link type="primary" size="small" @click="downloadAttachment(att)">下载</el-button>
              </div>
            </div>
          </div>
 
          <el-divider content-position="left">产品信息</el-divider>
          <el-table :data="productRows" border show-summary :summary-method="summarizeProductTable">
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="产品大类" prop="productCategory" show-overflow-tooltip />
            <el-table-column label="规格型号" prop="specificationModel" show-overflow-tooltip />
            <el-table-column label="单位" prop="unit" width="90" />
            <el-table-column label="数量" prop="quantity" width="90" />
            <el-table-column label="税率(%)" prop="taxRate" width="90" />
            <el-table-column label="含税单价(元)" prop="taxInclusiveUnitPrice" :formatter="formattedNumber" />
            <el-table-column label="含税总价(元)" prop="taxInclusiveTotalPrice" :formatter="formattedNumber" />
            <el-table-column label="不含税总价(元)" prop="taxExclusiveTotalPrice" :formatter="formattedNumber" />
            <el-table-column label="发票类型" prop="invoiceType" width="110" />
          </el-table>
 
          <el-divider content-position="left">项目团队</el-divider>
          <el-table :data="teamRows" border>
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="姓名" prop="userName" show-overflow-tooltip />
            <el-table-column label="项目组角色" prop="userRoleName" show-overflow-tooltip />
            <el-table-column label="进入日期" prop="joinTime" width="140" />
            <el-table-column label="离开日期" prop="departTime" width="140" />
            <el-table-column label="联系方式" prop="contact" show-overflow-tooltip />
            <el-table-column label="备注" prop="remark" show-overflow-tooltip />
          </el-table>
 
          <el-divider content-position="left">收货地址</el-divider>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="收货人">{{ shippingAddress.consignee || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系方式">{{ shippingAddress.contract || '-' }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ shippingAddress.address || '-' }}</el-descriptions-item>
          </el-descriptions>
 
          <el-divider content-position="left">联系信息</el-divider>
          <el-descriptions :column="4" border>
            <el-descriptions-item label="联系人">{{ contractInfo.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ contractInfo.sex || '-' }}</el-descriptions-item>
            <el-descriptions-item label="生日">{{ contractInfo.birthday || '-' }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ contractInfo.department || '-' }}</el-descriptions-item>
            <el-descriptions-item label="职务">{{ contractInfo.job || '-' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ contractInfo.phoneNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ contractInfo.email || '-' }}</el-descriptions-item>
            <el-descriptions-item label="QQ">{{ contractInfo.qq || '-' }}</el-descriptions-item>
            <el-descriptions-item label="固定电话">{{ contractInfo.lineaFissa || '-' }}</el-descriptions-item>
            <el-descriptions-item label="微信">{{ contractInfo.wx || '-' }}</el-descriptions-item>
            <el-descriptions-item label="籍贯">{{ contractInfo.origineEtnica || '-' }}</el-descriptions-item>
            <el-descriptions-item label="法人代表">{{ contractInfo.rappresentanteLegale || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
 
        <el-tab-pane label="项目类型" name="plan">
          <el-descriptions :column="4" border>
            <el-descriptions-item label="类型名称">{{ projectPlan.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">{{ projectPlan.description || '-' }}</el-descriptions-item>
          </el-descriptions>
 
          <div class="attachment-block" v-if="planAttachments.length > 0">
            <div class="attachment-title">类型附件</div>
            <div class="attachment-list">
              <div v-for="(att, idx) in planAttachments" :key="att.id || att.url || idx" class="attachment-item">
                <el-icon><Document /></el-icon>
                <span class="attachment-name">{{ att.name || att.fileName || att.url || '附件' }}</span>
                <el-button link type="primary" size="small" @click="downloadAttachment(att)">下载</el-button>
              </div>
            </div>
          </div>
 
          <el-table :data="planNodeRows" border style="margin-top: 14px;">
            <el-table-column align="center" label="步骤" type="index" width="80" />
            <el-table-column label="阶段名称" prop="name" min-width="160" show-overflow-tooltip />
            <el-table-column label="负责人" prop="leaderName" width="140" show-overflow-tooltip />
            <el-table-column label="预计工期(天)" prop="estimatedDuration" width="140" />
            <el-table-column label="工时单价" prop="hourlyRate" width="120" />
            <el-table-column label="作业内容" prop="workContent" min-width="180" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>
 
        <el-tab-pane label="项目阶段" name="stage">
          <el-table :data="stageNodeRows" border style="margin-top: 14px;">
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="阶段" prop="stageName" min-width="160" show-overflow-tooltip />
            <el-table-column label="描述" prop="description" min-width="220" show-overflow-tooltip />
            <el-table-column label="实际负责人" prop="actualLeaderName" width="140" show-overflow-tooltip />
            <el-table-column label="进度(%)" prop="progress" width="110" />
            <el-table-column label="计划开始" prop="planStartTime" width="120" />
            <el-table-column label="计划结束" prop="planEndTime" width="120" />
            <el-table-column label="实际开始" prop="actualStartTime" width="120" />
            <el-table-column label="实际结束" prop="actualEndTime" width="120" />
            <el-table-column label="预计工期(天)" prop="estimatedDuration" width="130" />
            <el-table-column label="附件" width="90" align="center">
              <template #default="{ row }">
                <span>{{ row.attachmentCount }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="false" label="操作" width="100" align="center" fixed="right" >
              <template #default="{ row }">
                <el-button link type="danger" size="small" @click="handleDeleteStage(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
 
        <el-tab-pane label="诉讼信息" name="lawsuit">
          <el-table :data="lawsuitRows" border v-loading="lawsuitLoading" style="margin-top: 14px;">
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="案件编号" prop="caseNo" width="160" show-overflow-tooltip />
            <el-table-column label="所属项目" prop="projectName" min-width="160" show-overflow-tooltip />
            <el-table-column label="合同编号" prop="contractNo" width="160" show-overflow-tooltip />
            <el-table-column label="诉讼状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="lawsuitStatusTypeMap[row.lawsuitStatus] || 'info'">{{ row.lawsuitStatus || '-' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="立案时间" prop="filingDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="承办律师/法务负责人" prop="lawyer" width="160" show-overflow-tooltip />
            <el-table-column label="开庭时间" prop="hearingDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="诉讼标的金额(元)" prop="claimAmount" width="150" align="right" :formatter="formatAmountColumn" />
            <el-table-column label="判决结果摘要" prop="judgmentSummary" min-width="180" show-overflow-tooltip />
            <el-table-column label="诉讼进展备注" prop="progressRemark" min-width="160" show-overflow-tooltip />
            <el-table-column label="附件" min-width="160">
              <template #default="{ row }">
                <div v-if="getLawsuitAttachments(row).length > 0" class="attachment-list">
                  <el-button
                    v-for="att in getLawsuitAttachments(row)"
                    :key="att.id || att.url || att.name || att.fileName"
                    link
                    type="primary"
                    size="small"
                    @click="downloadAttachment(att)"
                  >{{ att.name || att.fileName || '附件' }}</el-button>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
 
        <el-tab-pane label="中标信息" name="bidding">
          <el-table :data="biddingRows" border v-loading="biddingLoading" style="margin-top: 14px;">
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="所属项目" prop="projectName" min-width="160" show-overflow-tooltip />
            <el-table-column label="标书名称" prop="bidDocName" min-width="160" show-overflow-tooltip />
            <el-table-column label="招标单位" prop="tenderUnit" width="160" show-overflow-tooltip />
            <el-table-column label="投标单位" prop="bidUnit" width="160" show-overflow-tooltip />
            <el-table-column label="招标日期" prop="tenderDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="投标日期" prop="bidDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="标书款金额(元)" prop="bidDocFee" width="130" align="right" :formatter="formatAmountColumn" />
            <el-table-column label="标书款状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="bidDocFeeStatusTypeMap[row.bidDocFeeStatus] || 'info'">{{ row.bidDocFeeStatus || '-' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="标书款状态变更日期" prop="bidDocFeeStatusChangeDate" width="160" :formatter="formatDateColumn" />
            <el-table-column label="投标保证金(元)" prop="bidDeposit" width="130" align="right" :formatter="formatAmountColumn" />
            <el-table-column label="招投标结果" width="150" align="center">
              <template #default="{ row }">
                <el-tag :type="bidResultTypeMap[row.bidResult] || 'info'">{{ row.bidResult || '-' }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
 
        <el-tab-pane label="销售合同" name="contract">
          <el-table :data="contractRows" border v-loading="contractLoading" style="margin-top: 14px;">
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column label="销售合同号" prop="salesContractNo" width="180" show-overflow-tooltip />
            <el-table-column label="客户名称" prop="customerName" min-width="180" show-overflow-tooltip />
            <el-table-column label="业务员" prop="salesman" width="100" show-overflow-tooltip />
            <el-table-column label="项目名称" prop="projectName" width="180" show-overflow-tooltip />
            <el-table-column label="付款方式" prop="paymentMethod" width="120">
              <template #default="{ row }">
                <dict-tag :options="checkout_payment" :value="row.paymentMethod" />
              </template>
            </el-table-column>
            <el-table-column label="合同金额(元)" prop="contractAmount" width="140" align="right" :formatter="formatAmountColumn" />
            <el-table-column label="实际合同金额(元)" prop="netContractAmount" width="150" align="right" :formatter="formatAmountColumn" />
            <el-table-column label="录入人" prop="entryPersonName" width="100" show-overflow-tooltip />
            <el-table-column label="录入日期" prop="entryDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="签订日期" prop="executionDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="交付日期" prop="deliveryDate" width="110" :formatter="formatDateColumn" />
            <el-table-column label="备注" prop="remarks" min-width="160" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
 
  <ProgressReportDialog
    v-model="progressReportVisible"
    :project-id="info.id"
    :project-info="info"
    :plan-nodes="planNodeRows"
    :default-plan-node-id="defaultPlanNodeId"
    @submitted="handleProgressSubmitted"
  />
  <DiscussProgressDialog
    v-model="discussProgressVisible"
    :project-id="info.id"
    :plan-nodes="planNodeRows"
    :default-plan-node-id="defaultPlanNodeId"
    @submitted="handleDiscussSubmitted"
  />
</template>
 
<script setup name="ProjectManagementDetail">
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProject, saveStage, listStage, deleteStage } from '@/api/projectManagement/project'
import { listPlan } from '@/api/projectManagement/projectType'
import { lawsuitListPage } from '@/api/salesManagement/lawsuitManagement'
import { biddingListPage } from '@/api/salesManagement/biddingManagement'
import { ledgerListPage } from '@/api/salesManagement/salesLedger'
import ProgressReportDialog from '@/components/ProjectManagement/ProgressReportDialog.vue'
import DiscussProgressDialog from '@/components/ProjectManagement/DiscussProgressDialog.vue'
import useUserStore from '@/store/modules/user'
 
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const { bill_status, project_management, plan_status } = proxy.useDict('bill_status', 'project_management', 'plan_status')
const { checkout_payment } = proxy.useDict('checkout_payment')
 
const loading = ref(false)
const activeTab = ref('base')
const progressReportVisible = ref(false)
const discussProgressVisible = ref(false)
const userStore = useUserStore()
 
const info = ref({})
const shippingAddress = ref({})
const contractInfo = ref({})
const productRows = ref([])
const teamRows = ref([])
const attachments = ref([])
const projectTypeMap = ref(new Map())
const projectPlan = ref({})
const planNodeRows = ref([])
const planAttachments = ref([])
const stageNodeRows = ref([])
 
const lawsuitRows = ref([])
const biddingRows = ref([])
const contractRows = ref([])
const lawsuitLoading = ref(false)
const biddingLoading = ref(false)
const contractLoading = ref(false)
 
const estimatedDays = computed(() => {
  const raw = info.value?.estimatedDays
  const n = Number(raw)
  if (Number.isFinite(n) && n > 0) return n
  const start = info.value?.planStartTime
  const end = info.value?.planEndTime
  if (!start || !end) return 0
  const startTime = new Date(`${start}T00:00:00`).getTime()
  const endTime = new Date(`${end}T00:00:00`).getTime()
  if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime < startTime) return 0
  return Math.floor((endTime - startTime) / (24 * 60 * 60 * 1000)) + 1
})
 
const projectTypeLabel = computed(() => {
  const id = info.value?.projectManagementPlanId
  if (id === undefined || id === null || id === '') return '-'
  const p = projectTypeMap.value.get(Number(id))
  return p?.name || String(id)
})
 
const parentProjectLabel = computed(() => {
  return (
    info.value?.parentTitle ||
    info.value?.projectManagementInfoParentName ||
    info.value?.projectManagementInfoParentId ||
    '-'
  )
})
 
const planStageEnum = computed(() => {
  const list = Array.isArray(plan_status) ? plan_status : []
  return list.map(i => ({ value: String(i.value), label: i.label }))
})
 
const steps = computed(() => {
  const nodes = Array.isArray(planNodeRows.value) ? planNodeRows.value : []
  const sorted = [...nodes].sort((a, b) => Number(a.sort ?? 0) - Number(b.sort ?? 0))
  const labels = sorted.map(i => i.name || i.workContent).filter(Boolean)
  return labels.length > 0 ? labels : planStageEnum.value.map(i => i.label)
})
 
const activeStep = computed(() => {
  const statusOrStage = info.value?.stage ?? info.value?.status
  const enumList = planStageEnum.value
  // 优先使用 planStageEnum 的 value 匹配
  const found = enumList.find(i => i.value === String(statusOrStage))
  const label = found?.label
  // 在项目类型节点中查找对应 label 的下标
  const nodeLabels = steps.value
  const idxByLabel = label ? nodeLabels.findIndex(l => String(l) === String(label)) : -1
  if (idxByLabel >= 0) return idxByLabel + 1
  // 回退:如果 statusOrStage 是数字索引
  const n = Number(statusOrStage)
  if (Number.isFinite(n) && n > 0) return Math.min(n, nodeLabels.length)
  return 0
})
 
function goBack() {
  router.back()
}
 
function openProgressReport() {
  progressReportVisible.value = true
}
 
function openDiscussProgress() {
  discussProgressVisible.value = true
}
 
const defaultPlanNodeId = computed(() => {
  const nodes = Array.isArray(planNodeRows.value) ? planNodeRows.value : []
  if (nodes.length === 0) return undefined
  const stageVal = info.value?.stage
  const direct = nodes.find(n => String(n.id) === String(stageVal))
  if (direct?.id) return direct.id
  const sorted = [...nodes].sort((a, b) => Number(a.sort ?? 0) - Number(b.sort ?? 0))
  const idx = Number(stageVal)
  if (Number.isFinite(idx)) {
    const byIndex = sorted[idx - 1] || sorted[idx] || sorted[0]
    if (byIndex?.id) return byIndex.id
  }
  return sorted[0]?.id
})
 
async function handleProgressSubmitted(payload) {
  try {
    const nodes = Array.isArray(planNodeRows.value) ? planNodeRows.value : []
    const node = nodes.find(n => String(n.id) === String(payload.planNodeId)) || {}
    const description = payload.remark
      ? `${payload.reportDate || ''} ${payload.remark}`.trim()
      : `${payload.reportDate || ''} 进度汇报`.trim()
    const req = {
      id: null,
      projectManagementPlanNodeId: payload.planNodeId,
      projectManagementInfoId: info.value?.id,
      description,
      actualLeaderId: userStore.id || info.value?.managerId,
      actualLeaderName: userStore.nickName || info.value?.managerName || info.value?.managerName,
      estimatedDuration: Number(node.estimatedDuration ?? 0) || 0,
      planStartTime: payload.planStartTime || info.value?.planStartTime,
      planEndTime: payload.planEndTime || info.value?.planEndTime,
      actualStartTime: payload.actualStartTime || null,
      actualEndTime: payload.actualEndTime || null,
      progress: Number(payload.totalProgress ?? payload.completionProgress ?? 0) || 0,
      storageBlobDTOs: Array.isArray(payload.storageBlobDTOs) ? payload.storageBlobDTOs : []
    }
    const res = await saveStage(req)
    if (res?.code === 200) {
      ElMessage.success('提交成功')
      await Promise.all([loadDetail(), loadStageList()])
      return
    }
    ElMessage.error(res?.msg || '提交失败')
  } catch (e) {
    ElMessage.error('提交失败')
  }
}
 
async function handleDiscussSubmitted(payload) {
  try {
    const nodes = Array.isArray(planNodeRows.value) ? planNodeRows.value : []
    const node = nodes.find(n => String(n.id) === String(payload.planNodeId)) || {}
    const req = {
      id: null,
      projectManagementPlanNodeId: payload.planNodeId,
      projectManagementInfoId: info.value?.id,
      description: payload.remark,
      actualLeaderId: userStore.id || info.value?.managerId,
      actualLeaderName: userStore.nickName || info.value?.managerName || info.value?.managerName,
      estimatedDuration: Number(node.estimatedDuration ?? 0) || 0,
      planStartTime: info.value?.planStartTime,
      planEndTime: info.value?.planEndTime,
      actualStartTime: info.value?.actualStartTime || null,
      actualEndTime: info.value?.actualEndTime || null,
      progress: Number(info.value?.progress ?? 0) || 0,
      attachmentIds: Array.isArray(payload.attachmentIds) ? payload.attachmentIds : []
    }
    const res = await saveStage(req)
    if (res?.code === 200) {
      ElMessage.success('提交成功')
      await Promise.all([loadDetail(), loadStageList()])
      return
    }
    ElMessage.error(res?.msg || '提交失败')
  } catch (e) {
    ElMessage.error('提交失败')
  }
}
 
function downloadAttachment(row) {
  if (row?.url) {
    try {
            proxy.$download.byUrl(row.url, row.originalFilename);
      return
    } catch (e) {}
  }
  ElMessage.warning('附件暂无下载地址')
}
 
const lawsuitStatusTypeMap = {
  立案中: 'warning',
  审理中: 'primary',
  已判决: 'success',
  已撤诉: 'info',
  已和解: 'success'
}
 
const bidDocFeeStatusTypeMap = {
  未交: 'warning',
  已交: 'success',
  已退: 'info'
}
 
const bidResultTypeMap = {
  废标: 'info',
  流标: 'info',
  未中标: 'warning',
  中标待出通知书: 'primary',
  已出中标通知书: 'success',
  已签合同: 'success'
}
 
function formatDate(val) {
  if (val === undefined || val === null || val === '') return '-'
  return String(val).substring(0, 10)
}
 
function formatAmount(val) {
  if (val === undefined || val === null || val === '') return '0.00'
  const num = Number(val)
  return Number.isNaN(num) ? '0.00' : num.toFixed(2)
}
 
function formatDateColumn(row, column, cellValue) {
  return formatDate(cellValue)
}
 
function formatAmountColumn(row, column, cellValue) {
  return formatAmount(cellValue)
}
 
function getLawsuitAttachments(row) {
  if (Array.isArray(row?.storageBlobVOs)) return row.storageBlobVOs
  if (Array.isArray(row?.attachmentList)) return row.attachmentList
  return []
}
 
function matchProject(record, projectId, projectTitle) {
  if (!record) return false
  if (record.projectId !== undefined && record.projectId !== null && record.projectId !== '') {
    if (String(record.projectId) === String(projectId)) return true
  }
  const name = String(record.projectName || '').trim()
  const title = String(projectTitle || '').trim()
  if (name && title) {
    return name === title || name.includes(title) || title.includes(name)
  }
  return false
}
 
function filterByProject(records, projectId, projectTitle) {
  const list = Array.isArray(records) ? records : []
  if (list.length === 0) return []
  const matched = list.filter(r => matchProject(r, projectId, projectTitle))
  return matched.length > 0 ? matched : list
}
 
function extractRecords(res) {
  return (
    res?.data?.records ||
    res?.records ||
    res?.rows ||
    res?.data?.rows ||
    res?.data?.list ||
    (Array.isArray(res?.data) ? res.data : []) ||
    []
  )
}
 
async function loadLawsuitList() {
  const projectId = info.value?.id
  const projectTitle = info.value?.title
  if (!projectId) {
    lawsuitRows.value = []
    return
  }
  lawsuitLoading.value = true
  try {
    let res = await lawsuitListPage({ projectName: projectTitle, current: 1, size: 999 })
    let records = extractRecords(res)
    let matched = records.filter(r => matchProject(r, projectId, projectTitle))
    if (matched.length === 0) {
      res = await lawsuitListPage({ current: 1, size: 999 })
      records = extractRecords(res)
      matched = records.filter(r => matchProject(r, projectId, projectTitle))
    }
    lawsuitRows.value = matched
  } catch {
    lawsuitRows.value = []
  } finally {
    lawsuitLoading.value = false
  }
}
 
async function loadBiddingList() {
  const projectId = info.value?.id
  const projectTitle = info.value?.title
  if (!projectId) {
    biddingRows.value = []
    return
  }
  biddingLoading.value = true
  try {
    let res = await biddingListPage({ projectName: projectTitle, current: 1, size: 999 })
    let records = extractRecords(res)
    let matched = records.filter(r => matchProject(r, projectId, projectTitle))
    if (matched.length === 0) {
      res = await biddingListPage({ current: 1, size: 999 })
      records = extractRecords(res)
      matched = records.filter(r => matchProject(r, projectId, projectTitle))
    }
    biddingRows.value = matched
  } catch {
    biddingRows.value = []
  } finally {
    biddingLoading.value = false
  }
}
 
async function loadContractList() {
  const projectId = info.value?.id
  if (!projectId) {
    contractRows.value = []
    return
  }
  contractLoading.value = true
  try {
    const res = await ledgerListPage({ projectId, current: 1, size: 999 })
    const records = extractRecords(res)
    contractRows.value = filterByProject(records, projectId, info.value?.title).sort((a, b) => {
      const da = String(a.executionDate || '').substring(0, 10)
      const db = String(b.executionDate || '').substring(0, 10)
      if (!da && !db) return 0
      if (!da) return 1
      if (!db) return -1
      return db.localeCompare(da)
    })
  } catch {
    contractRows.value = []
  } finally {
    contractLoading.value = false
  }
}
 
async function loadProjectTypeMap() {
  try {
    const res = await listPlan({ current: 1, size: 999 })
    const records = res?.data?.records || res?.records || res?.rows || []
    projectTypeMap.value = new Map((records || []).map(r => [Number(r.id), r]))
  } catch {
    projectTypeMap.value = new Map()
  }
}
 
function getPlanNodeName(planNodeId) {
  const list = Array.isArray(planNodeRows.value) ? planNodeRows.value : []
  const node = list.find(n => String(n.id) === String(planNodeId))
  return node?.name || node?.workContent || String(planNodeId ?? '')
}
 
async function loadStageList() {
  const projectId = info.value?.id
  if (!projectId) {
    stageNodeRows.value = []
    return
  }
  try {
    const res = await listStage(projectId)
    const data = res?.data?.data ?? res?.data ?? res
    const list = data?.records || data?.rows || data?.list || data || []
    const records = Array.isArray(list) ? list : []
    stageNodeRows.value = records.map(r => {
      const attachmentList = Array.isArray(r.attachmentList) ? r.attachmentList : []
      const attachmentIds = Array.isArray(r.attachmentIds) ? r.attachmentIds : []
      return {
        ...r,
        stageName: getPlanNodeName(r.projectManagementPlanNodeId),
        attachmentCount: attachmentList.length || attachmentIds.length || 0
      }
    })
  } catch {
    stageNodeRows.value = []
  }
}
 
async function handleDeleteStage(row) {
  const stageId = row?.id
  if (!stageId) return
  try {
    await ElMessageBox.confirm('是否确认删除该项目阶段?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteStage(stageId)
    if (res?.code === 200) {
      ElMessage.success('删除成功')
      await loadStageList()
      return
    }
    ElMessage.error(res?.msg || '删除失败')
  } catch {}
}
 
function syncProjectPlan() {
  const id = info.value?.projectManagementPlanId
  if (id === undefined || id === null || id === '') {
    projectPlan.value = {}
    planNodeRows.value = []
    planAttachments.value = []
    return
  }
  const plan = projectTypeMap.value.get(Number(id)) || {}
  projectPlan.value = plan || {}
  planNodeRows.value = Array.isArray(plan?.planNodeList) ? plan.planNodeList : []
  planAttachments.value = Array.isArray(plan?.attachmentList) ? plan.attachmentList : []
}
 
async function loadDetail() {
  const id = route.params?.id
  if (!id) return
  loading.value = true
  try {
    const res = await getProject(id)
    const detail = res?.data?.data ?? res?.data ?? res
    info.value = detail?.info || {}
    shippingAddress.value = detail?.shippingAddress || {}
    contractInfo.value = detail?.contractInfo || {}
    productRows.value = Array.isArray(detail?.salesLedgerProductList) ? detail.salesLedgerProductList : []
    teamRows.value = Array.isArray(detail?.info?.teamList) ? detail.info.teamList : []
    attachments.value = Array.isArray(detail?.info?.attachmentList) ? detail.info.attachmentList : []
    syncProjectPlan()
    await loadStageList()
  } finally {
    loading.value = false
  }
}
 
onMounted(async () => {
  await loadProjectTypeMap()
  await loadDetail()
  await Promise.all([loadLawsuitList(), loadBiddingList(), loadContractList()])
})
</script>
 
<style scoped lang="scss">
.section-bar {
  width: 3px;
  height: 14px;
  background: #002FA7;
  border-radius: 2px;
}
.header-card {
  margin-bottom: 14px;
}
 
.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
 
.header-title {
  font-weight: 600;
  font-size: 16px;
}
 
.content-card {
  border-radius: 8px;
}
 
.attachment-block {
  margin-top: 14px;
}
 
.attachment-title {
  font-weight: 600;
  margin-bottom: 8px;
}
 
.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
 
.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
 
.attachment-name {
  max-width: 520px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>