Spaces:
Sleeping

File size: 24,976 Bytes
62df11d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad96dd
62df11d
bd52602
62df11d
bd52602
 
62df11d
bd52602
 
62df11d
 
bd52602
62df11d
2ad96dd
 
 
 
62df11d
 
6074721
b5487b9
62df11d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
function login() {
  const u = document.getElementById("username").value;
  const p = document.getElementById("password").value;

  if (u === "admin" && p === "1234") {
    document.getElementById("login").style.display = "none";
    document.getElementById("dashboard").style.display = "block";
    enableSubmenuClick();

    // ❗❗ Ẩn tất cả các phần fade-in trước
    document.querySelectorAll(".fade-in").forEach(el => {
      if (el) el.style.display = "none";
    });

    // ✅ Sau đó hiện Hồ sơ năng lực
    const hs = document.getElementById("Nl");
    if (hs) {
      hs.style.display = "block";
      hs.scrollIntoView({ behavior: "smooth" });
    }

  } else {
    alert("Sai tên đăng nhập hoặc mật khẩu!");
  }
}
const BACKEND_URL = "https://doluong6-qlht.hf.space";

// ==== Hiển thị nội dung theo mục được chọn ====
function chonMuc(muc) {
  // Ẩn tất cả phần tử có class .fade-in
  document.querySelectorAll(".fade-in").forEach(el => {
    if (el) el.style.display = "none";
  });

  // Hiển thị mục 'Chờ xử lý'
  if (muc === "pycload") {
    const stat = document.getElementById("pycload");
    if (stat) stat.style.display = "flex";
    hienThiDanhSachPYC();
  }

  // Hiển thị mục 'Đã hoàn thành'
  if (muc === "pycend") {
    const stat = document.getElementById("pycend");
    if (stat) stat.style.display = "flex";
    hienThiSoPYCHoanThanh();
  }
  if (muc === "pycdt") {
    const stat = document.getElementById("pycdt");
    if (stat) stat.style.display = "flex";
    hienThiDoanhThuPYC();
  }
  if (muc === "pyc") {
    const section = document.getElementById("pyc");
    if (section) section.style.display = "block";
    hienThiDanhSachPYCChuaHoanThanh();
  }
  if (muc === "dttong") {
    const stat = document.getElementById("dttong");
    if (stat) stat.style.display = "flex";
    hienThiDoanhThuTong(); // <--- Hàm này phải được định nghĩa
  }
  if (muc === "dtthang") {
    const stat = document.getElementById("dtthang");
    if (stat) stat.style.display = "block";
    hienThiDoanhThuTheoThang();
  }
  if (muc === "Nl") {
    const section = document.getElementById("Nl");
    if (section) section.style.display = "block";
  }
  if (muc === "dtdichvu") {
    document.getElementById("dtdichvu").style.display = "block";
    hienThiDoanhThuDichVu();  // Gọi API để hiển thị bảng
  }
  if (muc === "dtnoibo") {
    document.getElementById("dtnoibo").style.display = "block";
    hienThiDoanhThuNoiBo();
  }
  if (muc === "tailieu") {
    const section = document.getElementById("tailieu");
    if (section) {
      section.style.display = "block";
      taiDanhSachPDF();
      hienThiPDF();// ✅ Gọi API lấy danh sách PDF
    }
  }
  if (muc === "qt") {
    const section = document.getElementById("qt");
    if (section) {
      section.style.display = "block";
      taiDanhSachQuyTrinh();
      hienThiQT();
    }
  }
  if (muc === "dm") {
    const section = document.getElementById("dm");
    if (section) section.style.display = "block"; // ✅ hiện vùng hiển thị
    fetch(`${BACKEND_URL}/danh_muc_thiet_bi`)
      .then(res => {
        if (!res.ok) throw new Error("Lỗi từ server: " + res.status);
        return res.json();
      })
      .then(data => {
        const table = $('#bangDanhMucThietBi');
        table.empty();
    
        if (!Array.isArray(data) || data.length === 0) {
          table.html("<p style='color:red'>Không có dữ liệu để hiển thị.</p>");
          return;
        }
    
        if (!$.fn.DataTable.isDataTable('#bangDanhMucThietBi')) {
          table.DataTable({
            data: data,
            columns: Object.keys(data[0] || {}).map(key => ({ title: key, data: key })),
            paging: true,
            searching: true,
            scrollX: true,
            responsive: true,
            autoWidth: false
          });
        } else {
          const dt = table.DataTable();
          dt.clear().rows.add(data).draw();
        }
      })
      .catch(err => {
        console.error("Lỗi khi tải danh mục thiết bị:", err);
        $('#bangDanhMucThietBi').html("<p style='color:red'>Không thể tải dữ liệu.</p>");
      });
    }
  if (muc === "qlhc") {
    const section = document.getElementById("qlhc");
    if (section) {
      section.style.display = "block";
      hienThiHoaChat();
    }
  }
  if (muc === "hsl") {
    const section = document.getElementById("hsl");
    if (section) section.style.display = "block";
    hienThiHSKH();
  }
}



