from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Q, Sum
from django.utils import timezone
from datetime import datetime, timedelta
import json
from .models import *
from .forms import *
from .cookie_forms import PlatformCookieForm
from .utils import *


def index(request):
    """首页"""
    services = Service.objects.filter(is_active=True)
    company = CompanyInfo.objects.first()
    context = {
        'services': services,
        'company': company,
    }
    return render(request, 'portal/index.html', context)


def about(request):
    """关于我们"""
    company = CompanyInfo.objects.first()
    services = Service.objects.filter(is_active=True)
    context = {
        'company': company,
        'services': services,
    }
    return render(request, 'portal/about.html', context)


def services(request):
    """服务项目"""
    services = Service.objects.filter(is_active=True)
    context = {
        'services': services,
    }
    return render(request, 'portal/services.html', context)


def contact(request):
    """联系我们"""
    company = CompanyInfo.objects.first()

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '您的留言已成功提交，我们会尽快与您联系！')
            return redirect('contact')
    else:
        form = ContactForm()

    context = {
        'company': company,
        'form': form,
    }
    return render(request, 'portal/contact.html', context)


@login_required
def admin_dashboard(request):
    """后台管理首页"""
    # 统计数据
    stats = {
        'products': Product.objects.count(),
        'customers': Customer.objects.count(),
        'quotations': Quotation.objects.count(),
        'messages': ContactMessage.objects.filter(is_read=False).count(),
        'recent_quotations': Quotation.objects.order_by('-created_at')[:5],
        'recent_messages': ContactMessage.objects.order_by('-created_at')[:5],
    }
    return render(request, 'admin/dashboard.html', stats)


@login_required
def price_list(request):
    """价格管理"""
    category_id = request.GET.get('category')
    search = request.GET.get('search', '')

    products = Product.objects.filter(is_active=True)

    if category_id:
        products = products.filter(category_id=category_id)

    if search:
        products = products.filter(
            Q(name__icontains=search) |
            Q(brand__icontains=search) |
            Q(model__icontains=search)
        )

    categories = ProductCategory.objects.all()

    # 获取每个产品的最新价格
    for product in products:
        product.latest_price = product.price_records.filter(is_valid=True).first()

    context = {
        'products': products,
        'categories': categories,
        'selected_category': category_id,
        'search': search,
    }
    return render(request, 'admin/price_list.html', context)


@login_required
def fetch_prices(request):
    """获取价格（手动或自动）"""
    if request.method == 'POST':
        try:
            from .scrapers import get_product_price
            
            product_ids = request.POST.getlist('product_ids[]')
            platform = request.POST.get('platform', 'jd')
            
            if not product_ids:
                return JsonResponse({'status': 'error', 'message': '请选择要获取价格的产品'})

            updated_count = 0
            failed_count = 0
            results = []
            
            for product_id in product_ids:
                try:
                    product = Product.objects.get(id=product_id)
                    
                    # 使用爬虫获取实际价格
                    price = get_product_price(
                        product_name=product.name,
                        product_model=product.model or "",
                        platform=platform
                    )
                    
                    if price > 0:
                        # 创建价格记录
                        price_record = PriceRecord.objects.create(
                            product=product,
                            platform=platform,
                            price=price,
                            created_by=request.user
                        )
                        updated_count += 1
                        results.append({
                            'product': product.name,
                            'price': price,
                            'status': 'success'
                        })
                    else:
                        failed_count += 1
                        results.append({
                            'product': product.name,
                            'price': 0,
                            'status': 'failed',
                            'error': '未找到价格信息'
                        })
                        
                except Product.DoesNotExist:
                    failed_count += 1
                    results.append({
                        'product': f'ID:{product_id}',
                        'price': 0,
                        'status': 'failed',
                        'error': '产品不存在'
                    })
                except Exception as e:
                    failed_count += 1
                    results.append({
                        'product': product.name if 'product' in locals() else f'ID:{product_id}',
                        'price': 0,
                        'status': 'failed',
                        'error': str(e)
                    })

            # 构建返回消息
            message = f'完成价格获取：成功{updated_count}个'
            if failed_count > 0:
                message += f'，失败{failed_count}个'

            return JsonResponse({
                'status': 'success' if updated_count > 0 else 'warning',
                'message': message,
                'results': results,
                'updated_count': updated_count,
                'failed_count': failed_count
            })
            
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': f'获取价格失败: {str(e)}'})

    return JsonResponse({'status': 'error', 'message': '请求方法错误'})


