from django.contrib import admin
from basic_info.services import CustomerVisibilityService
from . import models


class AdminBase(admin.ModelAdmin):
    """管理员基础类，定义通用配置"""

    def get_readonly_fields(self, request, obj = ...):
        readonly_fields = list(super().get_readonly_fields(request, obj))
        if request.user.is_superuser is False and isinstance(obj, models.Employee) is False:
            readonly_fields.append('merchant')
        return readonly_fields

    def get_list_display(self, request):
        result = super().get_list_display(request)
        result = list(result)

        if 'id' not in result:
            result = ['id'] + result
            
        if request.user.is_superuser and 'merchant' not in result:
            result = result + ['merchant']

        return result

    def save_model(self, request, obj, form, change):
        if not change and isinstance(obj, models.Employee) is False:
            if not obj.merchant_id:
                if request.user.is_superuser is False:
                    obj.merchant_id = request.user.employee.merchant.id
        return super().save_model(request, obj, form, change)


@admin.register(models.QuickInput)
class QuickInputAdmin(admin.ModelAdmin):
    list_display = ('name', 'value', 'group')
    list_filter = ('group',)


@admin.register(models.MerchantSetting)
class MerchantSettingAdmin(admin.ModelAdmin):
    list_display = (
        'merchant', 'key', 'value', 
        'type', 'val_str', 'val_int', 
        'val_float', 'val_bool', 'description',
    )
    list_filter = ('merchant', 'type')
    search_fields = ('merchant__name', 'key', 'description')

    @admin.display(description='设置值')
    def _value(self, obj):
        return obj.value()


@admin.register(models.UserProfile)
class UserProfileAdmin(AdminBase):
    list_display = ('user', 'merchant')


@admin.register(models.Merchant)
class MerchantAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'type', 'email', 'mobile', 'auto_complete_stock_change')
    search_fields = ('name', 'mobile')
    list_filter = ('type', 'auto_complete_stock_change')


@admin.register(models.Supplier)
class SupplierAdmin(AdminBase):
    list_display = ('name', 'area', 'email', 'mobile')
    search_fields = ('name', 'area', 'email', 'mobile')


@admin.register(models.ProductCategory)
class ProductCategoryAdmin(AdminBase):
    list_display = ('name', 'product_prefix', 'description')
    search_fields = ('name',)


@admin.register(models.Product)
class ProductAdmin(AdminBase):
    list_display = (
        'name',
        'category',
        'human_id',
        'color',
        'width_size',
        'transform_rate',
        'minimum_quantity',
        'single_price_in',
        'single_price_out',
    )
    search_fields = ('name', 'human_id')
    list_filter = ('category',)


@admin.register(models.BankAccount)
class BankAccountAdmin(AdminBase):
    list_display = ('name', 'auto_number')
    search_fields = ('name', 'auto_number')


@admin.register(models.WareHouse)
class WareHouseAdmin(AdminBase):
    list_display = ('name', 'type', 'location', 'area', 'mobile', 'mode')
    list_filter = ('area', 'mode', 'type')
    search_fields = ('name', 'location', 'mobile')


@admin.register(models.Customer)
class CustomerAdmin(AdminBase):
    list_display = ('name', 'area', 'email', 'mobile', 'created_by', 'total_debt')
    search_fields = ('name', 'area', 'email', 'mobile')

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = CustomerVisibilityService.filter_customers_for_employee(qs, request.user)
        return qs

    @admin.display(boolean=False, description='累欠金额')
    def total_debt(self, obj):
        return '0 (动态逻辑字段待实现)'


@admin.register(models.Employee)
class EmployeeAdmin(AdminBase):
    list_display = ('name', 'mobile', 'status', 'position_display', 'sys_user')
    search_fields = ('name', 'mobile')
    list_filter = (
        'position',
        'status',
    )

    @admin.display(description='职位')
    def position_display(self, obj: models.Employee):
        """显示职位名称"""
        return obj.job_type if obj.position else '-'

    def get_readonly_fields(self, request, obj=...):
        return []


@admin.register(models.EmployeeType)
class EmployeeTypeAdmin(AdminBase):
    list_display = ('id', 'title', 'description', 'visible_pages_count')
    search_fields = ('title', 'description')
    filter_horizontal = ('visible_pages',)  # 便于多对多字段选择

    def get_readonly_fields(self, request, obj=...):
        return []

    @admin.display(description='可见页面数')
    def visible_pages_count(self, obj):
        return obj.visible_pages.count()


@admin.register(models.FrontendPage)
class FrontendPageAdmin(admin.ModelAdmin):
    """
    前端页面管理
    
    注意：此模型不继承 AdminBase，因为 FrontendPage 是全局系统配置，
    不关联 merchant（商户）。
    """
    list_display = ('key', 'label', 'page_type', 'parent', 'sort_order', 'is_active')
    list_filter = ('page_type', 'is_active', 'parent')
    search_fields = ('key', 'label')
    list_editable = ('sort_order', 'is_active')
    ordering = ('sort_order', 'id')
    autocomplete_fields = ('parent',)  # parent 也是 FrontendPage，支持自动完成

    def get_readonly_fields(self, request, obj=None):
        # key 字段创建后不可修改
        if obj:
            return ['key']
        return []


@admin.register(models.DeviceInfo)
class DeviceInfoAdmin(AdminBase):
    list_display = ('name', 'type', 'is_occupied', 'status')
    search_fields = ('name', 'start_working_at', 'stop_working_at')
    list_filter = ('type', 'status')


@admin.register(models.VehicleType)
class VehicleTypeAdmin(AdminBase):
    list_display = ('name', 'description')
    search_fields = ('name',)


@admin.register(models.VehicleTransportRecord)
class VehicleTransportRecordAdmin(AdminBase):
    list_display = ('driver_name', 'contact_number', 'delivery_date')
    search_fields = ('driver_name', 'contact_number')
    list_filter = ('vehicle_type',)


class TransportVehicleMaterialCapacityInline(admin.TabularInline):
    model = models.TransportVehicleMaterialCapacity
    extra = 0
    fields = ('material_name', 'capacity')


@admin.register(models.TransportVehicle)
class TransportVehicleAdmin(AdminBase):
    inlines = [TransportVehicleMaterialCapacityInline]
    list_display = ('name', 'license_plate')
    search_fields = ('name', 'license_plate')

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for obj in formset.deleted_objects:
            obj.delete()
        for instance in instances:
            if isinstance(instance, models.TransportVehicleMaterialCapacity):
                instance.merchant = form.instance.merchant
            instance.save()
        formset.save_m2m()


@admin.register(models.TransportVehicleMaterialCapacity)
class TransportVehicleMaterialCapacityAdmin(AdminBase):
    list_display = ('transport_vehicle', 'material_name', 'capacity')
    search_fields = ('transport_vehicle__name', 'transport_vehicle__license_plate', 'material_name')
    list_filter = ('transport_vehicle',)