async function hienThiDanhSachPYC() {
  try {
    const res = await fetch("/dem_pyc_tat_ca");
    const data = await res.json();
    console.log("DATA ĐẾM PYC:", data);

    if (data.tong_so_pyc !== undefined) {
      document.getElementById("pycCount").textContent = `${data.tong_so_pyc} phiếu`;
    } else {
      document.getElementById("pycCount").textContent = "Không xác định";
    }
  } catch (err) {
    console.error("Lỗi khi gọi API PYC:", err);
    document.getElementById("pycCount").textContent = "Lỗi";
  }
}

async function hienThiSoPYCHoanThanh() {
  try {
    const res = await fetch(`${BACKEND_URL}/dem_pyc_hoan_thanh`);
    const data = await res.json();

    if (res.ok && data.tong_so_hoan_thanh !== undefined) {
      document.getElementById("completedRequests").textContent = data.tong_so_hoan_thanh + " phiếu";
    } else {
      document.getElementById("completedRequests").textContent = "Không tải được";
    }
  } catch (err) {
    console.error("Lỗi khi gọi API hoàn thành:", err);
    document.getElementById("completedRequests").textContent = "Lỗi";
  }
}
async function hienThiDoanhThuPYC() {
  try {
    const res = await fetch(`${BACKEND_URL}/tong_doanh_thu_pyc`);
    const data = await res.json();

    console.log("DATA DOANH THU:", data); // ✅ Debug console

    if (res.ok && data.tong_doanh_thu !== undefined) {
      const formatted = Number(data.tong_doanh_thu).toLocaleString("vi-VN") + " VND";
      document.getElementById("requestRevenue").textContent = formatted;
    } else {
      document.getElementById("requestRevenue").textContent = "Không tải được";
    }
  } catch (err) {
    console.error("Lỗi khi gọi API doanh thu:", err);
    document.getElementById("requestRevenue").textContent = "Lỗi";
  }
}

