from django.contrib import admin
from .models import (
    ExternalFinishedProduct,
    SalesItem,
    SalesItemChangeRecord,
    SalesItemRebuildRecord,
    Shipment,
    ShipmentDelivery,
)


class SalesItemInline(admin.TabularInline):
    model = SalesItem
    extra = 1
    fields = ['name', 'quantity', 'unit', 'position', 'remark', 'printing_job_id', 'customer_id', 'created_by']
    readonly_fields = ['created_by']


class ExternalFinishedProductInline(admin.TabularInline):
    model = ExternalFinishedProduct
    extra = 1
    fields = ['style_name', 'num_of_rolls', 'remark', 'created_by', 'created_at']
    readonly_fields = ['created_by', 'created_at']


@admin.register(Shipment)
class ShipmentAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'merchant',
        'customer',
        'shipment_date',
        'status',
        'delivery',
        'external_id',
        'items_count',
        'created_by',
        'created_at',
    ]
    list_filter = ['merchant', 'status', 'shipment_date', 'created_at']
    search_fields = [
        'customer__name',
        'remark',
        'external_id',
        'address',
        'contact_name',
        'contact_phone',
    ]
    readonly_fields = ['created_at', 'updated_at', 'created_by']
    raw_id_fields = ['delivery']
    date_hierarchy = 'shipment_date'
    inlines = [SalesItemInline, ExternalFinishedProductInline]
    
    def items_count(self, obj):
        return obj.items.count()
    items_count.short_description = '销售品数量'
    
    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)
    
    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            if isinstance(instance, (SalesItem, ExternalFinishedProduct)) and not instance.pk:
                instance.created_by = request.user
            instance.save()
        formset.save_m2m()


@admin.register(SalesItem)
class SalesItemAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'quantity', 'unit', 'position', 'shipment_status', 'printing_job_id', 'customer_id', 'created_by', 'delete_at', 'delete_by', 'created_at']
    list_filter = ['unit', 'created_at', 'delete_at', ('shipment', admin.EmptyFieldListFilter)]
    search_fields = ['name', 'shipment__customer__name', 'position', 'remark']
    readonly_fields = ['created_at', 'updated_at', 'created_by', 'delete_at', 'delete_by']
    raw_id_fields = ['shipment']
    
    def shipment_status(self, obj):
        if obj.shipment:
            return f'出货单 #{obj.shipment.id}'
        return '待分配'
    shipment_status.short_description = '出货单'
    
    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(ExternalFinishedProduct)
class ExternalFinishedProductAdmin(admin.ModelAdmin):
    list_display = ['id', 'shipment', 'style_name', 'num_of_rolls', 'remark', 'created_by', 'created_at']
    list_filter = ['created_at', ('shipment', admin.EmptyFieldListFilter)]
    search_fields = ['style_name', 'remark', 'shipment__external_id', 'shipment__customer__name']
    readonly_fields = ['created_at', 'updated_at', 'created_by']
    raw_id_fields = ['shipment']

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(SalesItemChangeRecord)
class SalesItemChangeRecordAdmin(admin.ModelAdmin):
    list_display = [
        "id",
        "sales_item",
        "operator",
        "operated_at",
        "created_at",
    ]
    list_filter = ["operated_at", "created_at"]
    search_fields = [
        "sales_item__name",
        "operator__username",
        "operator__employee__name",
    ]
    readonly_fields = [
        "sales_item",
        "operator",
        "operated_at",
        "before_values",
        "after_values",
        "created_at",
        "updated_at",
    ]


@admin.register(SalesItemRebuildRecord)
class SalesItemRebuildRecordAdmin(admin.ModelAdmin):
    list_display = [
        "id",
        "old_sales_item",
        "new_sales_item",
        "operator",
        "old_printing_job_id",
        "new_printing_job_id",
        "rebuilt_at",
    ]
    list_filter = ["rebuilt_at", "created_at"]
    search_fields = [
        "old_sales_item__name",
        "new_sales_item__name",
        "operator__username",
        "operator__employee__name",
    ]
    readonly_fields = [
        "old_sales_item",
        "new_sales_item",
        "operator",
        "rebuilt_at",
        "old_printing_job_id",
        "new_printing_job_id",
        "old_quantity",
        "new_quantity",
        "created_at",
        "updated_at",
    ]


@admin.register(ShipmentDelivery)
class ShipmentDeliveryAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'merchant',
        'driver_name',
        'vehicle_trip',
        'contact_phone',
        'vehicle_capacity',
        'status',
        'shipments_count',
        'operator',
        'cancelled_by',
        'created_by',
        'started_at',
        'delivered_at',
        'cancelled_at',
        'created_at',
    ]
    list_filter = ['merchant', 'status', 'created_at', 'started_at', 'delivered_at', 'cancelled_at']
    search_fields = [
        'driver_name',
        'vehicle_trip',
        'contact_phone',
        'vehicle_capacity',
        'remark',
        'internal_remark',
        'operator__name',
        'cancelled_by__username',
        'created_by__username',
    ]
    readonly_fields = ['created_at', 'updated_at', 'created_by', 'operator', 'cancelled_by', 'cancelled_at', 'shipments_summary']
    fields = [
        'merchant',
        'driver_name',
        'vehicle_trip',
        'contact_phone',
        'vehicle_capacity',
        'remark',
        'internal_remark',
        'status',
        'started_at',
        'delivered_at',
        'cancelled_at',
        'operator',
        'cancelled_by',
        'created_by',
        'shipments_summary',
        'created_at',
        'updated_at',
    ]

    def shipments_count(self, obj):
        return obj.shipments.count()

    shipments_count.short_description = '出货单数量'

    def shipments_summary(self, obj):
        ids = list(obj.shipments.order_by('id').values_list('id', flat=True))
        if not ids:
            return '无'
        return ', '.join(str(item_id) for item_id in ids)

    shipments_summary.short_description = '关联出货单'

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        employee = getattr(request.user, 'employee', None)
        if employee:
            obj.operator = employee
        super().save_model(request, obj, form, change)