@login_required
def order_builder(request):
    """订单组合/报价单创建"""
    if request.method == 'POST':
        # 创建报价单
        customer_id = request.POST.get('customer_id')
        items_data = json.loads(request.POST.get('items', '[]'))

        customer = get_object_or_404(Customer, id=customer_id)

        quotation = Quotation.objects.create(
            customer=customer,
            title=request.POST.get('title', ''),
            created_by=request.user
        )

        total = 0
        for item in items_data:
            product = Product.objects.get(id=item['product_id'])
            quotation_item = QuotationItem.objects.create(
                quotation=quotation,
                product=product,
                quantity=item['quantity'],
                unit_price=item['price'],
                discount_rate=item.get('discount', 0)
            )
            total += quotation_item.subtotal

        quotation.total_amount = total
        quotation.save()

        return JsonResponse({
            'status': 'success',
            'quotation_id': quotation.id,
            'quotation_no': quotation.quotation_no
        })

    # GET请求
    products = Product.objects.filter(is_active=True)
    customers = Customer.objects.all()
    categories = ProductCategory.objects.all()

    context = {
        'products': products,
        'customers': customers,
        'categories': categories,
    }
    return render(request, 'admin/order_builder.html', context)


@login_required
def quotation_preview(request, quotation_id):
    """报价单预览"""
    quotation = get_object_or_404(Quotation, id=quotation_id)
    company = CompanyInfo.objects.first()

    context = {
        'quotation': quotation,
        'company': company,
    }
    return render(request, 'admin/quotation_preview.html', context)


@login_required
def generate_pdf(request, quotation_id):
    """生成PDF报价单"""
    from .utils import generate_quotation_pdf

    quotation = get_object_or_404(Quotation, id=quotation_id)
    pdf_buffer = generate_quotation_pdf(quotation)

    response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
    response['Content-Disposition'] = f'attachment; filename="{quotation.quotation_no}.pdf"'

    return response


@login_required
def api_get_product_price(request, product_id):
    """API：获取产品最新价格"""
    product = get_object_or_404(Product, id=product_id)
    latest_price = product.price_records.filter(is_valid=True).first()

    if latest_price:
        data = {
            'price': float(latest_price.price),
            'platform': latest_price.platform,
            'fetched_at': latest_price.fetched_at.strftime('%Y-%m-%d %H:%M')
        }
    else:
        data = {'price': 0, 'message': '暂无价格信息'}

    return JsonResponse(data)


@login_required
def api_get_products(request):
    """API：获取所有产品列表"""
    products = Product.objects.filter(is_active=True)
    
    product_list = []
    for product in products:
        latest_price = product.price_records.filter(is_valid=True).first()
        product_list.append({
            'id': product.id,
            'name': product.name,
            'brand': product.brand,
            'model': product.model,
            'category': product.category.name if product.category else '',
            'price': float(latest_price.price) if latest_price else 0.0,
            'unit': product.unit
        })
    
    return JsonResponse(product_list, safe=False)


@login_required
def api_get_customers(request):
    """API：获取所有客户列表"""
    customers = Customer.objects.all()
    
    customer_list = []
    for customer in customers:
        customer_list.append({
            'id': customer.id,
            'name': customer.name,
            'contact_person': customer.contact_person,
            'phone': customer.phone,
            'email': customer.email
        })
    
    return JsonResponse(customer_list, safe=False)


@login_required
def api_search_products(request):
    """API：搜索产品"""
    query = request.GET.get('q', '')
    
    products = Product.objects.filter(is_active=True)
    if query:
        products = products.filter(
            Q(name__icontains=query) |
            Q(brand__icontains=query) |
            Q(model__icontains=query)
        )
    
    product_list = []
    for product in products:
        latest_price = product.price_records.filter(is_valid=True).first()
        product_list.append({
            'id': product.id,
            'name': product.name,
            'brand': product.brand,
            'model': product.model,
            'price': float(latest_price.price) if latest_price else 0.0
        })
    
    return JsonResponse(product_list, safe=False)