function enableSubmenuClick() {
  document.querySelectorAll(".menu-item.has-sub").forEach(item => {
    item.addEventListener("click", () => {
      const id = item.getAttribute("data-submenu");
      const submenu = document.getElementById(id);
      const arrow = document.getElementById("arrow-" + id);

      if (submenu.style.display === "block") {
        submenu.style.display = "none";
        arrow.innerHTML = "►";
      } else {
        submenu.style.display = "block";
        arrow.innerHTML = "▼";
      }
    });
  });
}
async function hienThiDanhSachPYCChuaHoanThanh() {
  const container = document.getElementById("pycIncompleteList");
  container.innerHTML = "Đang tải dữ liệu...";
  try {
    const res = await fetch(`${BACKEND_URL}/pyc_chua_hoan_thanh`);
    const data = await res.json();

    if (!Array.isArray(data) || data.length === 0) {
      container.innerHTML = "Không có dữ liệu.";
      return;
    }

    let html = "<table class='display' id='tablePYCIncomplete'><thead><tr>";
    for (let key in data[0]) {
      html += `<th>${key}</th>`;
    }
    html += "</tr></thead><tbody>";

    for (let row of data) {
      html += "<tr>";
      for (let key in row) {
        html += `<td>${row[key]}</td>`;
      }
      html += "</tr>";
    }

    html += "</tbody></table>";
    container.innerHTML = html;

    $(document).ready(function () {
      $('#tablePYCIncomplete').DataTable();
    });
  } catch (err) {
    console.error("Lỗi khi tải bảng phiếu chưa hoàn thành:", err);
    container.innerHTML = "Lỗi khi tải dữ liệu.";
  }
}
async function hienThiDoanhThuTong() {
  try {
    const res = await fetch(`${BACKEND_URL}/doanh_thu_tong`);
    const data = await res.json();

    if (res.ok && data.tong_doanh_thu !== undefined) {
      const formatted = Number(data.tong_doanh_thu).toLocaleString("vi-VN") + " VND";
      document.getElementById("tongDoanhThu").textContent = formatted;
    } else {
      document.getElementById("tongDoanhThu").textContent = "Không tải được";
    }
  } catch (err) {
    console.error("Lỗi khi gọi API doanh thu tổng:", err);
    document.getElementById("tongDoanhThu").textContent = "Lỗi";
  }
}
async function hienThiDoanhThuTheoThang() {
  const ctx = document.getElementById("chartDoanhThuThang").getContext("2d");
  try {
    const res = await fetch(`${BACKEND_URL}/doanh_thu_theo_thang`);
    const data = await res.json();

    if (!res.ok || !data || !Array.isArray(data.thang) || !Array.isArray(data.doanh_thu)) {
      throw new Error("Dữ liệu không hợp lệ");
    }

    // Xóa biểu đồ cũ nếu đã có
    if (window.doanhThuChart) {
      window.doanhThuChart.destroy();
    }

    // Vẽ biểu đồ cột
    window.doanhThuChart = new Chart(ctx, {
      type: "bar",
      data: {
        labels: data.thang,
        datasets: [{
          label: "Doanh thu (VND)",
          data: data.doanh_thu,
          backgroundColor: "rgba(54, 162, 235, 0.6)",
          borderColor: "rgba(54, 162, 235, 1)",
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              callback: function(value) {
                return value.toLocaleString("vi-VN") + " VND";
              }
            }
          }
        },
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return context.raw.toLocaleString("vi-VN") + " VND";
              }
            }
          }
        }
      }
    });

  } catch (err) {
    console.error("Lỗi khi gọi API doanh thu theo tháng:", err);
    document.getElementById("chartDoanhThuThang").outerHTML = "<p>Lỗi khi tải biểu đồ.</p>";
  }
}
async function hienThiDoanhThuDichVu() {
  try {
    const res = await fetch("/doanh_thu_dich_vu");
    const result = await res.json();

    console.log("📊 Kết quả từ API doanh_thu_dich_vu:", result);

    if (!result || result.error) {
      document.querySelector("#anhDoanhThuDichVu").alt = "Lỗi khi tải biểu đồ.";
      $('#bangDoanhThuDichVu').html("<p style='color:red'>Không thể tải dữ liệu.</p>");
      return;
    }

    const data = result.data || [];
    const imageBase64 = result.image_base64;

    // Hiển thị ảnh biểu đồ
    const imgElement = document.querySelector("#anhDoanhThuDichVu");
    if (imageBase64) {
      imgElement.src = `data:image/png;base64,${imageBase64}`;
      imgElement.alt = "Biểu đồ doanh thu dịch vụ";
    } else {
      imgElement.alt = "Không có ảnh biểu đồ.";
    }

    // Hiển thị bảng dữ liệu
    const table = $('#bangDoanhThuDichVu');
    if ($.fn.dataTable.isDataTable('#bangDoanhThuDichVu')) {
      table.DataTable().clear().rows.add(data).draw();
    } else {
      table.DataTable({
        data: data,
        columns: [
          { title: "Dịch vụ", data: "Dịch vụ" },
          { title: "Số lượng", data: "Số lượng" },
          { title: "Tỷ lệ (%)", data: "Tỷ lệ (%)" },
          {
            title: "Tổng doanh thu",
            data: "Tổng doanh thu",
            render: function (data, type, row) {
              if (type === 'display' && typeof data === 'number') {
                return data.toLocaleString('vi-VN') + " ₫";
              }
              return data;
            }
          }
        ],
        paging: false,
        searching: false,
        info: false
      });
    }

  } catch (error) {
    console.error("❌ Lỗi khi tải dữ liệu doanh thu dịch vụ:", error);
    document.querySelector("#anhDoanhThuDichVu").alt = "Lỗi kết nối tới API.";
    $('#bangDoanhThuDichVu').html("<p style='color:red'>Lỗi kết nối tới máy chủ.</p>");
  }
}
async function hienThiDoanhThuNoiBo() {
  try {
    const res = await fetch(`${BACKEND_URL}/doanh_thu_noi_bo`);
    const result = await res.json();

    console.log("📊 Kết quả doanh thu nội bộ:", result);

    const data = result.data || [];
    const tong = result.tong || {};

    // Hiển thị bảng
    const table = $('#bangDoanhThuNoiBo');
    if ($.fn.dataTable.isDataTable('#bangDoanhThuNoiBo')) {
      table.DataTable().clear().rows.add(data).draw();
    } else {
      table.DataTable({
        data: data,
        columns: [
          { title: "Phòng", data: "Phòng" },
          {
            title: "Chuyển đến",
            data: "Chuyển đến",
            render: function (data) {
              return typeof data === 'number' ? data.toLocaleString('vi-VN') + " ₫" : "-";
            }
          },
          {
            title: "Chuyển đi",
            data: "Chuyển đi",
            render: function (data) {
              return typeof data === 'number' ? data.toLocaleString('vi-VN') + " ₫" : "-";
            }
          }
        ],
        paging: false,
        searching: false,
        info: false
      });
    }

    // Hiển thị tổng
    const cdStr = typeof tong["Tổng chuyển đến"] === 'number' ? tong["Tổng chuyển đến"].toLocaleString('vi-VN') + " ₫" : "-";
    const diStr = typeof tong["Tổng chuyển đi"] === 'number' ? tong["Tổng chuyển đi"].toLocaleString('vi-VN') + " ₫" : "-";

    document.getElementById("tongDoanhThuNoiBo").innerHTML = `
      <p>Tổng chuyển đến: <strong>${cdStr}</strong></p>
      <p>Tổng chuyển đi: <strong>${diStr}</strong></p>
    `;

  } catch (error) {
    console.error("❌ Lỗi khi tải doanh thu nội bộ:", error);
    document.getElementById("tongDoanhThuNoiBo").innerHTML = "<p style='color:red'>Không thể tải dữ liệu nội bộ.</p>";
  }
}
// Gọi API lấy danh sách PDF từ backend
async function taiDanhSachPDF() {
  try {
    const res = await fetch(`${BACKEND_URL}/danh_sach_pdf`);
    const data = await res.json();

    const select = document.getElementById("selectPdf");
    select.innerHTML = '<option value="">-- Chọn tài liệu để xem --</option>';

    data.pdfs.forEach(file => {
      const option = document.createElement("option");
      option.value = file;
      option.textContent = file;
      select.appendChild(option);
    });
  } catch (err) {
    console.error("Không thể tải danh sách PDF:", err);
  }
}

