# -*- coding: utf-8 -*-
"""
Làm sạch báo cáo mua hàng tháng 7: MUA HÀNG T7-26.xlsx
Các bước thực hiện:
1. Giữ lại sheet "FILE GỐC", xóa các sheet phụ khác.
2. Thêm "(Khối lượng Kg)" vào tiêu đề các cột số liệu từ cột 4 đến cột cuối cùng.
3. Định dạng Font chữ Times New Roman (Header 10pt Bold, Data 10pt).
4. Căn lề và thiết lập định dạng số nguyên cho các cột số liệu.
5. Thiết lập độ rộng cột chuẩn: STT(5), Mã KH(14), Tên KH(50), các cột Tháng(14), cột Tuần cuối(18).
6. Lưu kết quả vào thư mục File-lam-sach/.
"""
import openpyxl
from openpyxl.styles import Font, Alignment
from openpyxl.utils import get_column_letter
import os
import sys

sys.stdout.reconfigure(encoding='utf-8')

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_FILE = os.path.join(BASE_DIR, "MUA HÀNG T7- 26.xlsx") if os.path.exists(os.path.join(BASE_DIR, "MUA HÀNG T7- 26.xlsx")) else os.path.join(BASE_DIR, "MUA HÀNG T7-26.xlsx")
OUTPUT_DIR = os.path.join(BASE_DIR, "File-lam-sach")

os.makedirs(OUTPUT_DIR, exist_ok=True)

def clean_report(file_path, output_dir):
    basename = os.path.basename(file_path)
    print(f"Bắt đầu xử lý file: {basename}")
    
    # Mở file excel
    wb = openpyxl.load_workbook(file_path)
    
    # Tìm sheet FILE GỐC
    target_sheet = None
    for name in wb.sheetnames:
        if "FILE GỐC" in name.upper() or "FILE GOC" in name.upper():
            target_sheet = name
            break
            
    if not target_sheet:
        # Nếu không có sheet FILE GỐC, lấy sheet nhiều dòng nhất
        target_sheet = max(wb.sheetnames, key=lambda s: wb[s].max_row)
        
    print(f"Sheet được giữ lại: {target_sheet}")
    
    # Xóa các sheet còn lại
    for name in list(wb.sheetnames):
        if name != target_sheet:
            print(f"Xóa sheet phụ: {name}")
            del wb[name]
            
    ws = wb[target_sheet]
    max_row = ws.max_row
    max_col = ws.max_column
    
    # Sửa header dòng 4 (cột 4 đến cuối)
    for c in range(4, max_col + 1):
        cell = ws.cell(4, c)
        val = str(cell.value or "").replace("\n", " ").strip()
        if val and "(Khối lượng" not in val:
            cell.value = f"{val} (Khối lượng Kg)"
            
    # Fonts & Styles
    header_font = Font(name="Times New Roman", size=10, bold=True)
    data_font = Font(name="Times New Roman", size=10)
    
    # Định dạng dòng header (dòng 4)
    for c in range(1, max_col + 1):
        cell = ws.cell(4, c)
        cell.font = header_font
        cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        
    # Định dạng dữ liệu (từ dòng 5 đến hết)
    for r in range(5, max_row + 1):
        for c in range(1, max_col + 1):
            cell = ws.cell(r, c)
            cell.font = data_font
            
            # Cột số liệu (cột 4 trở đi)
            if c >= 4:
                cell.alignment = Alignment(horizontal="right")
                if cell.value is not None:
                    # Chuyển đổi về dạng số nguyên nếu có thể
                    try:
                        clean_val = str(cell.value).replace(",", "").strip()
                        if clean_val:
                            cell.value = int(float(clean_val))
                    except ValueError:
                        pass
                        
    # Đặt độ rộng cột
    for c in range(1, max_col + 1):
        col_letter = get_column_letter(c)
        if c == 1:
            ws.column_dimensions[col_letter].width = 5
        elif c == 2:
            ws.column_dimensions[col_letter].width = 14
        elif c == 3:
            ws.column_dimensions[col_letter].width = 50
        elif 4 <= c < max_col:
            ws.column_dimensions[col_letter].width = 14
        elif c == max_col:
            ws.column_dimensions[col_letter].width = 18
            
    # Lưu file kết quả
    out_name = f"MUA_HANG_T7-26_DA-LAM-SACH.xlsx"
    out_path = os.path.join(output_dir, out_name)
    wb.save(out_path)
    
    print(f"Đã lưu kết quả tại: {out_path}")
    print(f"Tổng số dòng: {max_row - 4} khách hàng.")

if __name__ == "__main__":
    clean_report(INPUT_FILE, OUTPUT_DIR)
