negotiationDetail.js
30.2 KB
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
/**
* 洽谈明细页面 orchestrator
* @see packageDynamicForm/docs/PAGES.md#洽谈明细negotiationdetail
* @see packageDynamicForm/docs/ARCHITECTURE.md
*
* 职责:周历选日、F3 subform、VIN OCR / 品牌选择桥接、今日计划到店客户入口条与弹层导入
* 加载:loadNegotiationDailyForm(结构同门店,templateType=3)
* 写入:onFieldChange → engine;vinOcrBridge / carBrandPickerBridge 回填字段;applyCustomersToEngine 批量导入 F3
* 联调:NEGOTIATION_DAILY_API_SWITCH(../config/apiSwitch.js)
* 维护:改动 Page 方法 / 加载链 / VIN·品牌桥接时,同步 PAGES.md、DEVLOG.md 并补方法 JSDoc(见 MAINTENANCE.md § 三页 Page 后续开发)
*/
var timeUtil = require('~/utils/timeFormat/time-utils.js')
const { parseGroupErrorKey } = require('../../form-engine/group-values.js')
const negotiationApi = require('../../api/negotiationDailyReport.js')
const { loadNegotiationDailyForm } = require('../../services/negotiationDailyFormLoader.js')
const { isApiSuccess } = require('../../utils/api-response.js')
const { buildDailyReportRequestContext } = require('../../utils/daily-report-request-context.js')
const { isDailyReportFormDisabled, resolveReportSubmittedPatch } = require('../../utils/daily-report-edit-state.js')
const {
isDateWithinDailyReportEditableWindow
} = require('../../utils/daily-report-editable-window.js')
const vinOcrBridge = require('../../services/vinOcrBridge.js')
const { resolveVinFieldContext } = require('../../services/vin-ocr-context.js')
const carBrandPickerBridge = require('../../services/carBrandPickerBridge.js')
const { resolveCarBrandValueForValidation } = require('../../form-engine/car-brand-value.js')
const { getSubformRowTemplateForAdd } = require('../../form-engine/field-types.js')
const {
buildCompleteFunAssignments,
getOrderLinkageClearKeys,
findOrderListFieldInGroup,
isNegotiationDealDateFieldKey
} = require('../../form-engine/select-complete-fun.js')
const { isOrderListField } = require('../../utils/order-list-params.js')
const dailyReportPage = require('../behaviors/dailyReportPage.js')
const dailyReportPageMethods = require('../behaviors/dailyReportPageMethods.js')
const { applyCustomersToEngine } = require('../../services/negotiationCustomerImport.js')
const { hasPlanImportDateMarker } = require('../../form-engine/plan-import-date-value.js')
const {
buildPackageDynamicFormIconUrl,
TODAY_PLAN_BANNER_CLASS_ICON,
TODAY_PLAN_BANNER_ARROW_RIGHT_ICON
} = require('../../utils/upgrade-icon-url.js')
Page({
behaviors: [dailyReportPage],
data: {
navBarHeight: 0,
pageTitle: '洽谈明细',
selectWeek: 0,
timeBean: {},
reportDate: '',
weeklyList: [],
isTodayReport: true,
isDateWithinEditableWindow: false,
reportStatus: '0',
isReportSubmitted: false,
isEditReport: false,
merchantName: '',
fixedFields: [],
sectionGroups: [],
groupFields: [],
values: {},
errors: {},
formDisabled: false,
requestContext: {},
groupActiveIndex: {},
groupRowsCache: {},
groupRowVisibleMap: {},
groupRowTotalMap: {},
loading: true,
loadError: '',
todayPlanCustomerCount: 0,
showTodayPlanPopup: false,
todayPlanMerchantId: '',
todayPlanAdvanceUserId: '',
todayPlanStaffName: '',
todayPlanClassIconUrl: '',
todayPlanArrowRightIconUrl: ''
},
engine: null,
reportTemplateId: null,
dailyReportRecordId: null,
userContext: null,
pageContext: null,
_pageContextSnapshot: null,
loadSeq: 0,
refreshSeq: 0,
engineKey: '',
_submitting: false,
/** 页面加载:初始化周历、拉 weekly 标记、加载当日表单 */
onLoad(options = {}) {
if (options.reportTemplateId) {
this.reportTemplateId = Number(options.reportTemplateId) || options.reportTemplateId
}
const ctx = this.getRequestContext()
if (ctx.shopMerchantName) {
this.setData({ merchantName: ctx.shopMerchantName })
}
this.initTodayPlanBannerIcons()
this.applyCalendarState(this.data.selectWeek)
this.refreshWeeklyList()
this.loadFormData()
},
/** 从 OCR/选品牌子页返回时消费 pending VIN 回填 */
onShow() {
this.flushPendingVinApply()
},
/** 自定义导航栏高度回调 */
navbarReady(e) {
const height = e?.detail?.height
if (height == null) return
this.setData({
navBarHeight: height
})
},
/** 按 reportDate 重算可编辑窗口(相对今天 ±29 天) */
refreshEditableWindowState(reportDate = this.data.reportDate) {
const isDateWithinEditableWindow = reportDate
? isDateWithinDailyReportEditableWindow(reportDate)
: false
Object.assign(this.data, { isDateWithinEditableWindow })
return { isDateWithinEditableWindow, formDisabled: this.getFormDisabled() }
},
/** 根据 selectWeek 计算 reportDate、isTodayReport、可编辑窗口 */
buildCalendarState(selectWeek, timeBeanInput) {
const timeBean = timeBeanInput || timeUtil.getWeekDayList(selectWeek)
const selectDay = timeBean.selectDay ?? 0
const date = timeBean.weekDayList?.[selectDay]?.date || ''
if (date) {
const time = new Date(date)
timeBean.yearMonth = `${time.getFullYear()}-${time.getMonth() + 1}`
}
const isTodayReport = date ? timeUtil.isTodayReport(date) : true
const base = {
timeBean,
selectWeek,
reportDate: date,
isTodayReport
}
Object.assign(this.data, base)
return {
...base,
...this.refreshEditableWindowState(date)
}
},
/** 切换周历周偏移并同步 data */
applyCalendarState(selectWeek, timeBeanInput) {
this.resetEditReport()
const state = this.buildCalendarState(selectWeek, timeBeanInput)
Object.assign(this.data, state)
state.formDisabled = this.getFormDisabled()
this.setData(state)
return state
},
/** 周历点击选日:更新 timeBean.selectDay */
applyDaySelect(selectDay) {
this.resetEditReport()
const timeBean = { ...this.data.timeBean, selectDay }
const state = this.buildCalendarState(this.data.selectWeek, timeBean)
Object.assign(this.data, state)
state.formDisabled = this.getFormDisabled()
this.setData(state)
return state
},
/** 可编辑窗外只读;已提交且未点编辑时只读 */
getFormDisabled() {
return isDailyReportFormDisabled({
isDateWithinEditableWindow: this.data.isDateWithinEditableWindow,
isReportSubmitted: this.data.isReportSubmitted,
isEditReport: this.data.isEditReport
})
},
/** 从 detail + weeklyList 同步提交态,并重算可编辑窗口 */
syncReportSubmittedState(detail = {}) {
const patch = resolveReportSubmittedPatch({
detail,
reportDate: this.data.reportDate,
weeklyList: this.data.weeklyList || []
})
Object.assign(this.data, patch)
Object.assign(patch, this.refreshEditableWindowState())
this.setData(patch)
return patch.isReportSubmitted
},
/** 进入编辑态(可编辑窗外不可解锁) */
editReport() {
if (!this.data.isDateWithinEditableWindow) {
return wx.$util.showToast('已超过提交时效')
}
dailyReportPageMethods.editReport.call(this)
},
/** 复制当前 subform 各 group 的活跃行索引 */
getGroupActiveIndexMap() {
return { ...(this.data.groupActiveIndex || {}) }
},
/** 将 rowIndex 限制在 [0, rowTotal-1] 并写回 map */
clampGroupActiveIndex(groupKey, rowIndex, rowTotal = 0) {
const map = this.getGroupActiveIndexMap()
let index = Number(rowIndex) || 0
if (rowTotal <= 0) {
index = 0
} else if (index >= rowTotal) {
index = rowTotal - 1
} else if (index < 0) {
index = 0
}
map[groupKey] = index
return map
},
/** 校验失败时定位到首个出错 subform 行 */
buildGroupActiveIndexFromErrors(errorMap = {}) {
const map = this.getGroupActiveIndexMap()
Object.keys(errorMap).forEach(errorKey => {
const parsed = parseGroupErrorKey(errorKey)
if (parsed) {
map[parsed.groupKey] = parsed.rowIndex
}
})
return map
},
/** 按 key 查找 subform 字段定义 */
findGroupByKey(groupKey) {
return (this.data.groupFields || []).find(item => item.key === groupKey)
},
/** subform 行内子字段 schema 定义 */
findChildFieldDef(group, childKey) {
if (!group?.key) {
return null
}
const template = getSubformRowTemplateForAdd(group)
return template.find(item => item.key === childKey) || null
},
/** 成交日期/订单联动:清空订单及 completeFun 目标字段 */
clearOrderLinkageInRow(groupKey, rowIndex, group, excludeChildKey) {
const orderField = findOrderListFieldInGroup(group)
if (!orderField) {
return this.engine.getViewState()
}
let viewState = this.engine.getViewState()
getOrderLinkageClearKeys(orderField).forEach(clearKey => {
if (clearKey === excludeChildKey) {
return
}
viewState = this.engine.mutateSubform(groupKey, rowIndex, clearKey, '')
})
return viewState
},
/** subform 新增一行 */
onGroupAdd(e) {
if (this.data.formDisabled) return
const { groupKey } = e.detail || {}
if (!this.engine || !groupKey) return
const group = this.findGroupByKey(groupKey)
if (!group) return
const viewState = this.engine.addGroupRow(group)
if (viewState.added === false) {
wx.showToast({ title: '最多添加20条', icon: 'none' })
return
}
const rows = viewState.values[groupKey] || []
const errors = { ...this.data.errors }
delete errors[groupKey]
this.applyEngineView(viewState, {
errors,
structureChanged: false,
changedGroupKey: groupKey,
groupActiveIndex: this.clampGroupActiveIndex(groupKey, viewState.rowIndex, rows.length)
})
},
/** subform 删除指定行 */
onGroupRemove(e) {
if (this.data.formDisabled) return
const { groupKey, rowIndex } = e.detail || {}
if (!this.engine || groupKey == null || rowIndex == null) return
const viewState = this.engine.removeGroupRow(groupKey, rowIndex)
const rows = viewState.values[groupKey] || []
const errors = { ...this.data.errors }
delete errors[groupKey]
Object.keys(errors).forEach(key => {
const parsed = parseGroupErrorKey(key)
if (parsed?.groupKey === groupKey) {
delete errors[key]
}
})
this.applyEngineView(viewState, {
errors,
structureChanged: false,
changedGroupKey: groupKey,
groupActiveIndex: this.clampGroupActiveIndex(groupKey, rowIndex, rows.length)
})
},
/** subform 行翻页(direction ±1) */
onGroupNav(e) {
const { groupKey, direction } = e.detail || {}
if (!groupKey || !this.engine) return
const rows = this.engine.getGroupRows(groupKey) || []
const current = this.data.groupActiveIndex[groupKey] || 0
const nextIndex = Math.min(
Math.max(0, current + (Number(direction) || 0)),
Math.max(0, rows.length - 1)
)
const viewState = this.engine.getViewState()
this.applyEngineView(viewState, {
structureChanged: false,
changedGroupKey: groupKey,
keepErrors: true,
groupActiveIndex: this.clampGroupActiveIndex(groupKey, nextIndex, rows.length)
})
},
/** subform 单元格变更 → engine.setGroupFieldValue / setAppGroupFieldValue;订单 completeFun 联动 */
onGroupChange(e) {
if (this.data.formDisabled) return
const { groupKey, rowIndex, childKey, value, displayLabel, metaValue, orderRaw } =
e.detail || {}
if (!this.engine || !groupKey || childKey == null || rowIndex == null) return
const group = this.findGroupByKey(groupKey)
const childField = group ? this.findChildFieldDef(group, childKey) : null
let viewState
if (isNegotiationDealDateFieldKey(childKey) && group) {
viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, value)
viewState = this.clearOrderLinkageInRow(groupKey, rowIndex, group, childKey)
} else if (childField && /-\d+-10$/.test(childKey) && value === '否') {
viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, value)
viewState = this.clearOrderLinkageInRow(groupKey, rowIndex, group, childKey)
} else if (childField && isOrderListField(childField) && (orderRaw || metaValue)) {
const raw = orderRaw || metaValue?.raw || metaValue
const orderCode =
raw?.orderCode ??
(typeof value === 'object' && value != null ? value.orderCode : value) ??
metaValue?.id ??
''
viewState = this.engine.mutateSubform(
groupKey,
rowIndex,
childKey,
{
id: orderCode,
displayLabel: orderCode || displayLabel,
metaValue: raw
},
{ appDualKey: true }
)
buildCompleteFunAssignments(childField, raw).forEach(({ childKey: ck, value: v }) => {
viewState = this.engine.mutateSubform(groupKey, rowIndex, ck, v)
})
} else if (hasPlanImportDateMarker(value)) {
// 计划到店导入洽谈日期包装:勿走 appDualKey,否则 field.value 丢标记
viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, value)
} else {
const isObjectValue = value != null && typeof value === 'object' && !Array.isArray(value)
const hasDualKeyHint =
displayLabel != null && displayLabel !== '' || isObjectValue
if (hasDualKeyHint) {
const payload = isObjectValue
? {
metaValue: value,
displayLabel: value.name ?? value.label ?? displayLabel
}
: { id: value, displayLabel }
viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, payload, {
appDualKey: true
})
} else {
viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, value)
}
}
const errors = { ...this.data.errors }
delete errors[`${groupKey}__${rowIndex}__${childKey}`]
this.applyEngineView(viewState, {
errors,
structureChanged: false,
changedGroupKey: groupKey
})
},
/** 周历圆点:标记本周已填日期(templateType=3) */
updateWeeklyDots(weeklyList = []) {
const timeBean = { ...this.data.timeBean }
timeBean.weekDayList = (timeBean.weekDayList || []).map(item => ({
...item,
hasDailyValue: weeklyList.includes(item.date)
}))
Object.assign(this.data, { timeBean, weeklyList })
this.setData({
timeBean,
weeklyList
})
this.syncReportSubmittedState({ reportStatus: this.data.reportStatus })
},
/** 拉取 weekly.list 更新周历标记 */
async refreshWeeklyList() {
const { timeBean } = this.data
const ctx = this.userContext || this.getRequestContext()
if (!ctx.merchantId || !timeBean?.reportStartDate) return
try {
const res = await negotiationApi.fetchWeeklyList({
merchantId: ctx.merchantId,
staffUuid: ctx.staffUuid,
sceneType: ctx.sceneType,
reportStartDate: timeBean.reportStartDate,
reportEndDate: timeBean.reportEndDate
})
if (res.code === 0) {
this.updateWeeklyDots(res.data || [])
} else {
wx.$util?.showToast?.(res.message || '获取周历失败')
}
} catch (error) {
console.error(error)
}
},
/** 从登录态解析 merchantId / staffUuid */
getRequestContext() {
const userInfo = wx.$util?.getUserInfo?.() || {}
return negotiationApi.normalizeUserInfo(userInfo)
},
/** 解析 engine / load 快照,供 requestContext 透出场景码(AppData 可见) */
resolvePageContextForRequest() {
return (
this.engine?.getPageContext?.() ||
this._pageContextSnapshot ||
this.pageContext ||
{}
)
},
/** 透传给 select/multipleSelect 的 optionsKey 请求上下文(含 sceneType) */
buildFormRequestContext() {
const ctx = this.userContext || this.getRequestContext()
const userInfo = wx.$util?.getUserInfo?.() || {}
return buildDailyReportRequestContext({
userContext: ctx,
userInfo,
reportDate: this.data.reportDate,
reportType: 'negotiation',
engineCtx: this.resolvePageContextForRequest(),
sceneTypeDefault: null
})
},
/** 主加载:Loader → engine.init → applyEngineView */
async loadFormData() {
const { reportDate } = this.data
if (!reportDate) return
const seq = ++this.loadSeq
const userContext = this.getRequestContext()
this.userContext = userContext
this.setData({ loading: true, loadError: '' })
try {
const loadRes = await loadNegotiationDailyForm({
userContext,
reportDate,
reportTemplateId: this.reportTemplateId
})
if (this.isStaleLoad(seq)) return
if (!isApiSuccess(loadRes.code) || !loadRes.data) {
const message = loadRes.message || '加载失败'
this.setData({ loadError: message })
return wx.$util.showToast(message)
}
const { pageContext, schema, detail, initialValues } = loadRes.data
this._pageContextSnapshot = pageContext || null
this.pageContext = pageContext || null
this.reportTemplateId = detail.reportTemplateId || this.reportTemplateId
this.dailyReportRecordId = detail.dailyReportRecordId || null
this.syncReportSubmittedState(detail)
const engine = this.ensureEngine(this.getEngineKey(reportDate))
const finalViewState = engine.init(schema, {
...pageContext,
initialValues: initialValues || {}
})
if (this.isStaleLoad(seq)) return
this.setData({
merchantName:
pageContext.shopMerchantName || pageContext.merchantName || '',
loadError: ''
})
this.applyEngineView(finalViewState, { structureChanged: true })
this.scheduleMetadataCacheRevalidate(
negotiationApi,
{
userContext,
baseSceneCode: pageContext.baseSceneCode,
reportTemplateId: this.reportTemplateId
},
seq
)
if (this.data.isDateWithinEditableWindow) {
this.refreshTodayPlanCustomerCount()
} else {
this.setData({ todayPlanCustomerCount: 0 })
}
} catch (error) {
if (this.isStaleLoad(seq)) return
console.error(error)
this.setData({ loadError: '加载失败' })
wx.$util.showToast('加载失败')
} finally {
if (this.isStaleLoad(seq)) return
this.setData({ loading: false })
}
},
/** 顶层字段变更 → engine.setFieldValue */
onFieldChange(e) {
if (this.data.formDisabled) return
const { key, value } = e.detail || {}
if (!this.engine || !key) return
const viewState = this.engine.setFieldValue(key, value)
const errors = { ...this.data.errors }
delete errors[key]
this.applyEngineView(viewState, { errors, structureChanged: false })
},
/** 提交:只执行模板声明的通用校验,通过后调用 dynamic.save。 */
async submit() {
if (this._submitting) {
return wx.$util.showToast('正在提交中,请稍候')
}
if (!this.engine) return
if (!this.data.isDateWithinEditableWindow) {
return wx.$util.showToast('已超过提交时效')
}
if (this.data.isReportSubmitted && !this.data.isEditReport) {
return wx.$util.showToast('日报已提交,不可再编辑')
}
wx.$util.showLoading()
try {
if (typeof this.engine.prepareForSubmit === 'function') {
this.engine.prepareForSubmit()
}
const validation = this.engine.validate()
if (!validation.ok) {
this.logSubmitValidationFailures({
errors: validation.errors,
errorMap: validation.errorMap
})
const firstErr = validation.errors[0]
this.applyEngineView(this.engine.getViewState(), {
errors: validation.errorMap,
structureChanged: false,
groupActiveIndex: this.buildGroupActiveIndexFromErrors(validation.errorMap)
})
return wx.$util.showToast(
firstErr?.message || firstErr?.label || '必填不能为空'
)
}
this.applyEngineView(this.engine.getViewState(), { errors: {}, structureChanged: false })
if (!this.reportTemplateId) {
return wx.$util.showToast('缺少报表模板,请联系运营配置')
}
this._submitting = true
const res = await negotiationApi.submitForm({
engine: this.engine,
reportTemplateId: this.reportTemplateId,
dailyReportRecordId: this.dailyReportRecordId,
reportDate: this.data.reportDate
})
if (!isApiSuccess(res.code)) {
return this.showSubmitFailureToast(res, null)
}
if (res.data?.dailyReportRecordId) {
this.dailyReportRecordId = res.data.dailyReportRecordId
}
wx.$util.showToast('提交成功')
await this.refreshAfterSubmit()
} catch (error) {
console.error('[negotiationDetail] submit', error)
this.showSubmitFailureToast(null, error, '提交失败,请重试')
} finally {
this._submitting = false
wx.$util.hideLoading()
}
},
/** 提交成功后轻量重拉详情并刷新周历 */
async refreshAfterSubmit() {
const seq = ++this.refreshSeq
const { reportDate } = this.data
const userContext = this.userContext || this.getRequestContext()
const loadRes = await loadNegotiationDailyForm({
userContext,
reportDate,
reportTemplateId: this.reportTemplateId
})
if (this.isStaleRefresh(seq)) return
if (!isApiSuccess(loadRes.code) || !loadRes.data) return
const { schema, detail, initialValues, pageContext } = loadRes.data
this._pageContextSnapshot = pageContext || null
this.pageContext = pageContext || null
this.dailyReportRecordId = detail.dailyReportRecordId || this.dailyReportRecordId
this.syncReportSubmittedState(detail)
this.resetEditReport()
if (!this.engine) return
const viewState = this.reinitEngineFromLoadData({
pageContext,
schema,
initialValues
})
if (this.isStaleRefresh(seq)) return
await this.refreshWeeklyList()
this.applyEngineView(viewState, { structureChanged: true })
},
/** 上一周:刷新 weekly + loadFormData */
lastWeek() {
const selectWeek = this.data.selectWeek - 1
let timeBean = timeUtil.getWeekDayList(selectWeek)
if (selectWeek !== 0) {
timeBean.selectDay = 0
}
this.applyCalendarState(selectWeek, timeBean)
this.refreshWeeklyList()
this.loadFormData()
},
/** 下一周:刷新 weekly + loadFormData */
nextWeek() {
const selectWeek = this.data.selectWeek + 1
const timeBean = timeUtil.getWeekDayList(selectWeek)
timeBean.selectDay = 0
this.applyCalendarState(selectWeek, timeBean)
this.refreshWeeklyList()
this.loadFormData()
},
/** 周历点击选日:仅 loadFormData,不重复 refreshWeeklyList */
dayClick(e) {
this.applyDaySelect(e.detail)
this.loadFormData()
},
/** 打开 VIN OCR 页并注册精确行回填;识别结果不触发接口校验。 */
openVinOcrForField({ childKey, groupKey, rowIndex } = {}) {
if (this.data.formDisabled || !childKey) return
const page = this
const resolved = resolveVinFieldContext(
{ childKey, groupKey, rowIndex },
this.data.groupActiveIndex || {}
)
this._vinOcrCtx = resolved
vinOcrBridge.openVinOcr({
childKey: resolved.childKey,
groupKey: resolved.groupKey,
rowIndex: resolved.rowIndex,
onResult(vin) {
page._vinOcrCtx = null
page.queueVinOcrApply({ ...resolved, vin })
}
})
},
/** 延迟到 nextTick 消费 OCR 结果,避免子页返回时 engine 未就绪 */
queueVinOcrApply(payload = {}) {
this._pendingVinApply = payload
const page = this
const flush = () => page.flushPendingVinApply()
if (typeof wx !== 'undefined' && typeof wx.nextTick === 'function') {
wx.nextTick(flush)
} else {
flush()
}
},
/** onShow 时执行 pending VIN 写入 engine */
flushPendingVinApply() {
const pending = this._pendingVinApply
if (!pending) return
this._pendingVinApply = null
this.applyVinOcrResult(pending)
},
/** 将 OCR 识别的 VIN 原样写入顶层或 subform,提交时由模板规则校验。 */
applyVinOcrResult({ childKey, groupKey, rowIndex, vin } = {}) {
if (!this.engine || !childKey || vin == null || vin === '') return
const resolved = resolveVinFieldContext(
{ childKey, groupKey, rowIndex },
this.data.groupActiveIndex || {}
)
let viewState
const errors = { ...this.data.errors }
if (resolved.isGroupField) {
viewState = this.engine.mutateSubform(
resolved.groupKey,
resolved.rowIndex,
resolved.childKey,
vin
)
delete errors[`${resolved.groupKey}__${resolved.rowIndex}__${resolved.childKey}`]
} else {
viewState = this.engine.setFieldValue(resolved.childKey, vin)
delete errors[resolved.childKey]
}
const extra = { errors, structureChanged: false }
if (resolved.isGroupField && resolved.groupKey) {
extra.changedGroupKey = resolved.groupKey
}
this.applyEngineView(viewState, extra)
},
/** 提交校验未通过时输出失败项(控制台),供联调定位 */
logSubmitValidationFailures({ errors = [], errorMap = {} } = {}) {
const items = (errors || []).map(err => ({
key: err.key,
label: err.label,
message: err.message,
groupKey: err.groupKey,
rowIndex: err.rowIndex
}))
if (items.length) {
console.warn('[negotiationDetail] submit validation failed', { items, errorMap })
}
},
/** 打开品牌选择页:四级车型走真实 merchant.info + scrm 接口(与 Loader brand mock 无关) */
openCarBrandForField({ childKey, groupKey, rowIndex } = {}) {
if (this.data.formDisabled || !childKey) return
let currentValue
if (this.engine) {
const viewState = this.engine.getViewState()
if (groupKey != null && rowIndex != null) {
const row = viewState.values?.[groupKey]?.[rowIndex]
const rowFields = viewState.groupRowsCache?.[groupKey]?.[rowIndex]
const rowField = rowFields?.find(field => field.key === childKey)
currentValue = resolveCarBrandValueForValidation(rowField, childKey, row?.[childKey])
} else {
currentValue = viewState.values?.[childKey]
}
}
const page = this
const userInfo = wx.$util?.getUserInfo?.() || {}
const merchantId = carBrandPickerBridge.resolveMerchantId(
userInfo.shopMerchantId ||
this.userContext?.merchantId ||
this.pageContext?.merchantId ||
this.engine?.getPageContext?.()?.merchantId ||
this.buildFormRequestContext()?.merchantId
)
carBrandPickerBridge.openCarBrandPick({
childKey,
groupKey,
rowIndex,
merchantId,
useMerchantBrandMock: false,
currentValue,
onResult(carInfo) {
page.applyCarBrandResult({ childKey, groupKey, rowIndex, carInfo })
}
})
},
/** 品牌选择回调:写入 carBrand 对象到顶层或 subform(App 双 key) */
applyCarBrandResult({ childKey, groupKey, rowIndex, carInfo } = {}) {
if (!this.engine || !childKey || !carInfo) return
let viewState
const errors = { ...this.data.errors }
const extra = { errors, structureChanged: false }
if (groupKey != null && rowIndex != null) {
viewState = this.engine.mutateSubform(
groupKey,
rowIndex,
childKey,
{ metaValue: carInfo },
{ appDualKey: true }
)
delete errors[`${groupKey}__${rowIndex}__${childKey}`]
extra.changedGroupKey = groupKey
} else {
viewState = this.engine.setFieldValue(childKey, carInfo)
delete errors[childKey]
}
this.applyEngineView(viewState, extra)
},
/** 全局 reWrite 桥:standNo 只回填 VIN 或交给 vinOcrBridge 处理。 */
reWrite(type, data) {
if (vinOcrBridge.handleReWrite(type, data)) {
this._vinOcrCtx = null
return
}
const ctx = this._vinOcrCtx
if (!ctx || type !== 'standNo' || data == null || data === '') {
return
}
const vin = vinOcrBridge.normalizeVin(data)
if (!vin) return
this._vinOcrCtx = null
const resolved = resolveVinFieldContext(
ctx,
this.data.groupActiveIndex || {}
)
this.queueVinOcrApply({ ...resolved, vin })
},
/** 初始化今日计划入口条 CDN 切图(class.png、arrow_right.png) */
initTodayPlanBannerIcons() {
this.setData({
todayPlanClassIconUrl: buildPackageDynamicFormIconUrl(
TODAY_PLAN_BANNER_CLASS_ICON
),
todayPlanArrowRightIconUrl: buildPackageDynamicFormIconUrl(
TODAY_PLAN_BANNER_ARROW_RIGHT_ICON
)
})
},
/**
* 拉取待接待客户数(入口条展示)
* 由 loadFormData 在可编辑窗口内调用,inviteDate 为周历选中日
*/
async refreshTodayPlanCustomerCount() {
const ctx = this.userContext || this.getRequestContext()
const inviteDate = this.data.reportDate
if (!ctx.merchantId || !ctx.staffUuid || !inviteDate) {
this.setData({ todayPlanCustomerCount: 0 })
return
}
try {
const res = await negotiationApi.fetchTodayPlanStoreCount({
merchantId: ctx.merchantId,
advanceUserId: ctx.staffUuid,
inviteDate
})
if (res.code === 0 && Number.isFinite(res.data)) {
this.setData({ todayPlanCustomerCount: res.data })
}
} catch (error) {
console.error(error)
}
},
/** 打开计划到店客户弹层(默认可编辑日内、默认日期为周历选中日) */
openTodayPlanCustomerPopup() {
if (this.data.formDisabled || !this.data.isDateWithinEditableWindow) return
const ctx = this.userContext || this.getRequestContext()
this.setData({
showTodayPlanPopup: true,
todayPlanMerchantId: ctx.merchantId || '',
todayPlanAdvanceUserId: ctx.staffUuid || '',
todayPlanStaffName: ctx.staffName || ''
})
},
/** 关闭今日计划客户弹层 */
closeTodayPlanCustomerPopup() {
this.setData({ showTodayPlanPopup: false })
},
/**
* 解析导入失败提示用的子表单展示名
* @param {string} [groupKey] F3-1 ~ F3-4
* @param {string} [groupLabel] 服务层带回的 label
* @returns {string}
*/
resolveCustomerImportGroupLabel(groupKey, groupLabel) {
const fromPage = groupKey ? this.findGroupByKey(groupKey)?.label : ''
return fromPage || groupLabel || groupKey || '当前子表单'
},
/**
* 添加失败:任一可见 subform 超 20 行
* @param {string} [groupKey] 触发上限的 F3 key
* @param {string} [groupLabel] 服务层带回的 subform label
*/
showCustomerImportMaxLengthError(groupKey, groupLabel) {
const name = this.resolveCustomerImportGroupLabel(groupKey, groupLabel)
wx.showModal({
title: '添加失败',
content: `${name}一次最多添加20个客户`,
showCancel: false,
confirmText: '知道了'
})
},
/**
* 弹层确认:批量导入客户到可见 F3 subform
* @param {WechatMiniprogram.CustomEvent} e detail.customers 选中客户列表
* 成功无 toast;超 20 行时 showCustomerImportMaxLengthError
*/
onTodayPlanCustomersConfirm(e) {
const customers = e?.detail?.customers || []
if (!customers.length || !this.engine) {
this.closeTodayPlanCustomerPopup()
return
}
const result = applyCustomersToEngine(this.engine, customers)
if (!result.ok) {
this.showCustomerImportMaxLengthError(result.groupKey, result.groupLabel)
return
}
const groupActiveIndex = { ...(this.data.groupActiveIndex || {}) }
const rowTotalMap = {}
;(result.changedGroupKeys || []).forEach(groupKey => {
const cacheRows = result.viewState?.groupRowsCache?.[groupKey] || []
const total = cacheRows.length
rowTotalMap[groupKey] = total
if (total > 0) {
groupActiveIndex[groupKey] = this.clampGroupActiveIndex(
groupKey,
total - 1,
total
)
}
})
this.applyEngineView(result.viewState, {
structureChanged: false,
groupActiveIndex
})
this.closeTodayPlanCustomerPopup()
},
/** 页面卸载:清理 VIN OCR / 车型选择 bridge pending */
onUnload() {
this._vinOcrCtx = null
this._pendingVinApply = null
vinOcrBridge.clearPending()
carBrandPickerBridge.clearPending()
},
/** 返回上一页 */
jump() {
wx.$router.back()
}
})