GLForm.js
15 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
import { IMG_URL } from '../../../utils/imageBase.js'
// packageEquity/pages/carEquity/components/GLForm/GLForm.js
const { loadAreaList } = require('~/utils/areaList')
Component({
externalClasses: ["custom-class"],
options: {
multipleSlots: true, // 在组件定义时的选项中启用多 slot 支持
styleIsolation: "shared", // 自定义覆盖vant样式
},
/**
* 组件的属性列表
*/
properties: {
formData: {
type: Object,
value: () => {},
observer: function (n) {
this.setData({
formData: n,
});
// 当 formData 更新时,重新计算所有 picker 的索引
this.calculatePickerIndexes();
},
},
formDataList: {
type: Array,
value: () => [],
observer: function (n) {
// 当 formDataList 更新时,重新计算索引
if (n && n.length > 0 && this.data.formData) {
wx.nextTick(() => {
this.calculatePickerIndexes();
});
}
},
},
labelWidth: {
type: String,
value: "var(--fontSize200)",
},
// 页面存放表单对象的对象名,用于直接变更page的值
dataAttrName: {
type: String,
value: null,
},
disable: {
type: Boolean,
value: false,
},
glCellClass: {
type: String,
value: false,
},
// 背景色
background: {
type: String,
value: "#FFFFFF",
},
},
/**
* 组件的初始数据
*/
data: {
IMG_URL,
targetIdx: -1,
areaList: [],
currentRegionTarget: null, // 当前选择地区的字段配置
currentDate: "", // 当前日期,格式:YYYY-MM-DD
pickerIndexMap: {}, // 存储每个 picker 的选中索引
},
lifetimes: {
attached() {
// 获取当前日期(格式:YYYY-MM-DD)
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0");
const day = String(today.getDate()).padStart(2, "0");
const currentDate = `${year}-${month}-${day}`;
this.setData({
currentDate: currentDate,
});
// 初始化时计算 picker 索引
wx.nextTick(() => {
this.calculatePickerIndexes();
});
let thisPage = wx.$router.getPageInstance();
wx.$eventbus.on("set_car_info", (n) => {
let { targetIdx, dataAttrName, formDataList } = this.data;
let formData = null;
if (dataAttrName && dataAttrName.includes(".")) {
const pathArr = dataAttrName.split(".");
formData = thisPage?.data;
for (let key of pathArr) {
formData = formData?.[key];
if (!formData) break;
}
} else {
formData = thisPage?.data[dataAttrName] || null;
}
if (formData) {
let targetItem = null;
if (targetIdx != -1) {
targetItem = formDataList[targetIdx] || {};
} else {
const brandIndex = formDataList.findIndex(
(item) => item.type === "brand"
);
if (brandIndex !== -1) {
targetItem = formDataList[brandIndex];
}
}
if (targetItem) {
if (targetItem.handleChange) {
targetItem.handleChange(thisPage, dataAttrName, n);
}
if (!targetItem.noDefault) {
thisPage.setData({
[dataAttrName + "." + targetItem.labelName]:
n.vehicleBrandName +
"/" +
n.vehicleSeriesName +
"/" +
n.vehicleShapeName +
"/" +
n.vehicleSubBrandName,
});
}
}
formData = Object.assign(formData, n);
thisPage.setData({
[dataAttrName]: formData,
});
}
});
},
},
/**
* 组件的方法列表
*/
methods: {
/**
* 表单验证方法
* @param {Object} rules 验证规则,格式同 firstData.js 中的 formRule
* @returns {Object|null} 返回错误信息 {field, message, attr} 或 null
*/
validate(rules) {
const { formData } = this.data;
if (!rules || typeof rules !== "object") {
return null;
}
const fieldKeys = Object.keys(rules);
for (let i = 0; i < fieldKeys.length; i++) {
const field = fieldKeys[i];
const fieldRules = rules[field];
const value = formData[field];
if (!Array.isArray(fieldRules)) {
continue;
}
for (let j = 0; j < fieldRules.length; j++) {
const rule = fieldRules[j];
// 必填校验
if (rule.required && !value) {
// 特殊处理:对于地区ID字段,如果有对应的名称字段,则认为有效
if (
field === "registrationCityId" &&
formData.registrationCityName
) {
continue; // 跳过验证
}
if (field === "carCityId" && formData.carCityName) {
continue; // 跳过验证
}
if (
field === "registrationProvinceId" &&
formData.registrationProvinceName
) {
continue; // 跳过验证
}
if (field === "carProvinceId" && formData.carProvinceName) {
continue; // 跳过验证
}
return {
field,
message: rule.message,
attr: field,
};
}
// 自定义校验函数
if (rule.validator && typeof rule.validator === "function") {
const result = rule.validator(rule, value, formData);
if (result && result.message) {
return {
field,
attr: field,
...result,
};
}
}
}
}
return null;
},
getHeight(selector) {
return new Promise((resolve) => {
wx.$util.getViewInfo(
selector,
(res) => {
return resolve(res);
},
this
);
});
},
parentSetData(attr, value) {
let { dataAttrName } = this.data;
let thisPage = wx.$router.getPageInstance();
thisPage.setData({
[dataAttrName + "." + attr]: value,
});
},
handleInput(e) {
let value = e.detail;
let { attr, item } = e.target.dataset;
let { dataAttrName } = this.data;
// if (attr == 'price') {
// value = value >= 2000000 ? '2000000' : value
// // wx.$eventbus.emit('delete_goodsSelect')
// }
// console.log(item,'handleInput');
let thisPage = wx.$router.getPageInstance();
if (item.inputLimit && item.inputLimit.maxVal) {
value =
value >= item.inputLimit.maxVal ? item.inputLimit.maxVal : value;
}
if (item.inputLimit && item.inputLimit.minVal) {
value =
value <= item.inputLimit.minVal ? item.inputLimit.minVal : value;
}
// 处理数字类型输入,过滤掉所有非数字字符
if (item.inputLimit && item.inputLimit.type == "number") {
value = value.toString().replace(/[^\d]/g, "");
}
if (item.inputLimit && item.inputLimit.type == "digit") {
let [number, decimal] = value.toString().split(".");
if (decimal != undefined) {
decimal = decimal.substring(0, 2);
number += `.${decimal}`;
value = number;
}
}
const diffValue = value.toString();
const trimValue = value.toString().trim();
if (diffValue != trimValue) {
value = trimValue;
}
thisPage.setData({
[dataAttrName + "." + attr]: value,
});
this.triggerEvent("inputEvent", {
attr,
});
},
handleBlur(e) {
let value = e.detail;
let { attr } = e.target.dataset;
this.triggerEvent("inputBlur", {
attr,
});
},
// 计算所有 picker 的选中索引
calculatePickerIndexes() {
const { formData, formDataList } = this.data;
if (!formData || !formDataList) return;
const pickerIndexMap = {};
formDataList.forEach((item) => {
if (
item.type === "select" &&
item.optionList &&
item.optionId &&
item.name
) {
const currentValue = formData[item.name];
if (
currentValue !== null &&
currentValue !== undefined &&
currentValue !== ""
) {
const currentValueStr = String(currentValue);
const optionList = item.optionList;
const optionId = item.optionId;
for (let i = 0; i < optionList.length; i++) {
const option = optionList[i];
if (!option) continue;
let optionValue = null;
if (optionId === "value") {
optionValue = option.value;
} else if (optionId === "name") {
optionValue = option.name;
} else {
optionValue = option[optionId];
}
if (optionValue !== null && optionValue !== undefined) {
// 支持数字和字符串类型的比较
const optionValueStr = String(optionValue);
const currentValueNum = Number(currentValue);
const optionValueNum = Number(optionValue);
// 先尝试数字比较(适用于综合评价等数字类型字段)
if (
!isNaN(currentValueNum) &&
!isNaN(optionValueNum) &&
currentValueNum === optionValueNum
) {
pickerIndexMap[item.name] = i;
break;
}
// 再尝试字符串比较(适用于其他字符串类型字段)
if (optionValueStr === currentValueStr) {
pickerIndexMap[item.name] = i;
break;
}
}
}
}
}
});
this.setData({
pickerIndexMap: pickerIndexMap,
});
},
handlePickerChange(e) {
console.log(e, "handlePickerChange");
let idx = e.detail.value || 0;
let { target } = e.currentTarget.dataset;
let { dataAttrName } = this.data;
console.log(dataAttrName, "dataAttrName");
let thisPage = wx.$router.getPageInstance();
thisPage.setData({
[dataAttrName + "." + target.name]:
target.optionList[idx][target.optionId],
[dataAttrName + "." + target.labelName]:
target.optionList[idx][target.optionLabel],
});
// 更新后重新计算索引
this.calculatePickerIndexes();
console.log(thisPage);
this.triggerEvent("pickerChange", {
obj: target.optionList[idx],
});
},
handleTimeChange(e) {
let { value } = e.detail;
let { target } = e.currentTarget.dataset;
let { dataAttrName } = this.data;
let thisPage = wx.$router.getPageInstance();
thisPage.setData({
[dataAttrName + "." + target.name]: value,
});
// console.log(this.data.formData)
},
// 品牌车型
handleJumpBrand(e) {
const thisPage = wx.$router.getPageInstance();
const carTips = thisPage?.data?.carTips || "";
console.log("[GLForm handleJumpBrand] carTips:", carTips);
const url = carTips
? `packageEquity.carBrands?cartips=${encodeURIComponent(carTips)}`
: "packageEquity.carBrands";
console.log("[GLForm handleJumpBrand] url:", url);
wx.$router.go(url);
},
handleCellClick(e) {
let { target, idx } = e.currentTarget.dataset;
switch (target.type) {
case "brand":
this.setData({
targetIdx: idx,
});
this.handleJumpBrand();
break;
default:
break;
}
},
showAreaFun(e) {
const { showArea, areaList } = this.data
const target = e?.currentTarget?.dataset?.target
const applyShowArea = list => {
if (!showArea) {
wx.hideKeyboard()
}
this.setData({
showArea: !showArea,
areaList: list,
areaTitle: target?.label || '',
currentRegionTarget: target || this.data.currentRegionTarget
})
}
const needLoad = !areaList || !areaList.province_list
if (needLoad) {
loadAreaList()
.then(applyShowArea)
.catch(() => {
wx.$util?.showToast?.('省市区数据加载失败,请稍后重试')
})
return
}
applyShowArea(areaList)
},
bindRegionChange(e) {
console.log("bindRegionChange event:", e);
// 从保存的 currentRegionTarget 获取目标字段信息
const target = this.data.currentRegionTarget;
const { detail } = e;
// van-area 组件返回的数据格式: detail = { values: [{code, name}, ...] }
const values = detail?.values || [];
console.log("选择的地区:", values, "target:", target);
if (!target || values.length === 0) {
this.showAreaFun();
return;
}
const { dataAttrName } = this.data;
let thisPage = wx.$router.getPageInstance();
// 根据 columnsNum 判断是省市还是省市区
const columnsNum = parseInt(target.columnsNum) || 3;
let provinceName = "",
cityName = "",
provinceCode = "",
cityCode = "";
if (columnsNum === 2) {
// 只选择省市
provinceName = values[0]?.name || "";
cityName = values[1]?.name || "";
provinceCode = values[0]?.code || "";
cityCode = values[1]?.code || "";
} else {
// 选择省市区(取前两级)
provinceName = values[0]?.name || "";
cityName = values[1]?.name || "";
provinceCode = values[0]?.code || "";
cityCode = values[1]?.code || "";
}
const displayText = provinceName + " " + cityName;
// 更新页面数据
// 根据 target.name 判断是上牌城市还是车辆所在地
if (target.name === "registrationCityName") {
// 上牌城市
thisPage.setData({
[dataAttrName + ".registrationProvinceName"]: provinceName,
[dataAttrName + ".registrationProvinceId"]: provinceCode,
[dataAttrName + ".registrationCityName"]: displayText,
[dataAttrName + ".registrationCityId"]: cityCode,
});
} else if (target.name === "carCityName") {
// 车辆所在地
thisPage.setData({
[dataAttrName + ".carProvinceName"]: provinceName,
[dataAttrName + ".carProvinceId"]: provinceCode,
[dataAttrName + ".carCityName"]: displayText,
[dataAttrName + ".carCityId"]: cityCode,
});
}
// 触发自定义事件
this.triggerEvent("RegionChange", e);
// 关闭弹窗
this.showAreaFun();
},
navOcr(e) {
let { type } = e.currentTarget.dataset;
wx.$router.go(`ocrUsedCarModules?type=${type}`);
},
},
});