# -*- coding: utf-8 -*-
import openpyxl, os, docx
from docx.shared import Inches, Pt, RGBColor
from docx.enum.section import WD_ORIENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml import OxmlElement, parse_xml
from docx.oxml.ns import nsdecls, qn

def set_cell_background(cell, fill_hex):
    tcPr = cell._tc.get_or_add_tcPr()
    shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{fill_hex}"/>')
    tcPr.append(shd)

def set_cell_margins(cell, top=80, bottom=80, left=60, right=60):
    tcPr = cell._tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')
    for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
        node = OxmlElement(f'w:{m}')
        node.set(qn('w:w'), str(val))
        node.set(qn('w:type'), 'dxa')
        tcMar.append(node)
    tcPr.append(tcMar)

clean_file = os.path.join('File-lam-sach', 'MUA_HANG_10T10-26_DA-LAM-SACH.xlsx')
wb = openpyxl.load_workbook(clean_file, data_only=True)
ws = wb['FILE GỐC']

days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 10]
month_names = ['Tháng 01', 'Tháng 02', 'Tháng 03', 'Tháng 04', 'Tháng 05', 'Tháng 06', 'Tháng 07', 'Tháng 08', 'Tháng 09', 'Kỳ T10 (10 ngày)']
short_headers = ['TB T1', 'TB T2', 'TB T3', 'TB T4', 'TB T5', 'TB T6', 'TB T7', 'TB T8', 'TB T9', 'TB T10 (10N)']

customers = []
tot_row = None

for r in range(5, ws.max_row + 1):
    stt = ws.cell(r, 1).value
    ma = ws.cell(r, 2).value
    ten = ws.cell(r, 3).value
    vals = [float(ws.cell(r, c).value or 0) for c in range(4, 14)]
    
    if r == ws.max_row or str(ten).strip().lower() == 'tổng cộng' or str(ma).strip().upper() == 'ZZZ':
        tot_row = vals
    else:
        customers.append({
            'stt': stt,
            'ma': str(ma or '').strip(),
            'ten': str(ten or '').strip(),
            'sales': vals
        })

print(f'Loaded {len(customers)} customers.')
print(f'Total row (T10): {tot_row[9]}')

doc = docx.Document()
section = doc.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = Inches(11.69), Inches(8.27)
section.top_margin = Inches(0.5)
section.bottom_margin = Inches(0.5)
section.left_margin = Inches(0.5)
section.right_margin = Inches(0.5)

style_normal = doc.styles['Normal']
style_normal.font.name = 'Times New Roman'
style_normal.font.size = Pt(11)

# Title
title_p = doc.add_paragraph()
title_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
title_p.paragraph_format.space_before = Pt(0)
title_p.paragraph_format.space_after = Pt(2)
r_title = title_p.add_run('BÁO CÁO PHÂN TÍCH & SO SÁNH LƯỢNG BÁN TRUNG BÌNH NGÀY HÀNG THÁNG')
r_title.font.size = Pt(16)
r_title.font.bold = True
r_title.font.color.rgb = RGBColor(26, 82, 118)

sub_p = doc.add_paragraph()
sub_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
sub_p.paragraph_format.space_after = Pt(10)
r_sub = sub_p.add_run('Kỳ Báo Cáo: 10 Ngày Đầu Tháng 10 Năm 2026 (Từ 01/10/2026 đến 10/10/2026 - 10 Ngày)')
r_sub.font.italic = True
r_sub.font.size = Pt(11)
r_sub.font.color.rgb = RGBColor(86, 101, 115)

# I. Thông tin chung
h1 = doc.add_paragraph()
h1.paragraph_format.space_before = Pt(6)
h1.paragraph_format.space_after = Pt(3)
r_h1 = h1.add_run('I. Thông tin chung & Phương pháp luận')
r_h1.font.bold = True
r_h1.font.size = Pt(13)
r_h1.font.color.rgb = RGBColor(26, 82, 118)