@login_required
def api_get_customer_detail(request, customer_id):
    """API：获取客户详情"""
    customer = get_object_or_404(Customer, id=customer_id)
    
    data = {
        'id': customer.id,
        'name': customer.name,
        'contact_person': customer.contact_person,
        'phone': customer.phone,
        'email': customer.email,
        'address': customer.address,
        'company_info': customer.company_info
    }
    
    return JsonResponse(data)


@login_required
def api_get_product_detail(request, product_id):
    """API：获取产品详情"""
    product = get_object_or_404(Product, id=product_id)
    latest_price = product.price_records.filter(is_valid=True).first()
    
    data = {
        'id': product.id,
        'name': product.name,
        'brand': product.brand,
        'model': product.model,
        'category': product.category.name if product.category else '',
        'specifications': product.specifications,
        'unit': product.unit,
        'price': float(latest_price.price) if latest_price else 0.0,
        'platform': latest_price.platform if latest_price else ''
    }
    
    return JsonResponse(data)


@login_required
def debug_csrf(request):
    """调试CSRF token"""
    return JsonResponse({
        'csrf_token': str(request.COOKIES.get('csrftoken', '')),
        'meta_csrf': str(request.META.get('CSRF_COOKIE', '')),
        'headers': dict(request.headers),
        'user': request.user.username
    })


@login_required
def cookie_management(request):
    """Cookie管理页面"""
    cookies = PlatformCookie.objects.filter(created_by=request.user).order_by('-updated_at')
    
    if request.method == 'POST':
        form = PlatformCookieForm(request.POST)
        if form.is_valid():
            cookie = form.save(commit=False)
            cookie.created_by = request.user
            cookie.save()
            messages.success(request, 'Cookie添加成功！')
            return redirect('cookie_management')
    else:
        form = PlatformCookieForm()
    
    context = {
        'cookies': cookies,
        'form': form,
    }
    return render(request, 'admin/cookie_management.html', context)


@login_required
def delete_cookie(request, cookie_id):
    """删除Cookie"""
    try:
        cookie = PlatformCookie.objects.get(id=cookie_id, created_by=request.user)
        cookie.delete()
        messages.success(request, 'Cookie删除成功！')
    except PlatformCookie.DoesNotExist:
        messages.error(request, 'Cookie不存在或无权删除')
    
    return redirect('cookie_management')


@login_required
def toggle_cookie(request, cookie_id):
    """启用/禁用Cookie"""
    try:
        cookie = PlatformCookie.objects.get(id=cookie_id, created_by=request.user)
        cookie.is_active = not cookie.is_active
        cookie.save()
        
        status = '启用' if cookie.is_active else '禁用'
        messages.success(request, f'Cookie已{status}！')
    except PlatformCookie.DoesNotExist:
        messages.error(request, 'Cookie不存在或无权操作')
    
    return redirect('cookie_management')


@login_required
def generated_orders(request):
    """已生成订单管理"""
    # 获取搜索和筛选参数
    search = request.GET.get('search', '')
    status_filter = request.GET.get('status', '')
    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    
    # 获取所有报价单
    quotations = Quotation.objects.all().order_by('-created_at')
    
    # 应用筛选条件
    if search:
        quotations = quotations.filter(
            Q(quotation_no__icontains=search) |
            Q(customer__name__icontains=search) |
            Q(title__icontains=search)
        )
    
    if status_filter:
        quotations = quotations.filter(status=status_filter)
    
    if date_from:
        quotations = quotations.filter(created_at__date__gte=date_from)
    
    if date_to:
        quotations = quotations.filter(created_at__date__lte=date_to)
    
    # 统计数据
    stats = {
        'total_count': quotations.count(),
        'pending_count': quotations.filter(status='pending').count(),
        'approved_count': quotations.filter(status='approved').count(),
        'rejected_count': quotations.filter(status='rejected').count(),
        'total_amount': quotations.aggregate(Sum('total_amount'))['total_amount__sum'] or 0,
    }
    
    context = {
        'quotations': quotations,
        'stats': stats,
        'search': search,
        'status_filter': status_filter,
        'date_from': date_from,
        'date_to': date_to,
        'status_choices': Quotation.STATUS_CHOICES,
    }
    return render(request, 'admin/generated_orders.html', context)