// Xử lý hiển thị PDF khi chọn trong dropdown
function hienThiPDF() {
  const select = document.getElementById("selectPdf");
  const fileName = select.value;
  const viewer = document.getElementById("pdfViewer");
  const iframe = document.getElementById("pdfFrame");
  const download = document.getElementById("pdfDownload");

  if (!fileName) {
    viewer.style.display = "none";
    return;
  }

  const pdfUrl = `${BACKEND_URL}/xem_pdf?file_name=${encodeURIComponent(fileName)}`;
  iframe.src = pdfUrl;
  download.href = pdfUrl;
  viewer.style.display = "block";
}

async function taiDanhSachQuyTrinh() {
  try {
    const res = await fetch(`${BACKEND_URL}/quy_trinh`);
    const data = await res.json();

    const select = document.getElementById("selectQT");
    select.innerHTML = `<option value="">-- Chọn tài liệu --</option>`;

    data.pdfs.forEach(item => {
      let fileName, filePath;
      if (typeof item === "string") {
        fileName = item;
        filePath = `Quy_trinh/${item}`;
      } else {
        fileName = item.name;
        filePath = item.path;
      }

      const option = document.createElement("option");
      option.value = filePath;
      option.textContent = fileName;
      select.appendChild(option);
    });
  } catch (error) {
    console.error("Lỗi khi tải danh sách quy trình:", error);
    alert("Không thể tải danh sách quy trình.");
  }
}
function hienThiQT() {
  const file = document.getElementById("selectQT").value;
  const iframe = document.getElementById("qtFrame");
  const viewer = document.getElementById("qtViewer");
  const download = document.getElementById("qtDownload");

  if (file) {
    const ext = file.toLowerCase().split('.').pop();
    const url = `${BACKEND_URL}/xem_pdf?file=${encodeURIComponent(file)}`;

    if (ext === "pdf") {
      iframe.src = url;
      iframe.style.display = "block";
    } else {
      iframe.src = "";
      iframe.style.display = "none";
      alert("Không hỗ trợ xem trực tiếp định dạng này. Vui lòng tải về.");
    }

    download.href = url + "&download=true";
    viewer.style.display = "block";
  } else {
    viewer.style.display = "none";
  }
}
function parseNgayVN(ngayStr) {
  if (!ngayStr || typeof ngayStr !== 'string') return null;
  ngayStr = ngayStr.trim().split(" ")[0];

  if (/^\d{4}-\d{2}-\d{2}$/.test(ngayStr)) return new Date(ngayStr);

  const parts = ngayStr.split(/\/|-/);
  if (parts.length === 3) {
    let [d, m, y] = parts;
    if (y.length === 2) y = '20' + y;
    return new Date(`${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`);
  }
  return null;
}

