# -*- coding: utf-8 -*-
"""B28: lưu file mua hàng anh vừa gửi vào thư mục dự án + soi cấu trúc để viết YEU_CAU cho AGY."""
import glob, os, shutil, datetime

NGUON = r'C:\Users\admin\AppData\Local\hermes\cache\documents\doc_039f57231e05_mua hàng tháng 10- 26 - 2.xlsx'
DICH_DIR = r'C:\Claw 2\Bao cao - Hanh chinh\bao cao mua hang'
if not os.path.exists(NGUON):
    cand = glob.glob(os.path.join(r'C:\Users\admin\AppData\Local\hermes\cache\documents', 'doc_039f57231e05*'))
    NGUON = cand[0] if cand else NGUON
print('  nguồn:', NGUON, os.path.getsize(NGUON) if os.path.exists(NGUON) else 'KHÔNG THẤY')

dich = os.path.join(DICH_DIR, 'mua hàng tháng 10- 26 - 2.xlsx')
if not os.path.exists(dich):
    shutil.copy2(NGUON, dich)
print('  đã lưu:', dich, os.path.getsize(dich), 'B')

print()
print('  === các file mua hàng tháng 10 hiện có trong dự án ===')
for p in sorted(glob.glob(os.path.join(DICH_DIR, '*tháng 10*')) + glob.glob(os.path.join(DICH_DIR, '*T10*')) + glob.glob(os.path.join(DICH_DIR, 'MUA_HANG*'))):
    print('   %-58s %8d B  %s' % (os.path.basename(p), os.path.getsize(p), datetime.datetime.fromtimestamp(os.path.getmtime(p)).strftime('%d/%m %H:%M')))

print()
print('  === cấu trúc file mới ===')
import openpyxl
wb = openpyxl.load_workbook(dich, data_only=True)
print('  sheets:', wb.sheetnames)
for ten in wb.sheetnames[:4]:
    ws = wb[ten]
    print('  --- sheet "%s": %d hàng x %d cột' % (ten, ws.max_row, ws.max_column))
    for r in range(1, min(6, ws.max_row + 1)):
        o = [ws.cell(r, c).value for c in range(1, min(ws.max_column, 22) + 1)]
        print('     h%d: %s' % (r, [str(x)[:14] if x is not None else '' for x in o]))
    print('     ...')
    for r in range(max(1, ws.max_row - 4), ws.max_row + 1):
        o = [ws.cell(r, c).value for c in range(1, min(ws.max_column, 22) + 1)]
        print('     h%-4d: %s' % (r, [str(x)[:14] if x is not None else '' for x in o]))