p1 = doc.add_paragraph(
    'Báo cáo được trích xuất và phân tích tự động từ dữ liệu mua hàng cập nhật mới nhất kỳ 01->10 Tháng 10/2026. '
    'Để phản ánh chính xác tốc độ tiêu thụ và loại bỏ sự chênh lệch do số ngày làm việc giữa các tháng trong năm '
    '(tháng 28 ngày, 30 ngày, 31 ngày và kỳ đầu tháng 10 ngày), toàn bộ số liệu sản lượng đã được quy đổi chuẩn hóa về '
    'chỉ số Sản Lượng Tiêu Thụ Trung Bình Ngày (Kg/ngày). Chỉ số so sánh chính được tính giữa Kỳ T10 (10 ngày) và Tháng 09 (30 ngày).'
)
p1.paragraph_format.space_after = Pt(6)

# II. Kết quả tổng quan toàn công ty
h2 = doc.add_paragraph()
h2.paragraph_format.space_before = Pt(6)
h2.paragraph_format.space_after = Pt(3)
r_h2 = h2.add_run('II. Kết quả tổng quan toàn công ty qua các kỳ')
r_h2.font.bold = True
r_h2.font.size = Pt(13)
r_h2.font.color.rgb = RGBColor(26, 82, 118)

sum_table = doc.add_table(rows=1, cols=6)
sum_table.alignment = WD_TABLE_ALIGNMENT.CENTER
sum_table.autofit = False

sum_headers = [
    'Kỳ Báo Cáo',
    'Tổng Sản Lượng (Kg)',
    'Số Ngày Trong Kỳ',
    'TB / Ngày (Kg/ngày)',
    'So Với Tháng Trước (Kg/ngày)',
    'Tăng/Giảm So Với Tháng Trước (%)'
]

for i, title in enumerate(sum_headers):
    c = sum_table.rows[0].cells[i]
    c.text = title
    p = c.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.runs[0].font.bold = True
    p.runs[0].font.size = Pt(10)
    p.runs[0].font.color.rgb = RGBColor(255, 255, 255)
    set_cell_background(c, '1A5276')
    set_cell_margins(c, top=100, bottom=100, left=80, right=80)

cty_tbs = []
prev_tb = None
for i in range(10):
    tot_val = round(tot_row[i])
    d_num = days[i]
    tb = round(tot_val / d_num)
    cty_tbs.append(tb)
    
    if prev_tb is not None:
        diff = tb - prev_tb
        pct = (diff / prev_tb) * 100
        diff_str = f'{diff:+,}'
        pct_str = f'{pct:+.1f}%'
    else:
        diff = 0
        pct = 0.0
        diff_str = '-'
        pct_str = '-'
        
    row_cells = sum_table.add_row().cells
    row_cells[0].text = month_names[i]
    row_cells[0].paragraphs[0].runs[0].font.bold = True
    row_cells[0].paragraphs[0].runs[0].font.size = Pt(10)
    row_cells[0].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
    
    row_cells[1].text = f'{tot_val:,}'
    row_cells[1].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    row_cells[1].paragraphs[0].runs[0].font.size = Pt(10)
    
    row_cells[2].text = str(d_num)
    row_cells[2].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    row_cells[2].paragraphs[0].runs[0].font.size = Pt(10)
    
    row_cells[3].text = f'{tb:,}'
    row_cells[3].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    row_cells[3].paragraphs[0].runs[0].font.bold = True
    row_cells[3].paragraphs[0].runs[0].font.size = Pt(10)
    
    row_cells[4].text = diff_str
    row_cells[4].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    row_cells[4].paragraphs[0].runs[0].font.size = Pt(10)
    if diff > 0:
        row_cells[4].paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
    elif diff < 0:
        row_cells[4].paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)
        
    row_cells[5].text = pct_str
    row_cells[5].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    row_cells[5].paragraphs[0].runs[0].font.bold = True
    row_cells[5].paragraphs[0].runs[0].font.size = Pt(10)
    if diff > 0:
        row_cells[5].paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
    elif diff < 0:
        row_cells[5].paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)
        
    bg = 'EAF2F8' if i == 9 else ('F4F6F7' if i % 2 == 1 else 'FFFFFF')
    for cell in row_cells:
        set_cell_background(cell, bg)
        set_cell_margins(cell, top=70, bottom=70, left=80, right=80)
        
    prev_tb = tb

