# -*- coding: utf-8 -*-
"""Kiểm thử DỰNG HTML trang chi tiết có bảng đề xuất hiệu chỉnh (không để lại dữ liệu tạm)."""
import importlib.util, os, sqlite3, json, time, traceback

GOC = r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\calib-app'
DB = r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\CSDLB.db'
spec = importlib.util.spec_from_file_location('s', os.path.join(GOC, 'server_calib.py'))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)

con = sqlite3.connect(DB)
c = con.cursor()
truoc = c.execute('SELECT COUNT(*) FROM hieu_chinh_mau').fetchone()[0]
h = ''
try:
    c.execute('INSERT INTO hieu_chinh_mau (ngay,mau_id,mau_ten,hon_hop_id,tham_so,gia_tri_cu,gia_tri_moi,ly_do,'
              'delta_E_truoc,nguon,da_ap_dung,lab_moi,nguon_anh) VALUES (?,?,?,?,?,?,?,?,?,?,0,?,?)',
              (time.strftime('%Y-%m-%d %H:%M'), 9, 'Orange 2RG-62 (1-2)', 999, 'he_so_cuong_do', '1.0', '1.25',
               'kiểm thử dựng HTML', 39.6, 'test', '{"L":65,"a":45,"b":65,"hex":"#eb6414"}', 'x.png'))
    con.commit()
    row = c.execute('SELECT * FROM hon_hop WHERE id=2').fetchone()
    cot = [x[0] for x in c.execute('SELECT * FROM hon_hop LIMIT 1').description]
    v = dict(zip(cot, row))
    v.update(id=999, trang_thai='cho_xac_nhan', nguoi_nhap='Test', thuc_te_hex='#7a3a12', thuc_te_L=40.0,
             thuc_te_a=30.0, thuc_te_b=25.0, delta_E=39.6, ket_luan='lệch mạnh',
             anh_thuc_te='viec/H0999_0810/anh/test.png', thu_muc='C:/tmp')
    hb = m.trang_chi_tiet(v, {})
    h = hb.decode('utf-8') if isinstance(hb, bytes) else hb
except Exception as e:
    print('LỖI dựng trang:', type(e).__name__, e)
    traceback.print_exc()
finally:
    c.execute('DELETE FROM hieu_chinh_mau WHERE hon_hop_id=999')
    con.commit()

print('  độ dài HTML:', len(h), 'byte ->', os.path.join(GOC, '_test_trang_chi_tiet.html'))
for k, x in [('bảng ĐỀ XUẤT HIỆU CHỈNH', 'ĐỀ XUẤT HIỆU CHỈNH' in h),
             ('nút "Xác nhận & ghi vào CSDL B"', 'Xác nhận &amp; ghi vào CSDL B' in h),
             ('ô mật khẩu', 'type="password"' in h),
             ('action ap-dung?id=999', 'action="ap-dung?id=999"' in h),
             ('hệ số mới 1.25', '1.25' in h),
             ('nhắc "CSDL B giữ nguyên"', 'CSDL B giữ nguyên' in h),
             ('dòng điều kiện chuẩn', 'Điều kiện chuẩn' in h),
             ('có <base> tự sinh', 'document.write("<base href="+B+">")' in h)]:
    print('   ·', k, ':', x)
print('  dòng đề xuất sau dọn:', c.execute('SELECT COUNT(*) FROM hieu_chinh_mau').fetchone()[0], '(trước:', truoc, ')')
print('  hệ số 8 màu:', sorted(set(r[0] for r in c.execute('SELECT he_so_cuong_do FROM mau'))))
print('  hỗn hợp:', c.execute('SELECT id,trang_thai FROM hon_hop ORDER BY id').fetchall())
con.close()