async function hienThiHoaChat() {
  try {
    const res = await fetch("/quan_ly_hoa_chat");
    if (!res.ok) throw new Error("Không thể tải dữ liệu hóa chất");

    const data = await res.json();
    const columns = data.columns;
    const rows = data.rows;

    const idxHanSD = columns.findIndex(c => c.toUpperCase().includes("HẠN"));
    const idxTinhTrang = columns.findIndex(c => c.toUpperCase().includes("TÌNH TRẠNG"));

    const table = document.getElementById("bangHoaChat");
    table.innerHTML = "";

    const thead = table.createTHead();
    const headerRow = thead.insertRow();
    columns.forEach(col => {
      const th = document.createElement("th");
      th.textContent = col;
      th.style.background = "#f2f2f2";
      th.style.padding = "8px";
      th.style.border = "1px solid #ccc";
      headerRow.appendChild(th);
    });

    const tbody = table.createTBody();
    rows.forEach(row => {
      const tr = tbody.insertRow();
      row.forEach((cell, colIndex) => {
        const td = tr.insertCell();
        const input = document.createElement("input");
        input.type = "text";
        input.value = cell;
        input.classList.add("input-cell");
        input.style.width = "100%";

        // Chỉ xử lý ô tình trạng
        if (colIndex === idxTinhTrang) {
          input.readOnly = true;
          input.style.fontWeight = "bold";

          const hanSD = parseNgayVN(row[idxHanSD]);
          let status = "Không xác định";
          let color = "black";

          if (hanSD instanceof Date && !isNaN(hanSD)) {
            const today = new Date();
            const diffDays = Math.ceil((hanSD - today) / (1000 * 3600 * 24));

            if (diffDays < 0) {
              status = "HẾT HẠN";
              color = "red";
            } else if (diffDays <= 30) {
              status = `CÒN: ${diffDays} ngày`;
              color = "orange";
            } else {
              status = `CÒN: ${diffDays} ngày`;
              color = "green";
            }
          }

          input.value = status;
          input.style.color = color;
        }

        td.appendChild(input);
      });
    });

    document.getElementById("nutLuuHoaChat").style.display = "block";
  } catch (err) {
    console.error("Lỗi khi tải danh mục hóa chất:", err);
    alert("❌ Không thể tải dữ liệu hóa chất.");
  }
}





