-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsingle-config.js
More file actions
1509 lines (1295 loc) · 57.5 KB
/
single-config.js
File metadata and controls
1509 lines (1295 loc) · 57.5 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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class ConfiguratorPage {
constructor() {
this.XANO_API_URL = "https://x2xj-hiw3-yjhd.t7.xano.io/api:0K4rr2yl";
this.currentConfig = {
model: null,
engine: null,
trim: null,
year: null,
color: null,
retail: null,
};
this.state = {
currentView: "exterior",
selectedColor: null,
selectedArea: null,
selectedDealer: null,
};
this.sliders = {
exterior: null,
interior: null,
};
this.init();
this.initializeSliders();
this.initializeEventListeners();
}
initializeSliders() {
// Initialize exterior carousel
const exteriorElement = document.querySelector(".exterior-carousel");
if (exteriorElement && exteriorElement.querySelector('.swiper-wrapper')) {
// Destroy existing instance if it exists
if (this.sliders.exterior) {
this.sliders.exterior.destroy(true, true);
}
this.sliders.exterior = new Swiper(exteriorElement, {
init: true,
enabled: true,
observer: true,
observeParents: true,
slidesPerView: 1,
navigation: {
enabled: true,
nextEl: '.exterior-carousel .swiper-button-next',
prevEl: '.exterior-carousel .swiper-button-prev',
},
});
exteriorElement.style.display = "block";
}
// Initialize interior carousel
const interiorElement = document.querySelector(".interior-carousel");
if (interiorElement && interiorElement.querySelector('.swiper-wrapper')) {
if (this.sliders.interior) {
this.sliders.interior.destroy(true, true);
}
this.sliders.interior = new Swiper(interiorElement, {
init: true,
enabled: true,
observer: true,
observeParents: true,
slidesPerView: 1,
navigation: {
enabled: true,
nextEl: '.interior-carousel .swiper-button-next',
prevEl: '.interior-carousel .swiper-button-prev',
},
});
interiorElement.style.display = "none";
}
}
initializeEventListeners() {
const viewToggles = document.querySelectorAll('[name="view"]');
viewToggles.forEach((toggle) => {
toggle.addEventListener("change", (e) => {
this.switchView(e.target.value);
});
});
const areaSelect = document.getElementById("area");
if (areaSelect) {
areaSelect.addEventListener("change", (e) => {
const selectedArea = e.target.value;
console.log("Area changed to:", selectedArea);
this.handleAreaChange(selectedArea);
});
}
this.initializePaymentToggle();
}
getBrandIdFromSlug(brandSlug) {
const brandMapping = {
'peugeot': 1,
'citroen': 2
};
return brandMapping[brandSlug];
}
async init() {
try {
const urlParams = new URLSearchParams(window.location.search);
const modelSlug = urlParams.get("model");
if (!modelSlug) {
throw new Error("Missing model parameter");
}
const model = await this.fetchModelBySlug(modelSlug);
this.currentConfig.model = model;
await this.initializeConfigurator();
if (this.currentConfig.model) {
await this.loadAreaOptions();
await this.loadConfigurationData();
await this.updateEngineOptions();
this.initializeInstallmentListeners();
this.initializePaymentToggle();
this.initializeSliders();
}
const loadingScreen = document.getElementById('loading-screen');
loadingScreen.classList.add('hidden');
setTimeout(() => {
loadingScreen.style.display = 'none';
}, 500); // Match with CSS transition duration
} catch (error) {
console.error("Initialization error:", error);
this.showError("無法載入配置器");
const loadingScreen = document.getElementById('loading-screen');
loadingScreen.classList.add('hidden');
setTimeout(() => {
loadingScreen.style.display = 'none';
}, 500);
}
}
async loadConfigurationData() {
try {
const response = await fetch(
`${this.XANO_API_URL}/configuration-details?model_id=${this.currentConfig.model.id}`
);
if (!response.ok) throw new Error("Failed to fetch configuration data");
this.configurationData = await response.json();
console.log("Loaded configuration data:", this.configurationData);
} catch (error) {
console.error("Error loading configuration data:", error);
throw error;
}
}
switchView(view) {
const exteriorElement = document.querySelector(".exterior-carousel");
const interiorElement = document.querySelector(".interior-carousel");
if (view === "exterior") {
if (exteriorElement) {
exteriorElement.style.display = "block";
this.sliders.exterior?.updateSlides();
}
if (interiorElement) {
interiorElement.style.display = "none";
}
} else {
if (exteriorElement) {
exteriorElement.style.display = "none";
}
if (interiorElement) {
interiorElement.style.display = "block";
this.sliders.interior?.updateSlides();
}
}
const radioInput = document.querySelector(`input[name="view"][value="${view}"]`);
if (radioInput) {
radioInput.checked = true;
}
this.state.currentView = view;
}
initializePaymentToggle() {
const paymentInputs = document.querySelectorAll('input[name="payment"]');
const paymentContents = document.querySelectorAll(".payment_content");
// 初始隱藏分期付款內容
paymentContents[1].style.display = "none";
paymentInputs.forEach((input) => {
input.addEventListener("change", function () {
paymentContents.forEach((content) => (content.style.display = "none"));
const selectedContent = document.querySelector(
`.payment_content.${this.value}`
);
if (selectedContent) selectedContent.style.display = "block";
});
});
}
initializeInstallmentListeners() {
const installmentPrice = document.getElementById("installment-price");
const installmentMonth = document.getElementById("installment-month");
// 監聽價格相關的輸入變化
const priceInputs = document.querySelectorAll(
'input[name="engine"], input[name="trim"], input[name="color"]'
);
priceInputs.forEach((input) => {
input.addEventListener("change", () => this.updateInstallmentOptions());
});
// 監聽分期選項的變化
if (installmentPrice) {
installmentPrice.addEventListener("change", () =>
this.calculateMonthlyPayment()
);
}
if (installmentMonth) {
installmentMonth.addEventListener("change", () =>
this.calculateMonthlyPayment()
);
}
this.updateInstallmentOptions();
}
updateInstallmentOptions() {
const modelPriceElement = document.getElementById("model-price");
if (!modelPriceElement) return;
// Get total price from the displayed price
const totalPrice = parseInt(
modelPriceElement.textContent.replace(/[^0-9]/g, "")
);
const installmentPrice = document.getElementById("installment-price");
if (!installmentPrice) return;
// Calculate down payment options (20% to 50% of total price in 5% increments)
let options = ['<option value="">請選擇自備款金額</option>'];
for (let percentage = 20; percentage <= 50; percentage += 5) {
const downPayment = Math.round(totalPrice * (percentage / 100));
options.push(`<option value="${downPayment}">${percentage}% - NT$${downPayment.toLocaleString()}</option>`);
}
installmentPrice.innerHTML = options.join("");
}
calculateMonthlyPayment() {
const installmentPrice = document.getElementById("installment-price");
const installmentMonth = document.getElementById("installment-month");
const monthlyPaymentElement = document.getElementById("monthly-payment");
const modelPriceElement = document.getElementById("model-price");
if (!installmentPrice || !installmentMonth || !monthlyPaymentElement || !modelPriceElement) return;
// Get total price and selected values
const totalPrice = parseInt(modelPriceElement.textContent.replace(/[^0-9]/g, ""));
const downPayment = parseInt(installmentPrice.value) || 0;
const selectedMonths = parseInt(installmentMonth.value) || 0;
// Calculate monthly payment only if both values are selected
if (downPayment > 0 && selectedMonths > 0) {
const remainingAmount = totalPrice - downPayment;
const monthlyPayment = Math.round(remainingAmount / selectedMonths);
monthlyPaymentElement.textContent = `NT$${monthlyPayment.toLocaleString()}`;
} else {
monthlyPaymentElement.textContent = "--";
}
}
// 重置顏色顯示的輔助方法
resetColorDisplay() {
// 重置顏色標籤和價格顯示
const colorLabel = document.querySelector(".color-label");
const colorPrice = document.querySelector(".color-price");
if (colorLabel) {
colorLabel.textContent = "請選擇車色";
}
if (colorPrice) {
colorPrice.textContent = "+NT$0";
}
// 重置 radio inputs
const colorInputs = document.querySelectorAll('input[name="color"]');
colorInputs.forEach(input => {
input.checked = false;
});
// 重置當前配置中的顏色
this.currentConfig.color = null;
// 重設為基本圖片
this.resetToBaseImages();
}
// 重置為基本圖片的方法
resetToBaseImages() {
const exteriorSlideContainer = document.querySelector(".exterior-carousel .swiper-wrapper");
if (exteriorSlideContainer && this.currentConfig.model?.base_image) {
exteriorSlideContainer.innerHTML = "";
// 如果 base_image 是陣列
const baseImages = Array.isArray(this.currentConfig.model.base_image) ?
this.currentConfig.model.base_image : [this.currentConfig.model.base_image];
baseImages.forEach(image => {
if (image?.url) {
const slide = document.createElement("div");
slide.className = "swiper-slide";
slide.innerHTML = `
<img src="${image.url}"
srcset="${image.url}"
alt="${this.currentConfig.model?.name || ''}"
class="model-image">
`;
exteriorSlideContainer.appendChild(slide);
}
});
if (this.sliders.exterior) {
this.sliders.exterior.update();
}
}
}
// Add this method to handle scrolling to the carousel
scrollToCarousel() {
// Check if it's mobile view (you can adjust the width as needed)
if (window.innerWidth <= 767) {
const carousel = document.querySelector('.exterior-carousel');
if (carousel) {
// Add a small delay to ensure the DOM is updated
setTimeout(() => {
// Get the navbar height
const navbar = document.querySelector('.nav_wrap');
const navbarHeight = navbar ? navbar.offsetHeight : 0;
// Calculate the scroll position with offset
const carouselPosition = carousel.getBoundingClientRect().top + window.pageYOffset;
const scrollPosition = carouselPosition - navbarHeight - 20; // 20px extra padding
// Smooth scroll to position
window.scrollTo({
top: scrollPosition,
behavior: 'smooth'
});
}, 100);
}
}
}
async fetchModelBySlug(slug) {
try {
console.log(`Fetching model data for slug: ${slug}`);
const response = await fetch(
`${this.XANO_API_URL}/models/by-brand-slug?slug=${slug}`
);
if (!response.ok) {
throw new Error("Failed to fetch model data");
}
const data = await response.json();
console.log("Model API response:", data);
// 如果 API 返回的是陣列,篩選符合的車型
if (Array.isArray(data)) {
const model = data.find((m) => m.slug === slug);
if (!model) {
throw new Error(`Model with slug "${slug}" not found`);
}
console.log("Found model:", model);
return model;
}
// 如果 API 返回的是單一物件,直接返回
if (data && data.slug === slug) {
console.log("Found model:", data);
return data;
}
throw new Error(`Model with slug "${slug}" not found`);
} catch (error) {
console.error("Error fetching model by slug:", error);
throw error;
}
}
// Modify updateModelInfo method
updateModelInfo(model) {
if (!model) {
console.error("Model data is missing or invalid");
return;
}
// Update model name
const modelName = document.getElementById("model-name");
if (modelName) {
modelName.textContent = model.name || "Unknown Model";
}
// Update exterior carousel with multiple base images
const exteriorSlideContainer = document.querySelector(".exterior-carousel .swiper-wrapper");
if (exteriorSlideContainer && model.base_images && Array.isArray(model.base_images)) {
exteriorSlideContainer.innerHTML = "";
model.base_images.forEach(image => {
if (image?.url) {
const slide = document.createElement("div");
slide.className = "swiper-slide";
slide.innerHTML = `
<img src="${image.url}"
srcset="${image.url}"
alt="${model.name || 'Model Image'}"
class="model-image">
`;
exteriorSlideContainer.appendChild(slide);
}
});
}
// Update model price
const modelPrice = document.getElementById("model-price");
if (modelPrice) {
const formattedPrice = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "TWD",
}).format(model.price || 0);
modelPrice.textContent = formattedPrice;
}
}
updateInteriorImages(trimData) {
const interiorSlideContainer = document.querySelector(".interior-carousel .swiper-wrapper");
if (!interiorSlideContainer || !trimData.interior_image) return;
interiorSlideContainer.innerHTML = "";
trimData.interior_image.forEach(image => {
if (image?.url) {
const slide = document.createElement("div");
slide.className = "swiper-slide";
slide.innerHTML = `
<img src="${image.url}"
srcset="${image.url}"
alt="${this.currentConfig.model?.name || ''} Interior">
`;
interiorSlideContainer.appendChild(slide);
}
});
// Reinitialize interior slider
if (this.sliders.interior) {
this.sliders.interior.destroy();
this.sliders.interior = new Swiper(".interior-carousel", {
slidesPerView: 1,
observer: true,
observeParents: true,
enabled: true,
navigation: {
nextEl: '.interior-carousel .swiper-button-next',
prevEl: '.interior-carousel .swiper-button-prev',
},
});
}
}
updatePriceDisplays() {
const basePrice = this.currentConfig.model?.price || 0;
const engineAdjustment = parseFloat(
document.querySelector('input[name="engine"]:checked')?.dataset.price || 0
);
const trimAdjustment = parseFloat(
document.querySelector('input[name="trim"]:checked')?.dataset.price || 0
);
const colorAdjustment = parseFloat(
document.querySelector('input[name="color"]:checked')?.dataset.price || 0
);
// Add accessories price adjustments
const accessoryAdjustments = Array.from(
document.querySelectorAll('input[name="additional"]:checked')
).reduce((total, accessory) => {
return total + (parseFloat(accessory.dataset.price) || 0);
}, 0);
// 計算總價格
const totalPrice =
basePrice +
engineAdjustment +
trimAdjustment +
colorAdjustment +
accessoryAdjustments;
// 更新所有相关的价格显示元素
const priceElements = {
modelPrice: document.getElementById("model-price"),
cashPrice: document.getElementById("cash-price"),
};
const formattedPrice = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "TWD",
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(totalPrice);
// 價格顯示
Object.values(priceElements).forEach((element) => {
if (element) {
element.textContent = formattedPrice;
}
});
this.updateInstallmentOptions();
this.calculateMonthlyPayment();
}
async initializeConfigurator() {
try {
if (!this.currentConfig.model) {
throw new Error("Missing model information");
}
this.updateModelInfo(this.currentConfig.model);
} catch (error) {
console.error("Error initializing configurator:", error);
throw error;
}
}
showError(message) {
const errorElement = document.getElementById("error-message");
if (errorElement) {
errorElement.textContent = message;
errorElement.style.display = "block";
}
console.error(message);
}
async loadAreaOptions() {
try {
// Get brand ID from the current URL path
const pathSegments = window.location.pathname.split('/');
const brandSlug = pathSegments[1];
const currentBrandId = this.getBrandIdFromSlug(brandSlug);
console.log("Current Brand ID:", currentBrandId);
// Fetch dealers with brand filter
const response = await fetch(`${this.XANO_API_URL}/dealers?brand_id=${currentBrandId}`);
if (!response.ok) throw new Error("Failed to fetch dealer data");
const dealersData = await response.json();
console.log("Dealers Data:", dealersData);
// Filter active dealers
const currentBrandDealers = dealersData.filter(dealer => dealer.is_active);
console.log("Filtered Dealers:", currentBrandDealers);
// Create area map
const areaMap = new Map();
currentBrandDealers.forEach(dealer => {
if (dealer.area) {
areaMap.set(dealer.area, true);
}
});
const uniqueAreas = Array.from(areaMap.keys());
console.log("Unique Areas:", uniqueAreas);
const areaSelect = document.getElementById("area");
if (!areaSelect) return;
areaSelect.innerHTML = `
<option value="">請選擇鄰近縣市</option>
${uniqueAreas.map(area => `<option value="${area}">${area}</option>`).join("")}
`;
this.dealersData = currentBrandDealers;
const navDealerResult = document.querySelector(".nav_dealer_result");
if (navDealerResult) {
navDealerResult.style.display = "none";
}
} catch (error) {
console.error("Error loading areas:", error);
}
}
async handleAreaChange(selectedArea) {
const dealerContainer = document.querySelector(".dealer-options");
dealerContainer.innerHTML = "";
if (!selectedArea) {
dealerContainer.style.display = "none";
return;
}
const dealersInArea = this.dealersData.filter(
dealer => dealer.area === selectedArea
);
dealerContainer.style.display = "block";
dealersInArea.forEach((dealer, index) => {
const dealerOption = document.createElement("label");
dealerOption.className = "form_option_wrap w-radio";
dealerOption.innerHTML = `
<input type="radio"
name="dealer"
id="dealer-${dealer.id}"
data-name="dealer"
required
class="w-form-formradioinput hide w-radio-input"
value="${dealer.name}"
data-address="${dealer.address || ''}"
data-phone="${dealer.phone || ''}"
${index === 0 ? "checked" : ""}>
<div class="form_radio_card">
<div class="radio_mark">
<div class="radio_dot"></div>
</div>
<div class="option_content">
<div class="u-weight-bold">${dealer.name || ''}</div>
<div>${dealer.address || ''}</div>
</div>
</div>
<span class="hide w-form-label" for="dealer-${dealer.id}">Radio</span>
`;
dealerContainer.appendChild(dealerOption);
const input = dealerOption.querySelector("input");
if (input) {
input.addEventListener("change", () => {
if (input.checked) {
this.currentConfig.retail = dealer.id;
const navDealerResult = document.querySelector(".nav_dealer_result");
if (navDealerResult) {
navDealerResult.style.display = "block";
const navDealerName = navDealerResult.querySelector("div:last-child");
if (navDealerName) {
navDealerName.textContent = dealer.name || '';
}
}
}
});
}
});
// After creating the dealer options, trigger the change event on the first dealer to display it by default
const firstDealerInput = dealerContainer.querySelector('input[name="dealer"]');
if (firstDealerInput) {
firstDealerInput.dispatchEvent(new Event('change'));
}
}
// Add this method to the ConfiguratorPage class
updateSummary() {
// Update engine summary
const selectedEngine = document.querySelector(
'input[name="engine"]:checked'
);
const summaryEngine = document.getElementById("summary-engine");
const summaryEnginePrice = document.getElementById("summary-engine-price");
if (selectedEngine && summaryEngine && summaryEnginePrice) {
const engineLabel = selectedEngine
.closest(".form_option_wrap")
.querySelector(".u-weight-bold").textContent;
summaryEngine.textContent = engineLabel;
const enginePrice = parseFloat(selectedEngine.dataset.price) || 0;
summaryEnginePrice.textContent =
enginePrice > 0 ? `+NT$${enginePrice.toLocaleString()}` : "包含";
}
// Update trim summary
const selectedTrim = document.querySelector('input[name="trim"]:checked');
const summaryTrim = document.getElementById("summary-trim");
const summaryTrimPrice = document.getElementById("summary-trim-price");
if (selectedTrim && summaryTrim && summaryTrimPrice) {
const trimLabel = selectedTrim
.closest(".form_option_wrap")
.querySelector(".u-weight-bold").textContent;
summaryTrim.textContent = trimLabel;
const modelPrice = this.currentConfig.model?.price || 0;
const trimPrice = parseFloat(selectedTrim.dataset.price) || 0;
const totalPrice = modelPrice + trimPrice;
summaryTrimPrice.textContent = `NT$${totalPrice.toLocaleString()}`;
}
// Update year summary
const selectedYear = document.querySelector('input[name="year"]:checked');
const summaryYear = document.getElementById("summary-year");
if (selectedYear && summaryYear) {
summaryYear.textContent = `${selectedYear.value}年式`;
}
// Update color summary
const selectedColor = document.querySelector('input[name="color"]:checked');
const summaryColor = document.getElementById("summary-color");
const summaryColorPrice = document.getElementById("summary-color-price");
if (selectedColor && summaryColor && summaryColorPrice) {
const colorLabel = document.querySelector(".color-label").textContent;
summaryColor.textContent = colorLabel;
const colorPrice = parseFloat(selectedColor.dataset.price) || 0;
summaryColorPrice.textContent =
colorPrice > 0 ? `+NT$${colorPrice.toLocaleString()}` : "包含";
}
// Update accessories summary
const selectedAccessories = document.querySelectorAll(
'input[name="additional"]:checked'
);
const summaryGroup = document.querySelector(".summary_group");
const oldAccessorySummaries = document.querySelectorAll(
".summary_row.accessory"
);
oldAccessorySummaries.forEach((row) => row.remove());
selectedAccessories.forEach((accessory) => {
const accessoryRow = document.createElement("div");
accessoryRow.className = "summary_row accessory";
const priceAdjustment = parseFloat(accessory.dataset.price) || 0;
accessoryRow.innerHTML = `
<div>${accessory
.closest(".form_option_wrap")
.querySelector(".u-weight-bold").textContent
}</div>
<div>${priceAdjustment > 0
? `+NT$${priceAdjustment.toLocaleString()}`
: "包含"
}</div>
`;
const specLink = summaryGroup
.querySelector("#summary-spec-link")
?.closest(".summary_row");
if (specLink) {
summaryGroup.insertBefore(accessoryRow, specLink);
} else {
summaryGroup.appendChild(accessoryRow);
}
});
// Find the configuration details based on selected engine and trim and year
const currentConfig = this.configurationData.find(config =>
config._engines.some(engine => engine.id === parseInt(this.currentConfig.engine)) &&
config._trims.some(trim => trim.id === parseInt(this.currentConfig.trim)) &&
config.year === this.currentConfig.year
);
// Get the brand slug from the URL
const pathSegments = window.location.pathname.split('/');
const brandSlug = pathSegments[1];
// Remove existing spec link
const existingSpecLink = document.getElementById("summary-spec-link")?.closest(".summary_row");
if (existingSpecLink) {
existingSpecLink.remove();
}
// Construct the spec link if currentConfig and brandSlug are available
if (currentConfig && brandSlug) {
const specLinkRow = document.createElement("div");
specLinkRow.className = "summary_row";
// Create the dynamic URL
const specLinkURL = `/${brandSlug}/spec?id=${currentConfig.id}`;
specLinkRow.innerHTML = `
<a href="${specLinkURL}"
target="_blank"
class="text_link_secondary w-inline-block"
id="summary-spec-link">
<div>檢視詳細規格表ⓘ</div>
</a>
`;
summaryGroup.appendChild(specLinkRow);
// Store the specLinkURL in currentConfig
this.currentConfig.specLinkURL = specLinkURL;
}
}
async updateEngineOptions() {
try {
if (!this.currentConfig.model || !this.configurationData) {
throw new Error("Model information or configuration data is missing");
}
const uniqueEngines = [];
const engineSet = new Set();
this.configurationData.forEach((item) => {
item._engines.forEach((engine) => {
if (!engineSet.has(engine.id)) {
engineSet.add(engine.id);
uniqueEngines.push(engine);
}
});
});
const engineContainer = document.querySelector(
".engine-selection .radio-group"
);
if (!engineContainer) return;
engineContainer.innerHTML = "";
uniqueEngines.forEach((engine, index) => {
const engineOption = document.createElement("label");
engineOption.className = "form_option_wrap w-radio";
engineOption.innerHTML = `
<input type="radio"
name="engine"
id="engine-${engine.id}"
data-name="engine"
data-price="${engine.price_adjustment || 0}"
required
class="w-form-formradioinput hide w-radio-input"
value="${engine.name}"
${index === 0 ? "checked" : ""}>
<div class="form_radio_card">
<div class="radio_mark">
<div class="radio_dot"></div>
</div>
<div class="option_content">
<div class="option_title_row">
<div class="u-weight-bold">${engine.name
}</div>
<div>${engine.price_adjustment > 0
? `+NT$${engine.price_adjustment}`
: "+NT$0"
}</div>
</div>
<span>${engine.power}</span>
</div>
</div>
<span class="hide w-form-label" for="engine-${engine.id
}">Engine${index + 1}</span>
`;
engineContainer.appendChild(engineOption);
const input = engineOption.querySelector("input");
if (input) {
input.addEventListener("change", async () => {
if (input.checked) {
this.currentConfig.engine = engine.id;
this.updatePriceDisplays();
await this.handleEngineChange(engine.id);
}
});
if (index === 0) {
input.dispatchEvent(new Event("change"));
}
}
});
} catch (error) {
console.error("Error updating engine options:", error);
}
}
async handleEngineChange(engineId) {
console.log("Engine changed:", engineId);
this.currentConfig.engine = engineId;
const availableTrims = await this.getTrimsForEngine(engineId);
this.currentConfig.trim = null;
this.renderTrimOptions(availableTrims);
this.updateSummary();
}
async getTrimsForEngine(engineId) {
try {
// Filter configuration data for the selected engine
const relevantConfigs = this.configurationData.filter((config) =>
config._engines.some((engine) => engine.id === parseInt(engineId))
);
const uniqueTrims = [];
const trimSet = new Set();
relevantConfigs.forEach((config) => {
config._trims.forEach((trim) => {
if (!trimSet.has(trim.id)) {
trimSet.add(trim.id);
uniqueTrims.push(trim);
}
});
});
return uniqueTrims;
} catch (error) {
console.error("Error getting trim options:", error);
return [];
}
}
renderTrimOptions(trims) {
console.log("Rendering trim options:", trims);
const summaryTrimPrice = document.getElementById("summary-trim-price");
const trimContainer = document.querySelector(
".trim-selection .radio-group"
);
if (!trimContainer) {
console.error("Trim container not found");
return;
}
trimContainer.innerHTML = "";
// Find the configuration data for each trim
trims.forEach((trim, index) => {
// Find the matching configuration for this trim
const trimConfig = this.configurationData.find((config) =>
config._trims.some((t) => t.id === trim.id)
);
const trimPrice = trimConfig ? trimConfig.trim_price : 0;
// 格式化價格,加入千分位
const formattedPrice = trimPrice > 0 ?
`+NT$${trimPrice.toLocaleString('en-US')}` :
"+NT$0";
const trimOption = document.createElement("label");
trimOption.className = "form_option_wrap w-radio";
trimOption.innerHTML = `
<input type="radio"
name="trim"
id="trim-${trim.id}"
data-name="trim"
data-price="${trimPrice}"
required
class="w-form-formradioinput hide w-radio-input"
value="${trim.name}"
${index === 0 ? "checked" : ""}>
<div class="form_radio_card">
<div class="radio_mark">
<div class="radio_dot"></div>
</div>
<div class="option_content">
<div class="option_title_row">
<div class="u-weight-bold">${trim.name}</div>
<div>${formattedPrice}</div>
</div>
<div>${trim.description || ""}</div>
<a href="${trim.pdf?.url || '#'}"
target="_blank"
class="text_link_secondary w-inline-block"
${!trim.pdf?.url ? 'style="display:none;"' : ''}>
<div>檢視詳細規格表ⓘ</div>
</a>
</div>
</div>
<span class="hide w-form-label" for="trim-${trim.id}">Trim${index + 1}</span>
`;
trimContainer.appendChild(trimOption);
const input = trimOption.querySelector("input");
input.addEventListener("change", () => {
if (input.checked) {
this.currentConfig.trim = trim.id;
if (summaryTrimPrice) {
const modelPrice = this.currentConfig.model?.price || 0;
const trimPrice = trim.price_adjustment || 0;
const totalPrice = modelPrice + trimPrice;
// 格式化總價,加入千分位
summaryTrimPrice.textContent = `NT$${totalPrice.toLocaleString('en-US')}`;
}
this.updatePriceDisplays();
this.handleTrimChange(trim.id);
this.updateSummary();
}
});
if (index === 0) {
input.dispatchEvent(new Event("change"));
}
});
}
async getColorsForTrim(engineId, trimId) {
try {