from django.db.models import Q
from . import models as basic_models


class CustomerVisibilityService:
    @staticmethod
    def filter_customers_for_employee(customer_queryset, user):
        """
        过滤客户查询集，使其仅包含对指定员工可见的客户。
        """

        if user.is_superuser:
            return customer_queryset

        emp = getattr(user, 'employee', None)
        if emp is None:
            return customer_queryset.none()

        print(f'Filtering customers for employee: {emp.id}')
        # 员工创建的客户可见 + 员工被设置为可见员工的客户可见
        visibility_filter = Q(created_by=emp) | Q(visible_employees=emp)
        return customer_queryset.filter(visibility_filter).distinct()

    @staticmethod
    def is_customer_visible_to_employee(customer, user):
        """
        检查特定客户是否对指定员工可见。
        """

        if user.is_superuser:
            return True

        emp = getattr(user, 'employee', None)
        if emp is None:
            return False

        if customer.created_by == emp:
            return True

        if emp in customer.visible_employees.all():
            return True

        return False


class DataVisibilityService:
    @staticmethod
    def is_product_visible_to_employee(product_id: int, user):
        """
        检查特定产品是否对指定员工可见。
        """

        if user.is_superuser:
            return True

        emp: basic_models.Employee = getattr(user, 'employee', None)
        if emp is None:
            return False

        return basic_models.Product.objects.filter(id=product_id).filter(merchant=emp.merchant).exists()

    @staticmethod
    def is_warehouse_visible_to_employee(warehouse_id: int, user):
        """
        检查特定仓库是否对指定员工可见。
        """

        if user.is_superuser:
            return True

        emp: basic_models.Employee = getattr(user, 'employee', None)
        if emp is None:
            return False

        return basic_models.WareHouse.objects.filter(id=warehouse_id).filter(merchant=emp.merchant).exists()


class MerchantSettingService:
    @staticmethod
    def get_setting(merchant: basic_models.Merchant, key: basic_models.MerchantSettingKeyEnum):
        return basic_models.MerchantSetting.objects.get(merchant=merchant, key=key)
