from io import BytesIO
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import requests
from bs4 import BeautifulSoup
import re
from decimal import Decimal

# 注册中文字体（需要下载对应字体文件）
try:
    pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc'))
except:
    pass


def fetch_jd_price(keyword):
    """爬取京东价格（示例）"""
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }

    try:
        # 这里应该使用实际的京东API或爬虫
        # 示例代码，实际需要更复杂的处理
        url = f"https://search.jd.com/Search?keyword={keyword}"
        response = requests.get(url, headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, 'html.parser')

        # 解析价格（需要根据实际页面结构调整）
        price_elements = soup.find_all('div', class_='p-price')
        if price_elements:
            price_text = price_elements[0].text
            price = re.findall(r'[\d.]+', price_text)
            if price:
                return Decimal(price[0])
    except Exception as e:
        print(f"Error fetching price: {e}")

    return None


def generate_quotation_pdf(quotation):
    """生成报价单PDF"""
    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4)
    story = []

    # 样式
    styles = getSampleStyleSheet()
    try:
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontName='SimSun',
            fontSize=24,
            textColor=colors.HexColor('#003366'),
            alignment=1  # 居中
        )
        normal_style = ParagraphStyle(
            'CustomNormal',
            parent=styles['Normal'],
            fontName='SimSun',
            fontSize=11
        )
    except:
        title_style = styles['Heading1']
        normal_style = styles['Normal']

    # 标题
    story.append(Paragraph("报价单", title_style))
    story.append(Spacer(1, 12))

    # 报价单信息
    info_data = [
        ['报价单号：', quotation.quotation_no, '日期：', quotation.created_at.strftime('%Y-%m-%d')],
        ['客户名称：', quotation.customer.name, '联系人：', quotation.customer.contact_person],
        ['联系电话：', quotation.customer.phone, '邮箱：', quotation.customer.email or ''],
    ]

    info_table = Table(info_data, colWidths=[2 * cm, 5 * cm, 2 * cm, 5 * cm])
    info_table.setStyle(TableStyle([
        ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
        ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey),
        ('BACKGROUND', (2, 0), (2, -1), colors.lightgrey),
    ]))
    story.append(info_table)
    story.append(Spacer(1, 20))

    # 产品明细表
    items_data = [['序号', '产品名称', '规格型号', '单位', '数量', '单价', '折扣', '小计']]

    total = Decimal('0')
    for idx, item in enumerate(quotation.items.all(), 1):
        items_data.append([
            str(idx),
            item.product.name,
            item.product.model,
            item.product.unit,
            str(item.quantity),
            f"¥{item.unit_price:.2f}",
            f"{item.discount_rate}%",
            f"¥{item.subtotal:.2f}"
        ])
        total += item.subtotal

    # 添加合计行
    items_data.append(['', '', '', '', '', '', '合计：', f"¥{total:.2f}"])

    items_table = Table(items_data, colWidths=[1 * cm, 4 * cm, 3 * cm, 1.5 * cm, 1.5 * cm, 2 * cm, 1.5 * cm, 2.5 * cm])
    items_table.setStyle(TableStyle([
        ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#003366')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
        ('BACKGROUND', (0, -1), (-1, -1), colors.lightgrey),
        ('SPAN', (0, -1), (5, -1)),
        ('ALIGN', (0, -1), (5, -1), 'RIGHT'),
    ]))
    story.append(items_table)
    story.append(Spacer(1, 20))

    # 备注
    if quotation.remark:
        story.append(Paragraph("备注：", normal_style))
        story.append(Paragraph(quotation.remark, normal_style))

    # 生成PDF
    doc.build(story)
    buffer.seek(0)
    return buffer


def auto_fetch_prices():
    """自动获取价格（定时任务）"""
    from .models import Product, PriceRecord

    products = Product.objects.filter(is_active=True)

    for product in products:
        # 构建搜索关键词
        keyword = f"{product.brand} {product.name} {product.model}".strip()

        # 获取京东价格
        jd_price = fetch_jd_price(keyword)
        if jd_price:
            PriceRecord.objects.create(
                product=product,
                platform='jd',
                price=jd_price,
                url='',
                supplier='京东自营'
            )

        # 可以添加其他平台的价格获取

    return True