"""
测试 PlateOrder timeline 接口的正确性
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from printing import models as printing_models
from stateflow import models as stateflow_models
from stateflow import services as stateflow_services
from basic_info import models as basic_info_models

User = get_user_model()


class PlateOrderTimelineTestCase(TestCase):
    """测试 PlateOrder timeline 接口"""
    
    def setUp(self):
        """设置测试数据"""
        self.user = User.objects.create_user(username='testuser', password='testpass123')
        
        self.merchant = basic_info_models.Merchant.objects.create(
            name='测试商户',
            type=basic_info_models.MerchantTypeEnum.FACTORY
        )
        
        self.customer = basic_info_models.Customer.objects.create(
            name='测试客户',
            merchant=self.merchant
        )
        
        # 创建流程
        self.process = stateflow_models.Process.objects.create(
            name='开版流程测试',
            description='用于测试的开版流程'
        )
        
        # 创建3个状态
        self.state1 = stateflow_models.State.objects.create(name='设计', description='设计阶段')
        self.state2 = stateflow_models.State.objects.create(name='制版', description='制版阶段')
        self.state3 = stateflow_models.State.objects.create(name='验收', description='验收阶段')
        
        # 创建流程节点
        stateflow_models.ProcessNode.objects.create(process=self.process, state=self.state1, order=1)
        stateflow_models.ProcessNode.objects.create(process=self.process, state=self.state2, order=2)
        stateflow_models.ProcessNode.objects.create(process=self.process, state=self.state3, order=3)
        
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
    
    def test_timeline_api_response(self):
        """测试 timeline API 返回的数据结构"""
        # 创建 PlateOrder
        plate_order = printing_models.PlateOrder.objects.create(
            design_code='TEST001',
            customer=self.customer,
            style_name='测试款式',
            process=self.process.id
        )
        
        bo = plate_order.business_object
        
        print(f"\n=== 测试 Timeline API ===")
        
        # 初始状态
        response = self.client.get(f'/api/v1/plate-orders/{plate_order.id}/timeline/')
        self.assertEqual(response.status_code, 200)
        
        print(f"\n初始 timeline:")
        for item in response.data['results']:
            print(f"  - {item['state_name']}: status={item['status']}, order={item['order']}")
        
        # 验证初始状态：都是 not_started
        self.assertEqual(len(response.data['results']), 3)
        self.assertEqual(response.data['results'][0]['status'], 'not_started')
        self.assertEqual(response.data['results'][1]['status'], 'not_started')
        self.assertEqual(response.data['results'][2]['status'], 'not_started')
        
        # 第一次推进
        stateflow_services.advance_to_next_state(bo, self.user)
        plate_order.refresh_from_db()
        
        response = self.client.get(f'/api/v1/plate-orders/{plate_order.id}/timeline/')
        self.assertEqual(response.status_code, 200)
        
        print(f"\n第一次推进后 timeline:")
        for item in response.data['results']:
            print(f"  - {item['state_name']}: status={item['status']}, order={item['order']}")
        
        # 验证：第一个节点已完成，后两个未开始
        self.assertEqual(response.data['results'][0]['status'], 'completed')
        self.assertEqual(response.data['results'][1]['status'], 'not_started')
        self.assertEqual(response.data['results'][2]['status'], 'not_started')
        
        # 第二次推进
        stateflow_services.advance_to_next_state(bo, self.user)
        plate_order.refresh_from_db()
        
        response = self.client.get(f'/api/v1/plate-orders/{plate_order.id}/timeline/')
        self.assertEqual(response.status_code, 200)
        
        print(f"\n第二次推进后 timeline:")
        for item in response.data['results']:
            print(f"  - {item['state_name']}: status={item['status']}, order={item['order']}")
        
        # 验证：前两个节点已完成，最后一个未开始
        self.assertEqual(response.data['results'][0]['status'], 'completed')
        self.assertEqual(response.data['results'][1]['status'], 'completed')
        self.assertEqual(response.data['results'][2]['status'], 'not_started')
        
        # 第三次推进
        stateflow_services.advance_to_next_state(bo, self.user)
        plate_order.refresh_from_db()
        
        response = self.client.get(f'/api/v1/plate-orders/{plate_order.id}/timeline/')
        self.assertEqual(response.status_code, 200)
        
        print(f"\n第三次推进后 timeline:")
        for item in response.data['results']:
            print(f"  - {item['state_name']}: status={item['status']}, order={item['order']}")
        
        # 验证：所有节点都已完成
        self.assertEqual(response.data['results'][0]['status'], 'completed')
        self.assertEqual(response.data['results'][1]['status'], 'completed')
        self.assertEqual(response.data['results'][2]['status'], 'completed')
        
        print(f"\n结论：timeline API 正确显示每个节点的状态")