sum_widths = [Inches(2.2), Inches(1.7), Inches(1.1), Inches(1.8), Inches(1.8), Inches(1.8)]
for row in sum_table.rows:
    for idx, width in enumerate(sum_widths):
        row.cells[idx].width = width

# Nhận xét đánh giá
diff_cty = cty_tbs[9] - cty_tbs[8]
pct_cty = (diff_cty / cty_tbs[8]) * 100

p_nx = doc.add_paragraph()
p_nx.paragraph_format.space_before = Pt(6)
p_nx.paragraph_format.space_after = Pt(8)
r_nx_title = p_nx.add_run('Đánh giá tổng quát: ')
r_nx_title.font.bold = True
r_nx_title.font.color.rgb = RGBColor(26, 82, 118)

nx_desc = (
    f'Trong 10 ngày đầu Tháng 10/2026 (01/10 - 10/10/2026), toàn công ty đạt tổng sản lượng {round(tot_row[9]):,} Kg, '
    f'tương đương mức tiêu thụ bình quân đạt {cty_tbs[9]:,} Kg/ngày. '
    f'So với Tháng 09/2026 ({cty_tbs[8]:,} Kg/ngày), lượng tiêu thụ trung bình ngày ghi nhận mức '
    f'TĂNG TRƯỞNG {diff_cty:+,} Kg/ngày ({pct_cty:+.1f}%). '
    f'Tốc độ bán hàng 10 ngày đầu Tháng 10 duy trì ở mức cao và ổn định, vượt bình quân Tháng 9.'
)
p_nx.add_run(nx_desc)

# III. Chi tiết từng khách hàng
h3 = doc.add_paragraph()
h3.paragraph_format.space_before = Pt(8)
h3.paragraph_format.space_after = Pt(3)
r_h3 = h3.add_run('III. Bảng so sánh chi tiết theo từng khách hàng')
r_h3.font.bold = True
r_h3.font.size = Pt(13)
r_h3.font.color.rgb = RGBColor(26, 82, 118)

p_detail_intro = doc.add_paragraph(
    f'Bảng tổng hợp chi tiết lượng bán trung bình ngày của toàn bộ {len(customers)} khách hàng qua 9 tháng đầu năm '
    f'và kỳ 10 ngày đầu Tháng 10/2026, cùng mức chênh lệch giữa Kỳ T10 so với Tháng 09/2026:'
)
p_detail_intro.paragraph_format.space_after = Pt(4)

detail_table = doc.add_table(rows=1, cols=15)
detail_table.alignment = WD_TABLE_ALIGNMENT.CENTER
detail_table.autofit = False

d_headers = ['STT', 'Mã KH', 'Tên Khách Hàng'] + short_headers + ['Chênh Lệch (Kg/ngày)', 'Tăng/Giảm (%)']
for i, title in enumerate(d_headers):
    c = detail_table.rows[0].cells[i]
    c.text = title
    p = c.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.runs[0].font.bold = True
    p.runs[0].font.size = Pt(8.0)
    p.runs[0].font.color.rgb = RGBColor(255, 255, 255)
    set_cell_background(c, '1A5276')
    set_cell_margins(c, top=60, bottom=60, left=30, right=30)

