import requests
from django.conf import settings
from .models import Order, OrderLine, Stage, Trip

class OdooService:
    def __init__(self):
        self.base_url = f"http://{settings.ODOO_INTERNAL_URL}"
        
    def get_odoo_orders(self, team_uuid):
        """Получить заказы из Odoo API"""
        try:
            url = f"{self.base_url}/fastapi/orders/api/v1/orders/team/{team_uuid}"
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json()
            return []
        except Exception as e:
            print(f"Error fetching from Odoo: {e}")
            return []
    
    def get_odoo_order(self, order_uuid):
        """Получить заказ из Odoo API"""
        try:
            url = f"{self.base_url}/fastapi/orders/api/v1/orders/{order_uuid}"
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json()
            return None
        except Exception as e:
            print(f"Error fetching order from Odoo: {e}")
            return None
    
    def sync_team_orders(self, team_uuid):
        """Синхронизировать заказы команды с Odoo"""
        odoo_orders = self.get_odoo_orders(team_uuid)
        django_orders = []
        
        for odoo_order in odoo_orders:
            # Создаем или обновляем заказ в Django
            order, created = Order.objects.get_or_create(
                uuid=odoo_order['uuid'],
                defaults={
                    'name': odoo_order['name'],
                    'team_uuid': odoo_order['teamUuid'],
                    'user_id': odoo_order['userId'],
                    'source_location_uuid': odoo_order['sourceLocationUuid'],
                    'source_location_name': odoo_order['sourceLocationName'],
                    'destination_location_uuid': odoo_order['destinationLocationUuid'],
                    'destination_location_name': odoo_order['destinationLocationName'],
                    'status': odoo_order['status'],
                    'total_amount': odoo_order['totalAmount'],
                    'currency': odoo_order['currency'],
                    'notes': odoo_order.get('notes', ''),
                }
            )
            
            # Синхронизируем order lines
            self.sync_order_lines(order, odoo_order.get('orderLines', []))
            
            # Синхронизируем stages
            self.sync_stages(order, odoo_order.get('stages', []))
            
            django_orders.append(order)
            
        return django_orders
    
    def sync_order(self, order_uuid):
        """Синхронизировать один заказ с Odoo"""
        odoo_order = self.get_odoo_order(order_uuid)
        if not odoo_order:
            return None
            
        # Создаем или обновляем заказ
        order, created = Order.objects.get_or_create(
            uuid=odoo_order['uuid'],
            defaults={
                'name': odoo_order['name'],
                'team_uuid': odoo_order['teamUuid'],
                'user_id': odoo_order['userId'],
                'source_location_uuid': odoo_order['sourceLocationUuid'],
                'source_location_name': odoo_order['sourceLocationName'],
                'destination_location_uuid': odoo_order['destinationLocationUuid'],
                'destination_location_name': odoo_order['destinationLocationName'],
                'status': odoo_order['status'],
                'total_amount': odoo_order['totalAmount'],
                'currency': odoo_order['currency'],
                'notes': odoo_order.get('notes', ''),
            }
        )
        
        # Синхронизируем связанные данные
        self.sync_order_lines(order, odoo_order.get('orderLines', []))
        self.sync_stages(order, odoo_order.get('stages', []))
        
        return order
    
    def sync_order_lines(self, order, odoo_lines):
        """Синхронизировать строки заказа"""
        # Удаляем старые
        order.order_lines.all().delete()
        
        # Создаем новые
        for line_data in odoo_lines:
            OrderLine.objects.create(
                uuid=line_data['uuid'],
                order=order,
                product_uuid=line_data['productUuid'],
                product_name=line_data['productName'],
                quantity=line_data['quantity'],
                unit=line_data['unit'],
                price_unit=line_data['priceUnit'],
                subtotal=line_data['subtotal'],
                currency=line_data.get('currency', 'RUB'),
                notes=line_data.get('notes', ''),
            )
    
    def sync_stages(self, order, odoo_stages):
        """Синхронизировать этапы заказа"""
        # Удаляем старые
        order.stages.all().delete()
        
        # Создаем новые
        for stage_data in odoo_stages:
            stage = Stage.objects.create(
                uuid=stage_data['uuid'],
                order=order,
                name=stage_data['name'],
                sequence=stage_data['sequence'],
                stage_type=stage_data['stageType'],
                transport_type=stage_data.get('transportType', ''),
                source_location_name=stage_data.get('sourceLocationName', ''),
                destination_location_name=stage_data.get('destinationLocationName', ''),
                location_name=stage_data.get('locationName', ''),
                selected_company_uuid=stage_data.get('selectedCompany', {}).get('uuid', '') if stage_data.get('selectedCompany') else '',
                selected_company_name=stage_data.get('selectedCompany', {}).get('name', '') if stage_data.get('selectedCompany') else '',
            )
            
            # Синхронизируем trips
            self.sync_trips(stage, stage_data.get('trips', []))
    
    def sync_trips(self, stage, odoo_trips):
        """Синхронизировать рейсы этапа"""
        for trip_data in odoo_trips:
            Trip.objects.create(
                uuid=trip_data['uuid'],
                stage=stage,
                name=trip_data['name'],
                sequence=trip_data['sequence'],
                company_uuid=trip_data.get('company', {}).get('uuid', '') if trip_data.get('company') else '',
                company_name=trip_data.get('company', {}).get('name', '') if trip_data.get('company') else '',
                planned_weight=trip_data.get('plannedWeight'),
                weight_at_loading=trip_data.get('weightAtLoading'),
                weight_at_unloading=trip_data.get('weightAtUnloading'),
                planned_loading_date=trip_data.get('plannedLoadingDate'),
                actual_loading_date=trip_data.get('actualLoadingDate'),
                real_loading_date=trip_data.get('realLoadingDate'),
                planned_unloading_date=trip_data.get('plannedUnloadingDate'),
                actual_unloading_date=trip_data.get('actualUnloadingDate'),
                notes=trip_data.get('notes', ''),
            )