from django.contrib.admin.sites import AdminSite
from django.contrib.auth import get_user_model
from django.test import RequestFactory, TestCase

from basic_info import models as basic_models
from printing import admin as printing_admin
from printing import models as printing_models
from stateflow import models as stateflow_models

User = get_user_model()


class PrintingJobAdminSearchTestCase(TestCase):
    def setUp(self):
        self.site = AdminSite()
        self.factory = RequestFactory()
        self.admin_user = User.objects.create_superuser(
            username='admin',
            email='admin@example.com',
            password='testpass123',
        )

        self.merchant = basic_models.Merchant.objects.create(
            name='测试印花厂',
            type=basic_models.MerchantTypeEnum.FACTORY,
        )
        self.customer = basic_models.Customer.objects.create(
            merchant=self.merchant,
            name='测试客户',
        )
        self.category = basic_models.ProductCategory.objects.create(
            merchant=self.merchant,
            name='测试分类',
        )
        self.product = basic_models.Product.objects.create(
            merchant=self.merchant,
            category=self.category,
            name='测试产品',
            human_id='TEST001',
            unit=basic_models.ProductUnitEnum.METER,
        )
        self.process = stateflow_models.Process.objects.create(name='测试流程')
        self.order = printing_models.PrintingOrder.objects.create(
            customer=self.customer,
            fabric='测试布料',
            width='150cm',
            process=self.process,
            external_order_id='KD20432371',
        )
        self.job = printing_models.PrintingJob.objects.create(
            printing_order=self.order,
            product=self.product,
            quantity=10,
            unit='米',
            size='10x10',
            pieces=1,
        )

    def test_search_by_external_order_id_does_not_raise_and_returns_job(self):
        model_admin = printing_admin.PrintingJobAdmin(printing_models.PrintingJob, self.site)
        request = self.factory.get('/admin/printing/printingjob/', {'q': 'KD20432371'})
        request.user = self.admin_user

        queryset, may_have_duplicates = model_admin.get_search_results(
            request,
            printing_models.PrintingJob.objects.all(),
            'KD20432371',
        )

        self.assertFalse(may_have_duplicates)
        self.assertEqual(list(queryset), [self.job])

    def test_printing_job_admin_uses_autocomplete_for_large_relations(self):
        model_admin = printing_admin.PrintingJobAdmin(printing_models.PrintingJob, self.site)

        self.assertEqual(
            model_admin.autocomplete_fields,
            (
                'merchant',
                'printing_order',
                'product',
                'business_object',
                'created_by',
            ),
        )