growth_records = []
for idx, cust in enumerate(customers, 1):
    row_cells = detail_table.add_row().cells
    
    # STT
    row_cells[0].text = str(cust['stt'] or idx)
    row_cells[0].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    row_cells[0].paragraphs[0].runs[0].font.size = Pt(7.5)
    
    # Mã KH
    row_cells[1].text = cust['ma']
    row_cells[1].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
    row_cells[1].paragraphs[0].runs[0].font.size = Pt(7.5)
    
    # Tên KH
    row_cells[2].text = cust['ten']
    row_cells[2].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
    row_cells[2].paragraphs[0].runs[0].font.size = Pt(7.5)
    
    cust_tbs = []
    for m_i in range(10):
        s_val = cust['sales'][m_i]
        tb_val = round(s_val / days[m_i])
        cust_tbs.append(tb_val)
        
        target_cell = row_cells[3 + m_i]
        target_cell.text = f'{tb_val:,}' if tb_val > 0 else '-'
        target_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
        target_cell.paragraphs[0].runs[0].font.size = Pt(7.5)
        if m_i == 9:
            target_cell.paragraphs[0].runs[0].font.bold = True
            
    tb_p = cust_tbs[8] # T9
    tb_c = cust_tbs[9] # T10
    d_kg = tb_c - tb_p
    d_pct = (d_kg / tb_p * 100) if tb_p > 0 else (100.0 if tb_c > 0 else 0.0)
    
    growth_records.append({
        'ma': cust['ma'],
        'ten': cust['ten'],
        'tb_p': tb_p,
        'tb_c': tb_c,
        'd_kg': d_kg,
        'd_pct': d_pct
    })
    
    # Chênh lệch Kg
    c_diff = row_cells[13]
    c_diff.text = f'{d_kg:+,}' if d_kg != 0 else '-'
    c_diff.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    c_diff.paragraphs[0].runs[0].font.size = Pt(7.5)
    if d_kg > 0:
        c_diff.paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
    elif d_kg < 0:
        c_diff.paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)
        
    # Chênh lệch %
    c_pct = row_cells[14]
    pct_text = f'{d_pct:+.1f}%' if (tb_p > 0 or tb_c > 0) else '-'
    c_pct.text = pct_text
    c_pct.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    c_pct.paragraphs[0].runs[0].font.size = Pt(7.5)
    c_pct.paragraphs[0].runs[0].font.bold = True
    if d_kg > 0:
        c_pct.paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
    elif d_kg < 0:
        c_pct.paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)
        
    bg_r = 'F9FBFB' if idx % 2 == 0 else 'FFFFFF'
    for cell in row_cells:
        set_cell_background(cell, bg_r)
        set_cell_margins(cell, top=35, bottom=35, left=20, right=20)

# Dòng Tổng cộng Table 2
tot_cells = detail_table.add_row().cells
tot_cells[0].text = ''
tot_cells[1].text = 'TC'
tot_cells[1].paragraphs[0].runs[0].font.bold = True
tot_cells[1].paragraphs[0].runs[0].font.size = Pt(8.0)
tot_cells[2].text = 'TỔNG CỘNG TOÀN CÔNG TY'
tot_cells[2].paragraphs[0].runs[0].font.bold = True
tot_cells[2].paragraphs[0].runs[0].font.size = Pt(8.0)

for m_i in range(10):
    tot_val = round(tot_row[m_i])
    t_tb = round(tot_val / days[m_i])
    target_c = tot_cells[3 + m_i]
    target_c.text = f'{t_tb:,}'
    target_c.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
    target_c.paragraphs[0].runs[0].font.bold = True
    target_c.paragraphs[0].runs[0].font.size = Pt(8.0)

tot_cells[13].text = f'{diff_cty:+,}'
tot_cells[13].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
tot_cells[13].paragraphs[0].runs[0].font.bold = True
tot_cells[13].paragraphs[0].runs[0].font.size = Pt(8.0)
if diff_cty > 0:
    tot_cells[13].paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
elif diff_cty < 0:
    tot_cells[13].paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)

