#!/usr/bin/env python3
"""
专业形式发票PDF生成器
适用于外贸SOHO - 车辆翻新出口业务
"""

import os
import json
import sys
from datetime import datetime, timedelta
import pdfkit
from jinja2 import Template

def number_to_words(num):
    """将数字转换为英文大写金额"""
    units = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
    teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 
             'Seventeen', 'Eighteen', 'Nineteen']
    tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
    
    if num == 0:
        return "Zero"
    
    def convert_hundred(n):
        if n == 0:
            return ""
        elif n < 10:
            return units[n]
        elif n < 20:
            return teens[n-10]
        elif n < 100:
            return tens[n//10] + (" " + units[n%10] if n%10 != 0 else "")
        else:
            return units[n//100] + " Hundred" + (" " + convert_hundred(n%100) if n%100 != 0 else "")
    
    result = ""
    if num >= 1000000:
        millions = num // 1000000
        result += convert_hundred(millions) + " Million "
        num %= 1000000
    
    if num >= 1000:
        thousands = num // 1000
        result += convert_hundred(thousands) + " Thousand "
        num %= 1000
    
    if num > 0:
        result += convert_hundred(num)
    
    return result.strip() + " US Dollars"

def generate_sample_data():
    """生成示例数据"""
    today = datetime.now()
    shipment_date = today + timedelta(days=30)
    validity_date = today + timedelta(days=30)
    
    return {
        # 买方信息
        "buyer_name": "Global Trading Solutions Inc.",
        "buyer_address": "789 Business Avenue, Suite 501",
        "buyer_city": "New York",
        "buyer_country": "United States",
        "buyer_phone": "+1 (212) 555-7890",
        "buyer_email": "purchase@globaltrading.com",
        "contact_person": "Mr. John Smith",
        
        # 发票信息
        "invoice_no": f"PI-{today.strftime('%Y%m%d')}-001",
        "invoice_date": today.strftime("%Y-%m-%d"),
        "payment_terms": "T/T 30% in advance, 70% before shipment",
        "delivery_terms": "FOB Shanghai Port, China",
        "port_of_loading": "Shanghai Port, China",
        "port_of_destination": "Los Angeles Port, USA",
        "shipment_date": shipment_date.strftime("%Y-%m-%d"),
        "validity": validity_date.strftime("%Y-%m-%d"),
        
        # 产品信息
        "items": [
            {
                "description": "Renovated Heavy Duty Truck - Model HT-2024\n• Complete renovation including engine, transmission, chassis\n• New tires and brakes\n• Fresh paint and interior",
                "quantity": 3,
                "unit": "Unit",
                "unit_price": 28500.00,
                "hs_code": "87042390"
            },
            {
                "description": "Spare Parts Package\n• Engine spare parts kit\n• Transmission components\n• Electrical system parts",
                "quantity": 1,
                "unit": "Set",
                "unit_price": 3500.00,
                "hs_code": "87089900"
            },
            {
                "description": "Professional Renovation Service\n• Quality inspection and certification\n• Pre-shipment testing\n• Documentation preparation",
                "quantity": 1,
                "unit": "Lot",
                "unit_price": 1200.00,
                "hs_code": "998859"
            }
        ],
        
        # 费用信息
        "subtotal": 0,  # 自动计算
        "shipping_cost": 4500.00,
        "insurance": 850.00,
        "other_charges": 320.00,
        "total_amount": 0,  # 自动计算
        
        # 银行信息 - USD账户
        "bank_name_usd": "Industrial and Commercial Bank of China (ICBC)",
        "account_name_usd": "Saiyoubo Automobile CO.,LTD",
        "account_no_usd": "USD-1234567890123456",
        "swift_code_usd": "ICBKCNBJSHI",
        "bank_address_usd": "No. 123, Pudong Avenue, Shanghai 200120, China",
        
        # 银行信息 - CNY账户
        "bank_name_cny": "Industrial and Commercial Bank of China (ICBC)",
        "account_name_cny": "赛优博汽车有限公司",
        "account_no_cny": "CNY-9876543210987654",
        "swift_code_cny": "ICBKCNBJSHI",
        "bank_address_cny": "上海市浦东大道123号，邮编200120",
        
        # 业务条款
        "delivery_time": "30 working days",
        "price_basis": "FOB Shanghai Port, China",
        "payment_details": "30% deposit by T/T upon order confirmation, 70% balance before shipment",
        "warranty_period": "6 months or 10,000 km",
        "signature_date": today.strftime("%Y-%m-%d")
    }

def calculate_totals(data):
    """计算总计金额"""
    # 计算产品小计
    subtotal = sum(item['quantity'] * item['unit_price'] for item in data['items'])
    data['subtotal'] = subtotal
    
    # 计算总金额
    total = subtotal + data['shipping_cost'] + data['insurance'] + data['other_charges']
    data['total_amount'] = total
    
    # 生成大写金额
    data['amount_in_words'] = number_to_words(int(total))
    
    return data

def generate_invoice_pdf(template_file, data, output_file):
    """生成PDF发票"""
    try:
        # 读取模板
        with open(template_file, 'r', encoding='utf-8') as f:
            template_content = f.read()
        
        # 创建Jinja2模板
        template = Template(template_content)
        
        # 渲染HTML
        html_content = template.render(**data)
        
        # PDF生成选项
        options = {
            'page-size': 'A4',
            'margin-top': '1.5cm',
            'margin-right': '1.5cm',
            'margin-bottom': '1.5cm',
            'margin-left': '1.5cm',
            'encoding': "UTF-8",
            'no-outline': None,
            'enable-local-file-access': None,
            'quiet': ''
        }
        
        # 生成PDF
        pdfkit.from_string(html_content, output_file, options=options)
        
        print(f"✅ 发票已成功生成: {output_file}")
        print(f"📄 发票号: {data['invoice_no']}")
        print(f"💰 总金额: USD {data['total_amount']:,.2f}")
        print(f"👤 买方: {data['buyer_name']}")
        
        return True
        
    except Exception as e:
        print(f"❌ 生成PDF时出错: {str(e)}")
        return False

def save_sample_data(data, filename="sample_invoice_data.json"):
    """保存示例数据到JSON文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"📝 示例数据已保存: {filename}")

def main():
    """主函数"""
    print("=" * 60)
    print("专业形式发票PDF生成器 - Saiyoubo Automobile")
    print("=" * 60)
    
    # 检查wkhtmltopdf是否安装
    if os.system("which wkhtmltopdf > /dev/null 2>&1") != 0:
        print("❌ 未找到 wkhtmltopdf，请先安装:")
        print("   sudo apt-get install wkhtmltopdf")
        return
    
    # 文件路径
    template_file = "proforma_invoice_template.html"
    output_file = f"proforma_invoice_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
    data_file = "sample_invoice_data.json"
    
    # 检查模板文件
    if not os.path.exists(template_file):
        print(f"❌ 模板文件不存在: {template_file}")
        return
    
    # 生成示例数据
    print("\n📋 生成示例发票数据...")
    data = generate_sample_data()
    data = calculate_totals(data)
    
    # 保存示例数据
    save_sample_data(data, data_file)
    
    # 生成PDF
    print("\n🔄 正在生成PDF发票...")
    if generate_invoice_pdf(template_file, data, output_file):
        print("\n" + "=" * 60)
        print("🎉 发票生成完成！")
        print("=" * 60)
        print(f"\n📁 生成的文件:")
        print(f"   • PDF发票: {output_file}")
        print(f"   • 数据文件: {data_file}")
        print(f"   • HTML模板: {template_file}")
        
        print(f"\n📊 发票详情:")
        print(f"   发票号: {data['invoice_no']}")
        print(f"   日期: {data['invoice_date']}")
        print(f"   买方: {data['buyer_name']}")
        print(f"   总金额: USD {data['total_amount']:,.2f}")
        print(f"   大写金额: {data['amount_in_words']}")
        
        print(f"\n🚀 使用方法:")
        print(f"   1. 修改 {data_file} 中的买方和产品信息")
        print(f"   2. 运行: python generate_invoice.py")
        print(f"   3. 或使用自定义数据: python generate_invoice.py your_data.json")
        
        # 显示文件大小
        if os.path.exists(output_file):
            size = os.path.getsize(output_file) / 1024
            print(f"\n📏 PDF文件大小: {size:.1f} KB")
    else:
        print("❌ 发票生成失败")

if __name__ == "__main__":
    # 如果提供了数据文件参数，使用自定义数据
    if len(sys.argv) > 1:
        data_file = sys.argv[1]
        try:
            with open(data_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            data = calculate_totals(data)
            output_file = f"proforma_invoice_{data.get('invoice_no', datetime.now().strftime('%Y%m%d_%H%M%S'))}.pdf"
            generate_invoice_pdf("proforma_invoice_template.html", data, output_file)
        except Exception as e:
            print(f"❌ 加载数据文件出错: {str(e)}")
    else:
        main()