// ==== Lưu dữ liệu đã chỉnh sửa ====
async function luuHoaChat() {
  const table = document.getElementById("bangHoaChat");
  if (!table) return;

  const headers = Array.from(table.querySelectorAll("thead th")).map(th => th.textContent.trim());
  const data = [];

  table.querySelectorAll("tbody tr").forEach(tr => {
    const row = Array.from(tr.querySelectorAll("td input")).map(input => input.value.trim());
    if (row.length === headers.length) {
      data.push(row);
    }
  });

  console.log("🧪 Gửi:", { columns: headers, data: data });

  try {
    const res = await fetch(`${BACKEND_URL}/cap_nhat_hoa_chat`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ columns: headers, data: data })
    });

    const result = await res.json();
    alert(result.message || "✅ Đã lưu dữ liệu thành công!");
  } catch (err) {
    console.error("❌ Lỗi khi lưu hóa chất:", err);
    alert("❌ Không thể lưu dữ liệu.");
  }
}
// Gọi API hiển thị HSKH
async function hienThiHSKH() {
  try {
    const response = await fetch(`${BACKEND_URL}/hien_thi_hskh`);
    const data = await response.json();

    if (!data || !data.rows || data.rows.length === 0) {
      console.warn("Không có dữ liệu HSKH.");
      return;
    }

    const fullIndex = data.columns.indexOf("Full");

    if ($.fn.DataTable.isDataTable("#bangHSKH")) {
      $('#bangHSKH').DataTable().clear().destroy();
    }

    let tbodyHtml = "";
    data.rows.forEach(row => {
      tbodyHtml += `<tr>`;

      for (let j = 0; j < data.columns.length; j++) {
        const col = data.columns[j];
        const cell = row[j] || "";

        if (["Full", "PYC", "BB", "GCN"].includes(col)) {
          const checked = cell.toLowerCase() === "x" ? "checked" : "";
          const className = col === "Full" ? "checkbox-full" : "checkbox-cell";
          tbodyHtml += `<td><input type="checkbox" class="${className}" ${checked}></td>`;
        } else {
          tbodyHtml += `<td><input class="input-cell" type="text" value="${cell}" /></td>`;
        }
      }

      tbodyHtml += `</tr>`;
    });

    $("#bangHSKH tbody").html(tbodyHtml);    
    $("#bangHSKH").DataTable({
      destroy: true,
      scrollX: true,
      autoWidth: true,
      paging: false,                // ✅ Tắt hoàn toàn phân trang
      ordering: false,
      searching: true,
      info: true,
      language: {
        search: "🔍 Tìm kiếm:",
        info: "Đang hiển thị _TOTAL_ dòng",
        emptyTable: "Không có dữ liệu"
      },
      columnDefs: [
        { targets: "_all", className: "dt-center" }
      ]
    });



    // ✅ Tô màu dòng nếu FULL được tick
    function capNhatMauDong() {
      $("#bangHSKH tbody tr").each(function () {
        const checkbox = $(this).find(`td:eq(${fullIndex}) input[type="checkbox"]`);
        if (checkbox.prop("checked")) {
          $(this).css("background-color", "#d2f8d2"); // Xanh
        } else {
          $(this).css("background-color", "#fde2e2"); // Hồng
        }
      });
    }

    capNhatMauDong();

    // ✅ Khi tích/bỏ tick vào cột FULL thì cập nhật màu dòng
    $("#bangHSKH").off("change", "input.checkbox-full")
      .on("change", "input.checkbox-full", function () {
        capNhatMauDong();
      });

    // ✅ Hiện nút lưu
    document.getElementById("nutLuuHSKH").style.display = "inline-block";

  } catch (error) {
    console.error("Lỗi khi tải dữ liệu HSKH:", error);
    alert("Không thể tải dữ liệu hồ sơ lưu.");
  }
}

async function luuHSKH() {
  try {
    const headers = [];
    $("#bangHSKH thead tr:last-child th").each(function () {
      headers.push($(this).text().trim());
    });

    const topHeaders = $("#bangHSKH thead tr:first-child th[rowspan='2']");
    topHeaders.each(function (index) {
      headers.splice(index, 0, $(this).text().trim());
    });

    const rows = [];
    $("#bangHSKH tbody tr").each(function () {
      const row = [];
      $(this)
        .find("td")
        .each(function (i) {
          const input = $(this).find("input");
          if (input.length > 0) {
            if (input.attr("type") === "checkbox") {
              row.push(input.prop("checked") ? "x" : "");
            } else {
              row.push(input.val());
            }
          } else {
            row.push($(this).text());
          }
        });
      rows.push(row);
    });

    const response = await fetch(`${BACKEND_URL}/cap_nhat_hskh`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        columns: headers,
        rows: rows
      })
    });

    if (response.ok) {
      alert("✅ Dữ liệu đã được lưu thành công!");
    } else {
      const err = await response.json();
      alert("❌ Lỗi khi lưu: " + err.detail);
    }
  } catch (error) {
    console.error("Lỗi khi gửi dữ liệu:", error);
    alert("❌ Không thể gửi dữ liệu để lưu.");
  }
}