tot_cells[14].text = f'{pct_cty:+.1f}%'
tot_cells[14].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
tot_cells[14].paragraphs[0].runs[0].font.bold = True
tot_cells[14].paragraphs[0].runs[0].font.size = Pt(8.0)
if diff_cty > 0:
    tot_cells[14].paragraphs[0].runs[0].font.color.rgb = RGBColor(39, 174, 96)
elif diff_cty < 0:
    tot_cells[14].paragraphs[0].runs[0].font.color.rgb = RGBColor(192, 57, 43)

for cell in tot_cells:
    set_cell_background(cell, 'EAECEE')
    set_cell_margins(cell, top=60, bottom=60, left=20, right=20)

# Column widths for detail table
detail_widths = [Inches(0.35), Inches(0.65), Inches(2.10)]
for _ in range(10):
    detail_widths.append(Inches(0.58))
detail_widths.extend([Inches(0.85), Inches(0.74)])

for row in detail_table.rows:
    for idx, w in enumerate(detail_widths):
        row.cells[idx].width = w

# IV. Phân tích Top biến động
doc.add_paragraph()
h4 = doc.add_paragraph()
h4.paragraph_format.space_before = Pt(8)
h4.paragraph_format.space_after = Pt(3)
r_h4 = h4.add_run('IV. Phân tích Top biến động sản lượng tiêu thụ (Kỳ T10 vs Tháng 09)')
r_h4.font.bold = True
r_h4.font.size = Pt(13)
r_h4.font.color.rgb = RGBColor(26, 82, 118)

valid_records = [r for r in growth_records if r['d_kg'] != 0]
top_inc = sorted(valid_records, key=lambda x: x['d_kg'], reverse=True)[:5]
top_dec = sorted(valid_records, key=lambda x: x['d_kg'])[:5]

p_top_inc = doc.add_paragraph()
p_top_inc.paragraph_format.space_after = Pt(2)
r_inc_t = p_top_inc.add_run('1. Top 5 Khách hàng tăng trưởng sản lượng lớn nhất (Kg/ngày):')
r_inc_t.font.bold = True
r_inc_t.font.color.rgb = RGBColor(39, 174, 96)

for idx, k in enumerate(top_inc, 1):
    p_item = doc.add_paragraph(
        f'   {idx}. {k["ten"]} ({k["ma"]}): TB Tháng 09 = {k["tb_p"]:,} Kg/ngày → Kỳ T10 = {k["tb_c"]:,} Kg/ngày '
        f'(Tăng {k["d_kg"]:+,} Kg/ngày, {k["d_pct"]:+.1f}%)'
    )
    p_item.paragraph_format.space_after = Pt(2)

p_top_dec = doc.add_paragraph()
p_top_dec.paragraph_format.space_before = Pt(4)
p_top_dec.paragraph_format.space_after = Pt(2)
r_dec_t = p_top_dec.add_run('2. Top 5 Khách hàng sụt giảm sản lượng nhiều nhất (Kg/ngày):')
r_dec_t.font.bold = True
r_dec_t.font.color.rgb = RGBColor(192, 57, 43)

for idx, k in enumerate(top_dec, 1):
    p_item = doc.add_paragraph(
        f'   {idx}. {k["ten"]} ({k["ma"]}): TB Tháng 09 = {k["tb_p"]:,} Kg/ngày → Kỳ T10 = {k["tb_c"]:,} Kg/ngày '
        f'(Giảm {k["d_kg"]:+,} Kg/ngày, {k["d_pct"]:+.1f}%)'
    )
    p_item.paragraph_format.space_after = Pt(2)

os.makedirs('Bao_cao', exist_ok=True)
out_docx = os.path.join('Bao_cao', 'BAO_CAO_SO_SANH_MUA_HANG_T10_ky10.docx')
doc.save(out_docx)
print(f'Successfully generated DOCX report at: {out_docx}')
print(f'File size: {os.path.getsize(out_docx)} bytes')
