-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
714 lines (598 loc) · 26.3 KB
/
Copy pathscript.js
File metadata and controls
714 lines (598 loc) · 26.3 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
// ------------ Глобальные переменные ------------
let db; // База данных
let selectedDate = new Date();
// ------------ Функции календаря ------------
function updateDateDisplay() {
const currentDateElement = document.getElementById('current-date');
const currentDayElement = document.getElementById('current-day');
// Форматируем дату и день недели в одну строку
currentDateElement.textContent = selectedDate.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' });
currentDayElement.textContent = selectedDate.toLocaleDateString('ru-RU', { weekday: 'long' });
}
function renderCalendar(date) {
const calendarGrid = document.getElementById('calendar-grid');
const currentMonthElement = document.getElementById('current-month');
const year = date.getFullYear();
const month = date.getMonth();
// Отображаем текущий месяц и год
currentMonthElement.textContent = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' }).format(date);
const firstDayOfMonth = new Date(year, month, 1);
const daysInMonth = new Date(year, month + 1, 0).getDate();
const startingDay = firstDayOfMonth.getDay() === 0 ? 6 : firstDayOfMonth.getDay() - 1;
calendarGrid.innerHTML = '';
// Заполняем пустые ячейки до первого дня месяца
for (let i = 0; i < startingDay; i++) {
calendarGrid.appendChild(document.createElement('div'));
}
// Заполняем дни месяца
for (let day = 1; day <= daysInMonth; day++) {
const dayElement = document.createElement('div');
dayElement.textContent = day;
const dayDate = new Date(year, month, day);
dayElement.addEventListener('click', () => selectDate(dayDate));
// Выделяем выбранную дату
if (selectedDate.toDateString() === dayDate.toDateString()) {
dayElement.classList.add('selected');
}
calendarGrid.appendChild(dayElement);
}
}
function changeMonth(offset) {
selectedDate.setMonth(selectedDate.getMonth() + offset); // Изменяем месяц у выбранной даты
renderCalendar(selectedDate); // Перерисовываем календарь
}
function selectDate(date) {
selectedDate = date; // Обновляем выбранную дату
updateDateDisplay(); // Обновляем отображение даты
renderCalendar(selectedDate); // Перерисовываем календарь с новой датой
}
function changeDay(offset) {
selectedDate.setDate(selectedDate.getDate() + offset); // Изменяем выбранную дату
updateDateDisplay(); // Обновляем отображение даты
renderCalendar(selectedDate); // Перерисовываем календарь с новой датой
}
function toggleCalendar() {
const calendar = document.getElementById('calendar');
if (calendar.style.display === 'none') {
renderCalendar(selectedDate);
calendar.style.display = 'block';
} else {
calendar.style.display = 'none';
}
}
// Закрытие календаря при клике вне его области
document.addEventListener('click', function (event) {
const calendar = document.getElementById('calendar');
const datePicker = document.getElementById('date-picker');
if (!datePicker.contains(event.target)) {
calendar.style.display = 'none';
}
});
// Инициализация календаря при загрузке страницы
document.addEventListener('DOMContentLoaded', () => {
updateDateDisplay(); // Обновляем отображение даты
renderCalendar(selectedDate); // Рисуем календарь с текущей датой
});
// ------------ Общие функции интерфейса ------------
function toggleReadMore() {
const hiddenText = document.getElementById('hidden-text');
const readFullButton = document.getElementById('text1');
const hideButton = document.getElementById('hide-button');
const gradientOverlay = document.getElementById('gradient-overlay');
if (hiddenText.classList.contains('open')) {
hiddenText.classList.remove('open');
gradientOverlay.style.opacity = '1';
readFullButton.style.display = 'block';
hideButton.style.display = 'none';
} else {
hiddenText.classList.add('open');
gradientOverlay.style.opacity = '0';
readFullButton.style.display = 'none';
hideButton.style.display = 'block';
}
}
// ------------ Функции для модального окна ------------
document.getElementById('fixed-button').addEventListener('click', function () {
document.getElementById('modal').style.display = 'flex';
showStep(1);
});
function showStep(step) {
document.querySelectorAll('.step').forEach(function (stepElement) {
stepElement.style.display = 'none';
});
document.getElementById(`step${step}`).style.display = 'flex';
const backButton = document.querySelector('.back-button');
const closeButton = document.querySelector('.close-modal');
if (step === 1) {
backButton.style.display = 'none';
closeButton.style.display = 'block';
} else if (step === 5) {
backButton.style.display = 'none';
closeButton.style.display = 'none';
} else {
backButton.style.display = 'block';
closeButton.style.display = 'block';
}
updateConfirmButton();
if (step === 4) {
validateStep4();
setupStep4Listeners();
}
if (step === 3) {
updateDateDisplay();
renderCalendar(selectedDate);
}
}
function nextStep() {
const currentStep = document.querySelector('.step[style="display: flex;"]');
if (!currentStep) return;
const currentStepNumber = parseInt(currentStep.id.replace('step', ''));
const nextStepNumber = currentStepNumber + 1;
if (nextStepNumber === 5) {
saveAppointment();
} else {
showStep(nextStepNumber);
}
}
function prevStep() {
const currentStep = document.querySelector('.step[style="display: flex;"]');
if (currentStep) {
const currentStepNumber = parseInt(currentStep.id.replace('step', ''));
if (currentStepNumber > 1) {
showStep(currentStepNumber - 1);
}
}
updateConfirmButton();
}
function resetModal() {
document.getElementById('brand').selectedIndex = 0;
document.getElementById('model').innerHTML = '<option value="">Выберите модель</option>';
document.getElementById('model').disabled = true;
const servicesContainer = document.getElementById('services-container');
servicesContainer.innerHTML = '';
document.getElementById('total').textContent = '0₽';
selectedDate = new Date(); // Сбрасываем дату на текущую
updateDateDisplay(); // Обновляем отображение даты
renderCalendar(selectedDate); // Перерисовываем календарь
const timeSlotsContainer = document.querySelector('.time-slots');
timeSlotsContainer.innerHTML = '';
document.getElementById('clientName').value = '';
document.getElementById('clientPhone').value = '';
document.getElementById('clientCarNumber').value = '';
document.getElementById('next1').disabled = true;
document.getElementById('next2').disabled = true;
document.getElementById('next3').disabled = true;
document.getElementById('next4').disabled = true;
showStep(1);
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
resetModal();
}
// ------------ Работа с данными ------------
function populateBrands(brands) {
const brandSelect = document.getElementById('brand');
brandSelect.innerHTML = '<option value="">Выберите марку</option>';
if (!brands || !Array.isArray(brands)) {
console.error("Ошибка: brands не определен или не является массивом");
return;
}
brands.forEach(brand => {
const option = document.createElement('option');
option.value = brand.id;
option.textContent = brand.name;
brandSelect.appendChild(option);
});
}
function populateModels(models) {
const modelSelect = document.getElementById('model');
modelSelect.innerHTML = '<option value="">Выберите модель</option>';
modelSelect.disabled = true;
if (!Array.isArray(models)) {
console.error("Models не является массивом");
return;
}
if (models.length === 0) {
console.warn("Нет доступных моделей для выбранной марки");
return;
}
models.forEach(model => {
const option = document.createElement('option');
option.value = model.id;
option.textContent = model.name;
modelSelect.appendChild(option);
});
modelSelect.disabled = false;
}
function populateServices(services) {
const servicesContainer = document.getElementById('services-container');
servicesContainer.innerHTML = '';
if (!services || !Array.isArray(services)) {
console.error("Ошибка: services не определен или не является массивом");
return;
}
if (services.length === 0) {
console.warn("Нет доступных услуг для выбранной модели");
servicesContainer.innerHTML = '<p>Услуги для данного авто пока что добавляются, скоро все исправим)</p>';
return;
}
services.forEach(service => {
const serviceContainer = document.createElement('div');
serviceContainer.className = 'service-container';
serviceContainer.style.marginBottom = '10px';
serviceContainer.style.position = 'relative'; // Делаем контейнер относительным для позиционирования описания
const label = document.createElement('label');
label.innerHTML = `
<input type="checkbox" name="service" value="${service.id}" data-price="${service.price}" data-duration="${service.duration}" onchange="updateTotal()">
${service.name} (${service.price}₽, ${service.duration} мин)
`;
const questionIcon = document.createElement('div');
questionIcon.className = 'question-icon';
questionIcon.innerHTML = '?';
const description = document.createElement('div');
description.className = 'service-description';
description.style.position = 'absolute'; // Абсолютное позиционирование относительно контейнера
description.style.top = '100%'; // Размещаем описание под иконкой
description.style.left = '0'; // Выравниваем по левому краю иконки
description.style.display = 'none'; // Скрываем по умолчанию
if (service.name === 'KCX - Euro') {
description.innerHTML = `
<strong>Евромойка</strong><br>
1. Первичная обработка Multi Star.<br>
2. Мойка колесных дисков и насадок глушителя.<br>
3. Мойка пористой губкой и шампунем, (арки, пороги, коврики) Twin Shampoo.<br>
4. Консервация ЛКП Magic Dry & Care.<br>
5. Полная продувка кузова.
`;
} else if (service.name === 'KCX - Nano') {
description.innerHTML = `
<strong>Наномойка</strong><br>
1. Первичная обработка Multi Star.<br>
2. Мойка колесных дисков и насадок глушителя.<br>
3. Мойка пористой губкой и шампунем, (арки, пороги, коврики) Nano Magic Shampoo.<br>
4. Полная продувка кузова.
`;
} else if (service.name === 'KCX - Protector') {
description.innerHTML = `
<strong>Керамо-мойка</strong><br>
1. Первичная обработка Multi Star SIO2.<br>
2. Мойка колесных дисков и насадок глушителя.<br>
3. Мойка пористой губкой и шампунем, (арки, пороги, коврики) ACID SHAMPOO.<br>
4. Консервация ЛКП Protector CarWash.<br>
5. Полная продувка кузова.
`;
}
questionIcon.addEventListener('click', (event) => {
event.stopPropagation();
// Закрываем все открытые описания
const allDescriptions = document.querySelectorAll('.service-description');
allDescriptions.forEach(desc => {
if (desc !== description) {
desc.style.display = 'none';
}
});
// Показываем или скрываем текущее описание
if (description.style.display === 'none' || !description.style.display) {
description.style.display = 'block';
} else {
description.style.display = 'none';
}
});
serviceContainer.appendChild(label);
serviceContainer.appendChild(questionIcon);
serviceContainer.appendChild(description); // Добавляем описание внутрь контейнера
servicesContainer.appendChild(serviceContainer);
});
// Закрываем описание при клике вне его области
document.addEventListener('click', (event) => {
const descriptions = document.querySelectorAll('.service-description');
descriptions.forEach(desc => {
if (!desc.contains(event.target) && !desc.parentElement.contains(event.target)) {
desc.style.display = 'none';
}
});
});
}
function calculateTimeSlots(duration) {
const slots = [];
let startTime = new Date();
startTime.setHours(9, 0, 0);
while (startTime.getHours() < 20) {
const endTime = new Date(startTime.getTime() + duration * 60000);
slots.push({
start: startTime.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }),
end: endTime.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })
});
startTime = endTime;
}
return slots;
}
function populateTimeSlots(duration) {
const slots = calculateTimeSlots(duration);
const timeSlotsContainer = document.querySelector('.time-slots');
timeSlotsContainer.innerHTML = '';
slots.forEach(slot => {
const slotDiv = document.createElement('div');
slotDiv.className = 'time-slot available';
slotDiv.textContent = `${slot.start} - ${slot.end}`;
slotDiv.addEventListener('click', function () {
const isSelected = this.classList.contains('selected');
if (isSelected) {
this.classList.remove('selected');
} else {
document.querySelectorAll('.time-slot').forEach(s => s.classList.remove('selected'));
this.classList.add('selected');
}
updateConfirmButton();
});
timeSlotsContainer.appendChild(slotDiv);
});
}
function updateTotal() {
const selectedServices = document.querySelectorAll('input[name="service"]:checked');
let total = 0;
let totalDuration = 0;
selectedServices.forEach(service => {
total += parseInt(service.dataset.price);
totalDuration += parseInt(service.dataset.duration);
});
document.getElementById('total').textContent = `${total}₽`;
if (selectedServices.length > 0) {
populateTimeSlots(totalDuration);
} else {
const timeSlotsContainer = document.querySelector('.time-slots');
timeSlotsContainer.innerHTML = '';
}
updateConfirmButton();
}
// ------------ Валидация и форматирование ------------
function capitalizeInput(input) {
input.value = input.value
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
function validateName(input) {
input.value = input.value.replace(/[^а-яА-ЯёЁ\s]/g, '');
capitalizeInput(input);
validateStep4();
}
function formatPhone(input) {
let phone = input.value.replace(/\D/g, '');
if (phone.startsWith('7') || phone.startsWith('8')) {
phone = phone.substring(1);
}
if (phone.length > 10) {
phone = phone.substring(0, 10);
}
let formattedPhone = '+7';
if (phone.length > 0) {
formattedPhone += ` (${phone.substring(0, 3)}`;
}
if (phone.length > 3) {
formattedPhone += `) ${phone.substring(3, 6)}`;
}
if (phone.length > 6) {
formattedPhone += `-${phone.substring(6, 8)}`;
}
if (phone.length > 8) {
formattedPhone += `-${phone.substring(8, 10)}`;
}
input.value = formattedPhone;
validateStep4();
}
function validateStep4() {
const nameInput = document.getElementById('clientName');
const phoneInput = document.getElementById('clientPhone');
const carNumberInput = document.getElementById('clientCarNumber');
const nextButton = document.getElementById('next4');
const name = nameInput.value.trim();
const phone = phoneInput.value.trim();
const carNumber = carNumberInput.value.trim();
const isPhoneValid = phone.length === 18;
nextButton.disabled = !(name && isPhoneValid && carNumber);
}
function setupStep4Listeners() {
const nameInput = document.getElementById('clientName');
const phoneInput = document.getElementById('clientPhone');
const carNumberInput = document.getElementById('clientCarNumber');
nameInput.addEventListener('input', validateStep4);
phoneInput.addEventListener('input', validateStep4);
carNumberInput.addEventListener('input', validateStep4);
}
function updateConfirmButton() {
const currentStep = document.querySelector('.step[style="display: flex;"]');
if (!currentStep) return;
const stepNumber = parseInt(currentStep.id.replace('step', ''));
const confirmButton = document.getElementById(`next${stepNumber}`);
switch (stepNumber) {
case 1:
const brandSelected = document.getElementById('brand').value;
const modelSelected = document.getElementById('model').value;
confirmButton.disabled = !(brandSelected && modelSelected);
break;
case 2:
const servicesSelected = document.querySelectorAll('input[name="service"]:checked').length > 0;
confirmButton.disabled = !servicesSelected;
break;
case 3:
const timeSlotSelected = document.querySelector('.time-slot.selected');
confirmButton.disabled = !(timeSlotSelected && selectedDate);
break;
case 4:
validateStep4();
break;
default:
confirmButton.disabled = false;
}
}
// ------------ Инициализация и обработчики ------------
document.getElementById('fixed-button').addEventListener('click', async function () {
try {
db = await dbFunctions.initDatabase();
const brands = await dbFunctions.getBrands(db);
populateBrands(brands);
showStep(1);
} catch (error) {
console.error("Ошибка:", error);
}
});
document.getElementById('brand').addEventListener('change', async function () {
try {
const brandId = this.value;
if (!brandId) {
document.getElementById('model').disabled = true;
document.getElementById('next1').disabled = true;
return;
}
const models = await dbFunctions.getModels(db, brandId);
populateModels(models);
document.getElementById('model').disabled = false;
} catch (error) {
console.error("Ошибка при загрузке моделей:", error);
document.getElementById('model').disabled = true;
document.getElementById('next1').disabled = true;
}
});
document.getElementById('model').addEventListener('change', function () {
const modelId = this.value;
if (modelId) {
document.getElementById('next1').disabled = false;
} else {
document.getElementById('next1').disabled = true;
}
updateConfirmButton();
});
document.getElementById('model').addEventListener('change', async function () {
try {
const modelId = this.value;
if (!modelId) {
return;
}
const services = await dbFunctions.getServices(db, modelId);
populateServices(services);
} catch (error) {
console.error("Ошибка при загрузке услуг:", error);
}
});
async function getBrandAndModelName(db, modelId) {
try {
const stmt = db.prepare(`
SELECT b.name AS brandName, m.name AS modelName
FROM models m
JOIN brands b ON m.brand_id = b.id
WHERE m.id = $modelId
`);
stmt.bind({ $modelId: modelId });
const result = stmt.step() ? stmt.getAsObject() : null;
stmt.free();
return result ? `${result.brandName} ${result.modelName}` : "Неизвестная модель";
} catch (error) {
console.error("Ошибка при получении марки и модели:", error);
return "Неизвестная модель";
}
}
document.getElementById('clientPhone').addEventListener('focus', function () {
const phoneInput = this;
if (!phoneInput.value.startsWith('+7')) {
phoneInput.value = '+7';
}
});
document.getElementById('clientName').addEventListener('paste', function (event) {
event.preventDefault();
const pastedText = (event.clipboardData || window.clipboardData).getData('text');
this.value = pastedText;
capitalizeInput(this);
});
document.addEventListener('scroll', function () {
const fixedButton = document.getElementById('fixed-button');
const aboutSection = document.querySelector('.about-section');
const footer = document.querySelector('.footer');
const aboutSectionRect = aboutSection.getBoundingClientRect();
const footerRect = footer.getBoundingClientRect();
if (aboutSectionRect.top <= window.innerHeight || footerRect.top <= window.innerHeight) {
fixedButton.classList.add('hidden');
} else {
fixedButton.classList.remove('hidden');
}
});
// ------------ Вспомогательные функции ------------
function updateTimeSlots() {
const selectedServices = document.querySelectorAll('input[name="service"]:checked');
let totalDuration = 0;
selectedServices.forEach(service => {
totalDuration += parseInt(service.dataset.duration);
});
if (selectedServices.length > 0) {
populateTimeSlots(totalDuration);
} else {
const timeSlotsContainer = document.querySelector('.time-slots');
timeSlotsContainer.innerHTML = '';
}
}
// ------------ Функция для сохранения записи ------------
async function saveAppointment() {
if (!db) {
console.error("База данных не инициализирована");
return;
}
const clientName = document.getElementById('clientName').value;
const clientPhone = document.getElementById('clientPhone').value;
const clientCarNumber = document.getElementById('clientCarNumber').value;
const selectedServices = Array.from(document.querySelectorAll('input[name="service"]:checked'))
.map(service => service.value);
const selectedTimeSlot = document.querySelector('.time-slot.selected');
if (!selectedTimeSlot) {
console.error("Время не выбрано");
return;
}
const [startTime, endTime] = selectedTimeSlot.textContent.split(' - ');
const modelId = document.getElementById('model').value;
const brandAndModelName = await getBrandAndModelName(db, modelId);
const appointment = {
clientName,
clientPhone,
carNumber: clientCarNumber,
model: brandAndModelName,
services: selectedServices,
date: selectedDate.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' }),
startTime,
endTime,
timestamp: new Date().toLocaleString()
};
try {
await dbFunctions.saveAppointment(db, clientName, clientPhone, clientCarNumber, modelId, selectedServices, startTime, endTime);
saveAppointmentToLocalStorage(appointment);
console.log("Запись успешно сохранена");
showStep(5);
} catch (error) {
console.error("Ошибка при сохранении записи:", error);
}
}
function saveAppointmentToLocalStorage(appointment) {
const appointments = JSON.parse(localStorage.getItem('appointments')) || [];
appointments.push(appointment);
localStorage.setItem('appointments', JSON.stringify(appointments));
console.log('Запись сохранена в LocalStorage:', appointment);
}
document.querySelector('.number').addEventListener('click', function () {
document.getElementById('phone-modal').style.display = 'flex';
});
document.querySelector('.close-phone-modal').addEventListener('click', function () {
document.getElementById('phone-modal').style.display = 'none';
});
window.addEventListener('click', function (event) {
const phoneModal = document.getElementById('phone-modal');
if (event.target === phoneModal) {
phoneModal.style.display = 'none';
}
});
document.getElementById('copy-phone-number').addEventListener('click', function () {
const phoneNumber = '+7 (495) 228-64-28';
navigator.clipboard.writeText(phoneNumber).then(function () {
alert('Номер скопирован: ' + phoneNumber);
}).catch(function (error) {
console.error('Ошибка при копировании: ', error);
});
});