"""
PlateOrder 模型测试
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.utils import timezone
from decimal import Decimal
from printing import models as printing_models
from basic_info import models as basic_models
from stateflow import models as stateflow_models

User = get_user_model()


class PlateOrderModelTestCase(TestCase):
    """测试 PlateOrder 模型"""
    
    def setUp(self):
        """设置测试数据"""
        self.user = User.objects.create_user(username='testuser', password='testpass')
        
        # 创建商户
        self.merchant = basic_models.Merchant.objects.create(
            name='测试印花厂',
            type=basic_models.MerchantTypeEnum.FACTORY
        )
        
        # 创建客户
        self.customer = basic_models.Customer.objects.create(
            merchant=self.merchant,
            name='测试客户',
            mobile='13900139000',
            area='测试地区'
        )
        
        # 创建员工
        self.salesperson = basic_models.Employee.objects.create(
            sys_user=self.user,
            merchant=self.merchant,
            name='销售员',
            mobile='13800138000',
            status=basic_models.EmployeeStatusEnum.ACTIVE
        )
        
        self.merchandiser = basic_models.Employee.objects.create(
            merchant=self.merchant,
            name='跟单员',
            mobile='13800138001',
            status=basic_models.EmployeeStatusEnum.ACTIVE
        )
    
    def test_create_plate_order_basic(self):
        """测试创建基本的开版订单"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES001',
            customer=self.customer,
            plate_type='首版',
            urgency_level='正常',
            style_name='测试款式',
            fabric='纯棉',
            width='150cm',
        )
        
        self.assertIsNotNone(plate_order.id)
        self.assertEqual(plate_order.design_code, 'DES001')
        self.assertEqual(plate_order.customer, self.customer)
        self.assertEqual(plate_order.style_name, '测试款式')
    
    def test_plate_order_with_employees(self):
        """测试带销售员和跟单员的开版订单"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES002',
            customer=self.customer,
            salesperson=self.salesperson,
            merchandiser=self.merchandiser,
            urgency_level='加急',
        )
        
        self.assertEqual(plate_order.salesperson, self.salesperson)
        self.assertEqual(plate_order.merchandiser, self.merchandiser)
        self.assertEqual(plate_order.urgency_level, '加急')
    
    def test_plate_order_with_ratings(self):
        """测试带质量评级的开版订单"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES003',
            customer=self.customer,
            drawing_rating='A',
            color_matching_rating='B',
            sample_rating='A',
            difficulty_rating='高',
            is_mark_frame=True,
        )
        
        self.assertEqual(plate_order.drawing_rating, 'A')
        self.assertEqual(plate_order.color_matching_rating, 'B')
        self.assertEqual(plate_order.sample_rating, 'A')
        self.assertEqual(plate_order.difficulty_rating, '高')
        self.assertTrue(plate_order.is_mark_frame)
    
    def test_plate_order_with_dates(self):
        """测试带时间信息的开版订单"""
        now = timezone.now()
        completion_date = now + timezone.timedelta(days=7)
        required_date = now + timezone.timedelta(days=10)
        
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES004',
            customer=self.customer,
            plate_date=now,
            completion_date=completion_date,
            required_completion_date=required_date,
        )
        
        self.assertIsNotNone(plate_order.plate_date)
        self.assertIsNotNone(plate_order.completion_date)
        self.assertIsNotNone(plate_order.required_completion_date)
    
    def test_plate_order_with_sample_info(self):
        """测试带样品信息的开版订单"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES005',
            customer=self.customer,
            sample_meter='米样1',
            required_sample_meters=Decimal('100.50'),
        )
        
        self.assertEqual(plate_order.sample_meter, '米样1')
        self.assertEqual(plate_order.required_sample_meters, Decimal('100.50'))
    
    def test_plate_order_status_without_business_object(self):
        """测试没有 business_object 时的状态"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES006',
            customer=self.customer,
        )
        
        self.assertEqual(plate_order.status, '')  # 废除"未开始"，显示空字符串
        self.assertFalse(plate_order.is_completed)
        self.assertFalse(plate_order.has_started)  # 因为没有 business_object
        self.assertEqual(plate_order.progress_percentage, 0.0)
    
    def test_plate_order_with_business_object(self):
        """测试带 business_object 的开版订单"""
        # 创建流程
        state1 = stateflow_models.State.objects.create(name='画图')
        state2 = stateflow_models.State.objects.create(name='调色')
        state3 = stateflow_models.State.objects.create(name='套样')
        
        process = stateflow_models.Process.objects.create(name='开版流程')
        process.replace_nodes([state1, state2, state3])
        
        # 创建 BusinessObject
        business_object = stateflow_models.BusinessObject.objects.create(
            name='PlateOrder-Test',
            process=process,
        )
        
        # 创建开版订单
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES007',
            customer=self.customer,
            business_object=business_object,
        )
        
        self.assertIsNotNone(plate_order.business_object)
        self.assertEqual(plate_order.progress_percentage, 0.0)
        
        # 推进一个状态
        from stateflow.services import advance_to_next_state
        advance_to_next_state(business_object, self.user)
        
        # 刷新并检查状态
        plate_order.refresh_from_db()
        self.assertEqual(plate_order.status, state2.name)  # current_state 是下一个待执行的状态（state2）
        self.assertFalse(plate_order.is_completed)
        self.assertTrue(plate_order.has_started)
        self.assertGreater(plate_order.progress_percentage, 0)
    
    def test_plate_order_str(self):
        """测试字符串表示"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES008',
            customer=self.customer,
        )
        
        self.assertEqual(str(plate_order), f'PlateOrder-{plate_order.id}')
    
    def test_plate_order_with_approval_and_order_status(self):
        """测试带审批和订单状态的开版订单"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES009',
            customer=self.customer,
            approval_result='通过',
            is_ordered=True,
            customer_feedback='颜色需要调整',
        )
        
        self.assertEqual(plate_order.approval_result, '通过')
        self.assertTrue(plate_order.is_ordered)
        self.assertEqual(plate_order.customer_feedback, '颜色需要调整')
    
    def test_plate_order_with_invalid_flag(self):
        """测试作废标记"""
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='DES010',
            customer=self.customer,
            is_invalid=True,
        )
        
        self.assertTrue(plate_order.is_invalid)
    
    def test_plate_order_nullable_fields(self):
        """测试可空字段"""
        plate_order = printing_models.PlateOrder.objects.create(
            customer=self.customer,
        )
        
        # 验证所有可空字段都可以为空
        self.assertIsNone(plate_order.design_code)
        self.assertIsNone(plate_order.plate_type)
        self.assertIsNone(plate_order.plate_date)
        self.assertIsNone(plate_order.salesperson)
        self.assertIsNone(plate_order.merchandiser)
        self.assertIsNone(plate_order.business_object)
