#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
================================================================================
Модуль: Рейс-Экспресс
================================================================================
Калькулятор рейса с тремя тарифами (за тонну, т/км, почасовая)
================================================================================
"""

from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QLineEdit, QPushButton, QGroupBox, QGridLayout,
    QSpinBox, QDoubleSpinBox, QCheckBox, QRadioButton, QButtonGroup,
    QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox,
    QScrollArea, QFrame, QMainWindow, QApplication, QFileDialog
)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QColor, QBrush, QFont
from datetime import datetime


class ReysExpressModule:
    """Класс модуля для ModuleManager"""
    
    display_name = "🚛 Рейс-Экспресс"
    description = "Быстрый расчёт рейса: топливо, водитель, три тарифа сразу"
    
    def __init__(self, main_window):
        self.main_window = main_window
        self.widget = None
        self.window = None
    
    def run(self):
        """Запуск модуля — открывает интерфейс в отдельном окне"""
        self.widget = ReysExpressWidget(self.main_window, self)
        
        self.window = QMainWindow()
        self.window.setWindowTitle(f"{self.display_name} - РейсМастер")
        self.window.setWindowIcon(self.main_window.windowIcon())
        self.window.setCentralWidget(self.widget)
        self.window.resize(1300, 950)
        self.window.show()


class ReysExpressWidget(QWidget):
    """Интерфейс калькулятора Рейс-Экспресс"""
    
    def __init__(self, main_window, module):
        super().__init__()
        self.main_window = main_window
        self.module = module
        self.last_result = ""
        self.last_params = None
        self.setup_ui()
        self.connect_signals()
        # Запускаем предварительный просмотр
        QTimer.singleShot(100, self.update_preview)
    
    def load_calculation(self, calculation: dict):
        """Загружает сохраненный расчет в поля"""
        params = calculation.get('params', {})
        if not params:
            return
        
        try:
            # Маршрут
            self.point_a_edit.setText(params.get('point_a', ''))
            self.point_b_edit.setText(params.get('point_b', ''))
            self.base_from_edit.setText(params.get('base_from', 'Красноуфимск'))
            self.dist_base_a.setValue(int(params.get('distance_base_a', 45)))
            self.dist_ab.setValue(int(params.get('distance_ab', 85)))
            self.dist_b_base.setValue(int(params.get('distance_b_base', 130)))
            self.trip_count.setValue(int(params.get('trip_count', 3)))
            self.use_base_cb.setChecked(params.get('use_base', True))
            self.use_multiple_cb.setChecked(params.get('use_multiple', True))
            
            # Груз
            self.cargo_name.setText(params.get('cargo', 'Щебень'))
            self.cargo_volume.setValue(float(params.get('volume', 25.0)))
            self.density.setValue(float(params.get('density', 1.6)))
            
            unit = params.get('unit', 'тонны')
            if unit == 'тонны':
                self.unit_tons.setChecked(True)
            else:
                self.unit_cubes.setChecked(True)
            
            # Топливо
            self.fuel_rate.setValue(float(params.get('fuel_rate', 45.0)))
            self.fuel_price.setValue(float(params.get('fuel_price', 62.0)))
            
            # Водитель (оба поля активны всегда)
            self.driver_percent.setValue(int(params.get('driver_percent', 15)))
            self.driver_fixed.setValue(int(params.get('driver_fixed', 5000)))
            self.use_daily_cb.setChecked(params.get('use_daily', True))
            self.daily_rate.setValue(int(params.get('daily_rate', 700)))
            self.days_on_trip.setValue(int(params.get('days', 3)))
            
            # Часы для почасового тарифа
            self.hours_spin.setValue(float(params.get('hours', 24)))
            
            # Тарифы
            self.rate_ton.setValue(float(params.get('rate_ton', 650.0)))
            self.rate_tkm.setValue(float(params.get('rate_tkm', 8.31)))
            self.rate_hourly.setValue(float(params.get('rate_hourly', 2875.0)))
            
            self.tariff_ton_cb.setChecked(params.get('tariff_ton', True))
            self.tariff_tkm_cb.setChecked(params.get('tariff_tkm', True))
            self.tariff_hourly_cb.setChecked(params.get('tariff_hourly', True))
            
            # Обновляем отображение
            self.update_total_tons()
            self.update_preview()
            
        except Exception as e:
            print(f"Ошибка загрузки расчета: {e}")
    
    def setup_ui(self):
        """Создание интерфейса"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.NoFrame)
        
        scroll_content = QWidget()
        scroll_layout = QVBoxLayout(scroll_content)
        scroll_layout.setSpacing(10)
        scroll_layout.setContentsMargins(10, 10, 10, 10)
        
        # === БЛОК 1: МАРШРУТ ===
        route_group = QGroupBox("📍 МАРШРУТ")
        route_group.setStyleSheet("""
            QGroupBox {
                font-size: 14px;
                font-weight: bold;
                border: 2px solid #c0c0c0;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 10px 0 10px;
            }
        """)
        route_layout = QGridLayout(route_group)
        
        self.use_base_cb = QCheckBox("🏠 Учитывать базу/гараж")
        self.use_base_cb.setChecked(True)
        route_layout.addWidget(self.use_base_cb, 0, 0, 1, 2)
        
        self.use_multiple_cb = QCheckBox("🔄 Несколько рейсов")
        self.use_multiple_cb.setChecked(True)
        route_layout.addWidget(self.use_multiple_cb, 0, 2, 1, 2)
        
        route_layout.addWidget(QLabel("Откуда (база):"), 1, 0)
        self.base_from_edit = QLineEdit("Красноуфимск")
        self.base_from_edit.setMinimumHeight(30)
        route_layout.addWidget(self.base_from_edit, 1, 1)
        
        route_layout.addWidget(QLabel("Пункт А (погрузка):"), 1, 2)
        self.point_a_edit = QLineEdit("Малодегтярский Карьер")
        self.point_a_edit.setMinimumHeight(30)
        route_layout.addWidget(self.point_a_edit, 1, 3)
        
        route_layout.addWidget(QLabel("Пункт Б (разгрузка):"), 2, 0)
        self.point_b_edit = QLineEdit("Арти")
        self.point_b_edit.setMinimumHeight(30)
        route_layout.addWidget(self.point_b_edit, 2, 1)
        
        route_layout.addWidget(QLabel("база → А (км):"), 2, 2)
        self.dist_base_a = QSpinBox()
        self.dist_base_a.setRange(0, 9999)
        self.dist_base_a.setValue(45)
        self.dist_base_a.setSuffix(" км")
        self.dist_base_a.setMinimumHeight(30)
        route_layout.addWidget(self.dist_base_a, 2, 3)
        
        route_layout.addWidget(QLabel("А → Б (км):"), 3, 0)
        self.dist_ab = QSpinBox()
        self.dist_ab.setRange(0, 9999)
        self.dist_ab.setValue(85)
        self.dist_ab.setSuffix(" км")
        self.dist_ab.setMinimumHeight(30)
        route_layout.addWidget(self.dist_ab, 3, 1)
        
        route_layout.addWidget(QLabel("Б → база (км):"), 3, 2)
        self.dist_b_base = QSpinBox()
        self.dist_b_base.setRange(0, 9999)
        self.dist_b_base.setValue(130)
        self.dist_b_base.setSuffix(" км")
        self.dist_b_base.setMinimumHeight(30)
        route_layout.addWidget(self.dist_b_base, 3, 3)
        
        route_layout.addWidget(QLabel("Количество рейсов:"), 4, 0)
        self.trip_count = QSpinBox()
        self.trip_count.setRange(1, 100)
        self.trip_count.setValue(3)
        self.trip_count.setMinimumHeight(30)
        route_layout.addWidget(self.trip_count, 4, 1)
        
        scroll_layout.addWidget(route_group)
        
        # === БЛОК 2: ГРУЗ ===
        cargo_group = QGroupBox("📦 ГРУЗ")
        cargo_group.setStyleSheet(route_group.styleSheet())
        cargo_layout = QGridLayout(cargo_group)
        
        cargo_layout.addWidget(QLabel("Что везём:"), 0, 0)
        self.cargo_name = QLineEdit("Щебень")
        self.cargo_name.setMinimumHeight(30)
        cargo_layout.addWidget(self.cargo_name, 0, 1)
        
        cargo_layout.addWidget(QLabel("Объём:"), 0, 2)
        self.cargo_volume = QDoubleSpinBox()
        self.cargo_volume.setRange(0.1, 1000.0)
        self.cargo_volume.setValue(25.0)
        self.cargo_volume.setDecimals(1)
        self.cargo_volume.setMinimumHeight(30)
        cargo_layout.addWidget(self.cargo_volume, 0, 3)
        
        self.unit_group = QButtonGroup(self)
        self.unit_tons = QRadioButton("тонны")
        self.unit_tons.setChecked(True)
        self.unit_cubes = QRadioButton("кубы")
        self.unit_group.addButton(self.unit_tons)
        self.unit_group.addButton(self.unit_cubes)
        
        cargo_layout.addWidget(self.unit_tons, 1, 1)
        cargo_layout.addWidget(self.unit_cubes, 1, 2)
        
        cargo_layout.addWidget(QLabel("Плотность (т/м³):"), 2, 0)
        self.density = QDoubleSpinBox()
        self.density.setRange(0.1, 10.0)
        self.density.setValue(1.6)
        self.density.setDecimals(2)
        self.density.setEnabled(False)
        self.density.setMinimumHeight(30)
        cargo_layout.addWidget(self.density, 2, 1)
        
        cargo_layout.addWidget(QLabel("Тонн за рейс:"), 2, 2)
        self.total_tons_label = QLabel("25.0 т")
        self.total_tons_label.setStyleSheet("font-weight: bold; color: #1976D2; font-size: 12pt; background-color: #e8f0fe; padding: 5px; border-radius: 4px;")
        self.total_tons_label.setAlignment(Qt.AlignCenter)
        cargo_layout.addWidget(self.total_tons_label, 2, 3)
        
        cargo_layout.addWidget(QLabel("ВСЕГО тонн:"), 3, 2)
        self.total_tons_all_label = QLabel("75.0 т")
        self.total_tons_all_label.setStyleSheet("font-weight: bold; color: #1976D2; font-size: 14pt; background-color: #e8f0fe; padding: 5px; border-radius: 4px;")
        self.total_tons_all_label.setAlignment(Qt.AlignCenter)
        cargo_layout.addWidget(self.total_tons_all_label, 3, 3)
        
        scroll_layout.addWidget(cargo_group)
        
        # === БЛОК 3: ТОПЛИВО ===
        fuel_group = QGroupBox("⛽ ТОПЛИВО")
        fuel_group.setStyleSheet(route_group.styleSheet())
        fuel_layout = QGridLayout(fuel_group)
        
        fuel_layout.addWidget(QLabel("Расход топлива (л/100км):"), 0, 0)
        self.fuel_rate = QDoubleSpinBox()
        self.fuel_rate.setRange(0, 100)
        self.fuel_rate.setValue(45.0)
        self.fuel_rate.setDecimals(1)
        self.fuel_rate.setMinimumHeight(30)
        fuel_layout.addWidget(self.fuel_rate, 0, 1)
        
        fuel_layout.addWidget(QLabel("Цена дизеля (₽/л):"), 0, 2)
        self.fuel_price = QDoubleSpinBox()
        self.fuel_price.setRange(0, 200)
        self.fuel_price.setValue(62.0)
        self.fuel_price.setDecimals(2)
        self.fuel_price.setPrefix("₽ ")
        self.fuel_price.setMinimumHeight(30)
        fuel_layout.addWidget(self.fuel_price, 0, 3)
        
        self.fuel_result_label = QLabel("⛽ Предварительный расчет топлива")
        self.fuel_result_label.setStyleSheet(
            "background-color: #e4ecf7; padding: 8px; border-radius: 4px; font-size: 11pt;"
        )
        self.fuel_result_label.setWordWrap(True)
        fuel_layout.addWidget(self.fuel_result_label, 1, 0, 1, 4)
        
        scroll_layout.addWidget(fuel_group)
        
        # === БЛОК 4: ВОДИТЕЛЬ (оба поля активны всегда) ===
        driver_group = QGroupBox("👤 ВОДИТЕЛЬ (будут показаны оба варианта расчета)")
        driver_group.setStyleSheet(route_group.styleSheet())
        driver_layout = QGridLayout(driver_group)
        
        driver_layout.addWidget(QLabel("Процент от выручки:"), 0, 0)
        self.driver_percent = QSpinBox()
        self.driver_percent.setRange(0, 50)
        self.driver_percent.setValue(15)
        self.driver_percent.setSuffix(" %")
        self.driver_percent.setMinimumHeight(30)
        driver_layout.addWidget(self.driver_percent, 0, 1)
        
        driver_layout.addWidget(QLabel("или фикс (₽/рейс):"), 0, 2)
        self.driver_fixed = QSpinBox()
        self.driver_fixed.setRange(0, 100000)
        self.driver_fixed.setValue(5000)
        self.driver_fixed.setSuffix(" ₽")
        self.driver_fixed.setSingleStep(1000)
        self.driver_fixed.setMinimumHeight(30)
        driver_layout.addWidget(self.driver_fixed, 0, 3)
        
        self.use_daily_cb = QCheckBox("Суточные")
        self.use_daily_cb.setChecked(True)
        driver_layout.addWidget(self.use_daily_cb, 1, 0)
        
        self.daily_rate = QSpinBox()
        self.daily_rate.setRange(0, 5000)
        self.daily_rate.setValue(700)
        self.daily_rate.setSuffix(" ₽/день")
        self.daily_rate.setMinimumHeight(30)
        driver_layout.addWidget(self.daily_rate, 1, 1)
        
        driver_layout.addWidget(QLabel("×"), 1, 2)
        
        self.days_on_trip = QSpinBox()
        self.days_on_trip.setRange(1, 30)
        self.days_on_trip.setValue(3)
        self.days_on_trip.setSuffix(" дня")
        self.days_on_trip.setMinimumHeight(30)
        driver_layout.addWidget(self.days_on_trip, 1, 3)
        
        scroll_layout.addWidget(driver_group)
        
        # === БЛОК 5: ЧАСЫ ДЛЯ ПОЧАСОВОГО ТАРИФА ===
        hours_group = QGroupBox("⏱️ ВРЕМЯ")
        hours_group.setStyleSheet(route_group.styleSheet())
        hours_layout = QGridLayout(hours_group)
        
        hours_layout.addWidget(QLabel("Общее время в пути (часов):"), 0, 0)
        self.hours_spin = QDoubleSpinBox()
        self.hours_spin.setRange(1, 1000)
        self.hours_spin.setValue(24)
        self.hours_spin.setDecimals(1)
        self.hours_spin.setSuffix(" ч")
        self.hours_spin.setMinimumHeight(30)
        hours_layout.addWidget(self.hours_spin, 0, 1)
        
        hours_layout.addWidget(QLabel("(используется для почасового тарифа)"), 0, 2)
        
        scroll_layout.addWidget(hours_group)
        
        # === БЛОК 6: ТАРИФЫ ===
        tariff_group = QGroupBox("💰 ТАРИФЫ (для сравнения)")
        tariff_group.setStyleSheet(route_group.styleSheet())
        tariff_layout = QGridLayout(tariff_group)
        
        self.tariff_ton_cb = QCheckBox("За тонну")
        self.tariff_ton_cb.setChecked(True)
        tariff_layout.addWidget(self.tariff_ton_cb, 0, 0)
        
        self.rate_ton = QDoubleSpinBox()
        self.rate_ton.setRange(0, 10000)
        self.rate_ton.setValue(650.0)
        self.rate_ton.setSuffix(" ₽/т")
        self.rate_ton.setDecimals(2)
        self.rate_ton.setMinimumHeight(30)
        tariff_layout.addWidget(self.rate_ton, 0, 1)
        
        self.tariff_tkm_cb = QCheckBox("За тонно-км")
        self.tariff_tkm_cb.setChecked(True)
        tariff_layout.addWidget(self.tariff_tkm_cb, 1, 0)
        
        self.rate_tkm = QDoubleSpinBox()
        self.rate_tkm.setRange(0, 100)
        self.rate_tkm.setValue(8.31)
        self.rate_tkm.setSuffix(" ₽/т/км")
        self.rate_tkm.setDecimals(2)
        self.rate_tkm.setMinimumHeight(30)
        tariff_layout.addWidget(self.rate_tkm, 1, 1)
        
        self.tariff_hourly_cb = QCheckBox("Почасовая")
        self.tariff_hourly_cb.setChecked(True)
        tariff_layout.addWidget(self.tariff_hourly_cb, 2, 0)
        
        self.rate_hourly = QDoubleSpinBox()
        self.rate_hourly.setRange(0, 10000)
        self.rate_hourly.setValue(2875.0)
        self.rate_hourly.setSuffix(" ₽/ч")
        self.rate_hourly.setDecimals(2)
        self.rate_hourly.setMinimumHeight(30)
        tariff_layout.addWidget(self.rate_hourly, 2, 1)
        
        scroll_layout.addWidget(tariff_group)
        
        # === БЛОК 7: РЕЗУЛЬТАТЫ ===
        result_group = QGroupBox("📊 РЕЗУЛЬТАТЫ (сравнение вариантов)")
        result_group.setStyleSheet(route_group.styleSheet())
        result_layout = QVBoxLayout(result_group)
        
        # Сводка по маршруту
        self.route_summary = QLabel()
        self.route_summary.setStyleSheet("background-color: #e8f0fe; padding: 10px; border-radius: 4px; font-size: 11pt;")
        self.route_summary.setWordWrap(True)
        result_layout.addWidget(self.route_summary)
        
        # Таблица результатов (расширенная для двух вариантов зарплаты)
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(8)
        self.result_table.setHorizontalHeaderLabels([
            "Тариф", "Ставка", "Выручка", "Топливо", 
            "З/п (%)", "З/п (фикс)", "Суточные", "Прибыль"
        ])
        self.result_table.horizontalHeader().setStretchLastSection(True)
        self.result_table.setAlternatingRowColors(True)
        self.result_table.setMinimumHeight(250)
        self.result_table.setStyleSheet("""
            QTableWidget {
                font-size: 10pt;
                gridline-color: #c0c0c0;
                border: 1px solid #c0c0c0;
                border-radius: 5px;
            }
            QTableWidget::item {
                padding: 5px;
            }
            QHeaderView::section {
                background-color: #e0e0e0;
                padding: 5px;
                font-size: 10pt;
                font-weight: bold;
                border: 1px solid #c0c0c0;
            }
        """)
        result_layout.addWidget(self.result_table)
        
        # Детализация расходов
        self.expenses_detail = QLabel()
        self.expenses_detail.setStyleSheet("background-color: #e8f0fe; padding: 10px; border-radius: 4px; font-size: 11pt;")
        self.expenses_detail.setWordWrap(True)
        result_layout.addWidget(self.expenses_detail)
        
        # Итог
        self.total_label = QLabel()
        self.total_label.setStyleSheet("background-color: #1976D2; color: white; padding: 10px; border-radius: 4px; font-size: 12pt; font-weight: bold;")
        self.total_label.setAlignment(Qt.AlignCenter)
        result_layout.addWidget(self.total_label)
        
        scroll_layout.addWidget(result_group)
        
        # === КНОПКИ ===
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        
        self.calc_btn = QPushButton("🧮 РАССЧИТАТЬ")
        self.calc_btn.setMinimumHeight(45)
        self.calc_btn.setMinimumWidth(200)
        self.calc_btn.setStyleSheet("""
            QPushButton {
                background-color: #1976D2;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 14px;
                font-weight: bold;
                padding: 10px 20px;
            }
            QPushButton:hover {
                background-color: #1565C0;
            }
        """)
        self.calc_btn.clicked.connect(self.calculate)
        btn_layout.addWidget(self.calc_btn)
        
        self.fav_btn = QPushButton("⭐ В избранное")
        self.fav_btn.setMinimumHeight(40)
        self.fav_btn.setMinimumWidth(150)
        self.fav_btn.setStyleSheet("""
            QPushButton {
                background-color: #FFC107;
                color: #1a2a3a;
                border: none;
                border-radius: 5px;
                font-size: 12pt;
                font-weight: bold;
                padding: 8px 15px;
            }
            QPushButton:hover {
                background-color: #FFB300;
            }
        """)
        self.fav_btn.clicked.connect(self.add_to_favorites)
        btn_layout.addWidget(self.fav_btn)
        
        self.copy_btn = QPushButton("📋 Копировать")
        self.copy_btn.setMinimumHeight(40)
        self.copy_btn.setMinimumWidth(150)
        self.copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #00A3FF;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 12pt;
                font-weight: bold;
                padding: 8px 15px;
            }
            QPushButton:hover {
                background-color: #0090E0;
            }
        """)
        self.copy_btn.clicked.connect(self.copy_table)
        btn_layout.addWidget(self.copy_btn)
        
        # НОВАЯ КНОПКА: Экспорт в Excel
        self.excel_btn = QPushButton("📊 Экспорт в Excel")
        self.excel_btn.setMinimumHeight(40)
        self.excel_btn.setMinimumWidth(150)
        self.excel_btn.setStyleSheet("""
            QPushButton {
                background-color: #2E7D32;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 12pt;
                font-weight: bold;
                padding: 8px 15px;
            }
            QPushButton:hover {
                background-color: #1B5E20;
            }
        """)
        self.excel_btn.clicked.connect(self.export_to_excel)
        btn_layout.addWidget(self.excel_btn)
        
        scroll_layout.addLayout(btn_layout)
        scroll_layout.addStretch()
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
    
    def connect_signals(self):
        """Подключение сигналов"""
        widgets_for_tons_update = [
            self.cargo_volume, self.density, self.unit_tons, self.unit_cubes,
            self.trip_count, self.use_multiple_cb
        ]
        
        for widget in widgets_for_tons_update:
            if isinstance(widget, (QCheckBox, QRadioButton)):
                widget.toggled.connect(self.update_total_tons)
            elif isinstance(widget, (QSpinBox, QDoubleSpinBox)):
                widget.valueChanged.connect(self.update_total_tons)
        
        # Обновление предварительного просмотра при любых изменениях
        all_widgets = [
            self.dist_base_a, self.dist_ab, self.dist_b_base,
            self.trip_count, self.fuel_rate, self.fuel_price,
            self.use_base_cb, self.use_multiple_cb,
            self.cargo_volume, self.density, self.unit_tons, self.unit_cubes,
            self.hours_spin, self.driver_percent, self.driver_fixed,
            self.use_daily_cb, self.daily_rate, self.days_on_trip
        ]
        
        for widget in all_widgets:
            if isinstance(widget, (QCheckBox, QRadioButton)):
                widget.toggled.connect(self.update_preview)
            elif isinstance(widget, (QSpinBox, QDoubleSpinBox)):
                widget.valueChanged.connect(self.update_preview)
        
        self.unit_tons.toggled.connect(self.on_unit_changed)
        self.unit_cubes.toggled.connect(self.on_unit_changed)
    
    def on_unit_changed(self):
        self.density.setEnabled(self.unit_cubes.isChecked())
        self.update_total_tons()
        self.update_preview()
    
    def update_total_tons(self):
        """Обновляет отображение тоннажа"""
        if self.unit_cubes.isChecked():
            tons_per_trip = self.cargo_volume.value() * self.density.value()
        else:
            tons_per_trip = self.cargo_volume.value()
        
        trips = self.trip_count.value() if self.use_multiple_cb.isChecked() else 1
        tons_total = tons_per_trip * trips
        
        self.total_tons_label.setText(f"{tons_per_trip:.1f} т")
        self.total_tons_all_label.setText(f"{tons_total:.1f} т")
    
    def calculate_fuel(self):
        """Расчет топлива (единая норма расхода)"""
        dist_base_a = self.dist_base_a.value()
        dist_ab = self.dist_ab.value()
        dist_b_base = self.dist_b_base.value()
        trip_count = self.trip_count.value() if self.use_multiple_cb.isChecked() else 1
        use_base = self.use_base_cb.isChecked()
        
        rate = self.fuel_rate.value()  # л/100км
        price = self.fuel_price.value()  # ₽/л
        
        if use_base:
            # С базой: база→А + А→Б + Б→база + (рейсы-1) × (Б→А)
            if trip_count == 1:
                total_km = dist_base_a + dist_ab + dist_b_base
            else:
                total_km = dist_base_a + (dist_ab * trip_count) + dist_b_base + (dist_ab * (trip_count - 1))
        else:
            # Без базы: только А→Б × рейсы
            total_km = dist_ab * trip_count
        
        total_fuel = total_km * rate / 100
        fuel_cost = total_fuel * price
        
        return {
            'total_km': total_km,
            'total_fuel': total_fuel,
            'fuel_cost': fuel_cost
        }
    
    def update_preview(self):
        """Обновляет предварительный просмотр"""
        try:
            fuel_data = self.calculate_fuel()
            
            trips = self.trip_count.value() if self.use_multiple_cb.isChecked() else 1
            tons_total = float(self.total_tons_all_label.text().replace(' т', ''))
            
            # Предварительный расчет обоих вариантов зарплаты
            driver_pay_percent_preview = 100000 * self.driver_percent.value() / 100
            driver_pay_fixed_preview = self.driver_fixed.value() * trips
            
            # Суточные (ПРАВИЛЬНО - только за дни)
            daily_pay_preview = self.daily_rate.value() * self.days_on_trip.value() if self.use_daily_cb.isChecked() else 0
            
            # Обновляем метку топлива
            fuel_text = (f"⛽ РАСЧЕТ ТОПЛИВА:\n"
                        f"📏 Общий пробег: {fuel_data['total_km']} км\n"
                        f"🛢️ Расход: {self.fuel_rate.value()} л/100км\n"
                        f"⛽ Всего топлива: {fuel_data['total_fuel']:.1f} л\n"
                        f"💰 Стоимость топлива: {fuel_data['fuel_cost']:,.0f} ₽")
            
            self.fuel_result_label.setText(fuel_text.replace(",", " "))
            
            # Обновляем сводку по маршруту
            if self.use_base_cb.isChecked():
                route_desc = f"база→А ({self.dist_base_a.value()} км) + А→Б ({self.dist_ab.value()} км) + Б→база ({self.dist_b_base.value()} км)"
                if trips > 1:
                    route_desc += f" + {trips-1} × Б→А ({self.dist_ab.value()} км)"
            else:
                route_desc = f"А→Б ({self.dist_ab.value()} км) × {trips}"
            
            # Доходная часть (только А→Б)
            revenue_km = self.dist_ab.value() * trips
            
            self.route_summary.setText(
                f"📍 Маршрут: {route_desc}\n"
                f"📦 Количество рейсов: {trips}\n"
                f"📏 Общий пробег: {fuel_data['total_km']} км\n"
                f"💰 Доходный пробег (А→Б): {revenue_km} км\n"
                f"⚖️ Всего тонн: {tons_total:.1f} т\n"
                f"⏱️ Общее время: {self.hours_spin.value():.1f} ч"
            )
            
        except Exception as e:
            print(f"Ошибка предпросмотра: {e}")
    
    def get_params(self) -> dict:
        """Возвращает словарь с текущими параметрами"""
        return {
            "point_a": self.point_a_edit.text(),
            "point_b": self.point_b_edit.text(),
            "base_from": self.base_from_edit.text(),
            "cargo": self.cargo_name.text(),
            "volume": self.cargo_volume.value(),
            "density": self.density.value(),
            "unit": "тонны" if self.unit_tons.isChecked() else "кубы",
            "use_base": self.use_base_cb.isChecked(),
            "use_multiple": self.use_multiple_cb.isChecked(),
            "distance_base_a": self.dist_base_a.value(),
            "distance_ab": self.dist_ab.value(),
            "distance_b_base": self.dist_b_base.value(),
            "trip_count": self.trip_count.value(),
            "fuel_rate": self.fuel_rate.value(),
            "fuel_price": self.fuel_price.value(),
            "driver_percent": self.driver_percent.value(),
            "driver_fixed": self.driver_fixed.value(),
            "use_daily": self.use_daily_cb.isChecked(),
            "daily_rate": self.daily_rate.value(),
            "days": self.days_on_trip.value(),
            "hours": self.hours_spin.value(),
            "tariff_ton": self.tariff_ton_cb.isChecked(),
            "rate_ton": self.rate_ton.value(),
            "tariff_tkm": self.tariff_tkm_cb.isChecked(),
            "rate_tkm": self.rate_tkm.value(),
            "tariff_hourly": self.tariff_hourly_cb.isChecked(),
            "rate_hourly": self.rate_hourly.value()
        }
    
    def calculate(self):
        """Основной расчет"""
        try:
            params = self.get_params()
            fuel_data = self.calculate_fuel()
            
            trips = params["trip_count"] if params["use_multiple"] else 1
            
            # Расчет тоннажа
            if params["unit"] == "кубы":
                tons_per_trip = params["volume"] * params["density"]
            else:
                tons_per_trip = params["volume"]
            
            total_tons = tons_per_trip * trips
            
            # Суточные (ПРАВИЛЬНО - только за дни, без умножения на рейсы)
            daily_pay = params["daily_rate"] * params["days"] if params["use_daily"] else 0
            
            # Расчет по каждому тарифу с двумя вариантами зарплаты
            results = []
            
            # Тариф за тонну
            if params["tariff_ton"]:
                revenue = total_tons * params["rate_ton"]
                
                # Два варианта зарплаты
                driver_pay_percent = revenue * params["driver_percent"] / 100
                driver_pay_fixed = params["driver_fixed"] * trips
                
                # Прибыль для двух вариантов
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_pay_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_pay_fixed - daily_pay
                
                results.append({
                    "name": "За тонну",
                    "rate": f"{params['rate_ton']:.2f} ₽/т",
                    "revenue": revenue,
                    "fuel_cost": fuel_data['fuel_cost'],
                    "driver_pay_percent": driver_pay_percent,
                    "driver_pay_fixed": driver_pay_fixed,
                    "daily_pay": daily_pay,
                    "profit_percent": profit_percent,
                    "profit_fixed": profit_fixed,
                    "profitability_percent": (profit_percent / revenue * 100) if revenue > 0 else 0,
                    "profitability_fixed": (profit_fixed / revenue * 100) if revenue > 0 else 0
                })
            
            # Тариф за тонно-км
            if params["tariff_tkm"]:
                revenue = tons_per_trip * trips * params["distance_ab"] * params["rate_tkm"]
                
                driver_pay_percent = revenue * params["driver_percent"] / 100
                driver_pay_fixed = params["driver_fixed"] * trips
                
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_pay_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_pay_fixed - daily_pay
                
                results.append({
                    "name": "За т/км",
                    "rate": f"{params['rate_tkm']:.2f} ₽/т/км",
                    "revenue": revenue,
                    "fuel_cost": fuel_data['fuel_cost'],
                    "driver_pay_percent": driver_pay_percent,
                    "driver_pay_fixed": driver_pay_fixed,
                    "daily_pay": daily_pay,
                    "profit_percent": profit_percent,
                    "profit_fixed": profit_fixed,
                    "profitability_percent": (profit_percent / revenue * 100) if revenue > 0 else 0,
                    "profitability_fixed": (profit_fixed / revenue * 100) if revenue > 0 else 0
                })
            
            # Почасовой тариф
            if params["tariff_hourly"]:
                revenue = params["hours"] * params["rate_hourly"]
                
                driver_pay_percent = revenue * params["driver_percent"] / 100
                driver_pay_fixed = params["driver_fixed"] * trips
                
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_pay_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_pay_fixed - daily_pay
                
                results.append({
                    "name": "Почасовая",
                    "rate": f"{params['rate_hourly']:.2f} ₽/ч",
                    "revenue": revenue,
                    "fuel_cost": fuel_data['fuel_cost'],
                    "driver_pay_percent": driver_pay_percent,
                    "driver_pay_fixed": driver_pay_fixed,
                    "daily_pay": daily_pay,
                    "profit_percent": profit_percent,
                    "profit_fixed": profit_fixed,
                    "profitability_percent": (profit_percent / revenue * 100) if revenue > 0 else 0,
                    "profitability_fixed": (profit_fixed / revenue * 100) if revenue > 0 else 0
                })
            
            if not results:
                QMessageBox.warning(self, "Предупреждение", "Выберите хотя бы один тариф!")
                return
            
            # Заполняем таблицу
            self.result_table.setRowCount(len(results) * 2)
            
            row = 0
            best_profit = float('-inf')
            best_name = ""
            
            for res in results:
                # Строка для процента
                self.result_table.setItem(row, 0, QTableWidgetItem(res["name"] + " (%)"))
                self.result_table.setItem(row, 1, QTableWidgetItem(res["rate"]))
                
                revenue_item = QTableWidgetItem(f"{res['revenue']:,.2f} ₽".replace(",", " "))
                revenue_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 2, revenue_item)
                
                fuel_item = QTableWidgetItem(f"{res['fuel_cost']:,.2f} ₽".replace(",", " "))
                fuel_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 3, fuel_item)
                
                driver_percent_item = QTableWidgetItem(f"{res['driver_pay_percent']:,.2f} ₽".replace(",", " "))
                driver_percent_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 4, driver_percent_item)
                
                driver_fixed_item = QTableWidgetItem(f"{res['driver_pay_fixed']:,.2f} ₽".replace(",", " "))
                driver_fixed_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 5, driver_fixed_item)
                
                daily_item = QTableWidgetItem(f"{res['daily_pay']:,.2f} ₽".replace(",", " "))
                daily_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 6, daily_item)
                
                profit_text = f"{res['profit_percent']:,.2f} ₽".replace(",", " ")
                if res['profitability_percent'] != 0:
                    profit_text += f" ({res['profitability_percent']:.1f}%)"
                
                profit_item = QTableWidgetItem(profit_text)
                profit_item.setTextAlignment(Qt.AlignCenter)
                
                # Цветовая индикация
                if res['profit_percent'] > 0:
                    if res['profitability_percent'] > 30:
                        profit_item.setBackground(QColor("#dff0d8"))
                        profit_item.setForeground(QBrush(QColor("#2e7d32")))
                    elif res['profitability_percent'] > 15:
                        profit_item.setBackground(QColor("#e8f5e9"))
                        profit_item.setForeground(QBrush(QColor("#2e7d32")))
                    else:
                        profit_item.setBackground(QColor("#fff3cd"))
                        profit_item.setForeground(QBrush(QColor("#b85e00")))
                else:
                    profit_item.setBackground(QColor("#f8d7da"))
                    profit_item.setForeground(QBrush(QColor("#b02a37")))
                
                self.result_table.setItem(row, 7, profit_item)
                
                # Проверяем, не лучше ли это вариант
                if res['profit_percent'] > best_profit:
                    best_profit = res['profit_percent']
                    best_name = f"{res['name']} (%)"
                
                row += 1
                
                # Строка для фиксированной ставки
                self.result_table.setItem(row, 0, QTableWidgetItem(res["name"] + " (фикс)"))
                self.result_table.setItem(row, 1, QTableWidgetItem(res["rate"]))
                
                revenue_item = QTableWidgetItem(f"{res['revenue']:,.2f} ₽".replace(",", " "))
                revenue_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 2, revenue_item)
                
                fuel_item = QTableWidgetItem(f"{res['fuel_cost']:,.2f} ₽".replace(",", " "))
                fuel_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 3, fuel_item)
                
                driver_percent_item = QTableWidgetItem(f"{res['driver_pay_percent']:,.2f} ₽".replace(",", " "))
                driver_percent_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 4, driver_percent_item)
                
                driver_fixed_item = QTableWidgetItem(f"{res['driver_pay_fixed']:,.2f} ₽".replace(",", " "))
                driver_fixed_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 5, driver_fixed_item)
                
                daily_item = QTableWidgetItem(f"{res['daily_pay']:,.2f} ₽".replace(",", " "))
                daily_item.setTextAlignment(Qt.AlignCenter)
                self.result_table.setItem(row, 6, daily_item)
                
                profit_text = f"{res['profit_fixed']:,.2f} ₽".replace(",", " ")
                if res['profitability_fixed'] != 0:
                    profit_text += f" ({res['profitability_fixed']:.1f}%)"
                
                profit_item = QTableWidgetItem(profit_text)
                profit_item.setTextAlignment(Qt.AlignCenter)
                
                if res['profit_fixed'] > 0:
                    if res['profitability_fixed'] > 30:
                        profit_item.setBackground(QColor("#dff0d8"))
                        profit_item.setForeground(QBrush(QColor("#2e7d32")))
                    elif res['profitability_fixed'] > 15:
                        profit_item.setBackground(QColor("#e8f5e9"))
                        profit_item.setForeground(QBrush(QColor("#2e7d32")))
                    else:
                        profit_item.setBackground(QColor("#fff3cd"))
                        profit_item.setForeground(QBrush(QColor("#b85e00")))
                else:
                    profit_item.setBackground(QColor("#f8d7da"))
                    profit_item.setForeground(QBrush(QColor("#b02a37")))
                
                self.result_table.setItem(row, 7, profit_item)
                
                if res['profit_fixed'] > best_profit:
                    best_profit = res['profit_fixed']
                    best_name = f"{res['name']} (фикс)"
                
                row += 1
            
            self.result_table.resizeColumnsToContents()
            
            # Детализация расходов
            expenses_text = (f"💰 ДЕТАЛИЗАЦИЯ РАСХОДОВ:\n"
                            f"⛽ Топливо: {fuel_data['fuel_cost']:,.2f} ₽\n"
                            f"👤 Водитель (%): {results[0]['driver_pay_percent']:,.2f} ₽ ({params['driver_percent']}% от выручки)\n"
                            f"👤 Водитель (фикс): {results[0]['driver_pay_fixed']:,.2f} ₽ ({params['driver_fixed']} ₽/рейс × {trips} рейсов)\n"
                            f"💰 Суточные: {daily_pay:,.2f} ₽ ({params['daily_rate']} ₽/день × {params['days']} дн.)\n"
                            f"📊 ВСЕГО РАСХОДОВ (при %): {fuel_data['fuel_cost'] + results[0]['driver_pay_percent'] + daily_pay:,.2f} ₽\n"
                            f"📊 ВСЕГО РАСХОДОВ (при фикс): {fuel_data['fuel_cost'] + results[0]['driver_pay_fixed'] + daily_pay:,.2f} ₽")
            
            self.expenses_detail.setText(expenses_text.replace(",", " "))
            
            # Обновляем итоговую метку
            self.total_label.setText(
                f"🏆 ЛУЧШИЙ ВАРИАНТ: {best_name} | ПРИБЫЛЬ: {best_profit:,.2f} ₽"
                .replace(",", " ")
            )
            
            # Сохраняем результаты
            self.last_result = f"{best_profit:,.2f} ₽ ({best_name})".replace(",", " ")
            self.last_params = params
            
            # Сохраняем в историю
            self.save_to_history()
            
        except Exception as e:
            QMessageBox.critical(self, "Ошибка", f"Ошибка при расчёте:\n{str(e)}")
    
    def get_description(self) -> str:
        params = self.get_params()
        trips = params["trip_count"] if params["use_multiple"] else 1
        
        if params["unit"] == "кубы":
            tons = params["volume"] * params["density"] * trips
        else:
            tons = params["volume"] * trips
        
        return f"{params['point_a']} → {params['point_b']}, {params['cargo']} {tons:.1f} т ({trips} рейс)"
    
    def save_to_history(self):
        """Сохраняет текущий расчет в историю"""
        if self.main_window and hasattr(self.main_window, 'history_manager') and self.last_params:
            calculation = {
                "id": datetime.now().strftime("%Y%m%d%H%M%S"),
                "date": datetime.now().strftime("%d.%m.%Y %H:%M"),
                "module": "🚛 Рейс-Экспресс",
                "description": self.get_description(),
                "result": self.last_result,
                "params": self.last_params
            }
            self.main_window.history_manager.add_to_history(calculation)
            if hasattr(self.main_window, 'favorites_widget'):
                self.main_window.favorites_widget.refresh()
    
    def add_to_favorites(self):
        """Добавляет текущий расчет в избранное"""
        if not self.last_result or not self.last_params:
            QMessageBox.warning(self, "Предупреждение", "Сначала выполните расчёт!")
            return
        
        calculation = {
            "id": datetime.now().strftime("%Y%m%d%H%M%S"),
            "date": datetime.now().strftime("%d.%m.%Y %H:%M"),
            "module": "🚛 Рейс-Экспресс",
            "description": self.get_description(),
            "result": self.last_result,
            "params": self.last_params
        }
        
        if self.main_window and hasattr(self.main_window, 'history_manager'):
            if self.main_window.history_manager.add_to_favorites(calculation):
                QMessageBox.information(self, "Готово", "⭐ Расчёт добавлен в избранное!")
                if hasattr(self.main_window, 'favorites_widget'):
                    self.main_window.favorites_widget.refresh()
            else:
                QMessageBox.information(self, "Инфо", "Этот расчёт уже в избранном")
    
    def copy_table(self):
        """Копирует результаты в буфер обмена"""
        text = f"🚛 РЕЙС-ЭКСПРЕСС - РЕЗУЛЬТАТЫ РАСЧЕТА\n"
        text += f"{datetime.now().strftime('%d.%m.%Y %H:%M')}\n"
        text += "=" * 60 + "\n\n"
        
        text += self.route_summary.text() + "\n\n"
        text += self.fuel_result_label.text() + "\n\n"
        text += self.expenses_detail.text() + "\n\n"
        
        rows = self.result_table.rowCount()
        cols = self.result_table.columnCount()
        
        headers = []
        for col in range(cols):
            headers.append(self.result_table.horizontalHeaderItem(col).text())
        
        text += "\t".join(headers) + "\n"
        text += "-" * 120 + "\n"
        
        for row in range(rows):
            row_text = []
            for col in range(cols):
                item = self.result_table.item(row, col)
                row_text.append(item.text() if item else "")
            text += "\t".join(row_text) + "\n"
        
        text += "\n" + self.total_label.text()
        
        clipboard = QApplication.clipboard()
        clipboard.setText(text)
        
        QMessageBox.information(self, "Копирование", "✅ Результаты скопированы в буфер обмена!")
    
    # ========== НОВЫЙ МЕТОД: ЭКСПОРТ В EXCEL ==========
    def export_to_excel(self):
        """Экспорт текущего расчета в Excel"""
        if not self.last_params:
            QMessageBox.warning(self, "Предупреждение", "Сначала выполните расчёт!")
            return
        
        try:
            # Проверяем наличие openpyxl
            try:
                import openpyxl
                from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
                from openpyxl.utils import get_column_letter
            except ImportError:
                QMessageBox.warning(
                    self,
                    "Библиотека не установлена",
                    "Для экспорта в Excel требуется библиотека openpyxl\n\n"
                    "Установите: pip install openpyxl"
                )
                return
            
            # Запрашиваем имя файла
            filename, _ = QFileDialog.getSaveFileName(
                self,
                "Сохранить расчет в Excel",
                f"reysmaster_calculation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx",
                "Excel Files (*.xlsx)"
            )
            
            if not filename:
                return
            
            # Создаем книгу Excel
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = "Расчет рейса"
            
            # Настройка стилей
            title_font = Font(name='Arial', size=14, bold=True, color="FFFFFF")
            title_fill = PatternFill(start_color="1976D2", end_color="1976D2", fill_type="solid")
            header_font = Font(name='Arial', size=11, bold=True, color="FFFFFF")
            header_fill = PatternFill(start_color="2E7D32", end_color="2E7D32", fill_type="solid")
            section_font = Font(name='Arial', size=12, bold=True)
            section_fill = PatternFill(start_color="E3F2FD", end_color="E3F2FD", fill_type="solid")
            cell_font = Font(name='Arial', size=10)
            bold_cell_font = Font(name='Arial', size=10, bold=True)
            center_alignment = Alignment(horizontal="center", vertical="center")
            left_alignment = Alignment(horizontal="left", vertical="center")
            right_alignment = Alignment(horizontal="right", vertical="center")
            border = Border(
                left=Side(style='thin'),
                right=Side(style='thin'),
                top=Side(style='thin'),
                bottom=Side(style='thin')
            )
            
            # Заголовок
            ws.merge_cells('A1:H1')
            title_cell = ws['A1']
            title_cell.value = "🚛 РЕЙС-ЭКСПРЕСС - ДЕТАЛЬНЫЙ РАСЧЕТ РЕЙСА"
            title_cell.font = title_font
            title_cell.fill = title_fill
            title_cell.alignment = center_alignment
            title_cell.border = border
            
            # Дата и время
            ws.merge_cells('A2:H2')
            date_cell = ws['A2']
            date_cell.value = f"Дата расчета: {datetime.now().strftime('%d.%m.%Y %H:%M')}"
            date_cell.font = Font(name='Arial', size=10, italic=True)
            date_cell.alignment = right_alignment
            date_cell.border = border
            
            # Параметры маршрута
            row = 4
            ws.merge_cells(f'A{row}:H{row}')
            section_cell = ws[f'A{row}']
            section_cell.value = "📍 ПАРАМЕТРЫ МАРШРУТА"
            section_cell.font = section_font
            section_cell.fill = section_fill
            section_cell.alignment = left_alignment
            section_cell.border = border
            
            row += 1
            params = self.last_params
            trips = params["trip_count"] if params["use_multiple"] else 1
            
            # Данные маршрута
            route_data = [
                ("Точка А (погрузка):", params['point_a']),
                ("Точка Б (разгрузка):", params['point_b']),
                ("База/гараж:", params['base_from'] if params['use_base'] else "не учитывается"),
                ("Расстояние база→А:", f"{params['distance_base_a']} км" if params['use_base'] else "-"),
                ("Расстояние А→Б:", f"{params['distance_ab']} км"),
                ("Расстояние Б→база:", f"{params['distance_b_base']} км" if params['use_base'] else "-"),
                ("Количество рейсов:", f"{trips}"),
            ]
            
            for i, (label, value) in enumerate(route_data):
                ws[f'A{row+i}'] = label
                ws[f'A{row+i}'].font = bold_cell_font
                ws[f'A{row+i}'].border = border
                ws[f'A{row+i}'].alignment = left_alignment
                
                ws[f'B{row+i}'] = value
                ws[f'B{row+i}'].font = cell_font
                ws[f'B{row+i}'].border = border
                ws[f'B{row+i}'].alignment = left_alignment
            
            row += len(route_data) + 1
            
            # Параметры груза
            ws.merge_cells(f'A{row}:H{row}')
            section_cell = ws[f'A{row}']
            section_cell.value = "📦 ПАРАМЕТРЫ ГРУЗА"
            section_cell.font = section_font
            section_cell.fill = section_fill
            section_cell.alignment = left_alignment
            section_cell.border = border
            
            row += 1
            if params["unit"] == "кубы":
                tons_per_trip = params["volume"] * params["density"]
            else:
                tons_per_trip = params["volume"]
            
            total_tons = tons_per_trip * trips
            
            cargo_data = [
                ("Груз:", params['cargo']),
                ("Тонн за рейс:", f"{tons_per_trip:.1f} т"),
                ("Всего тонн:", f"{total_tons:.1f} т"),
                ("Единицы измерения:", params['unit']),
            ]
            
            if params["unit"] == "кубы":
                cargo_data.insert(1, ("Объем:", f"{params['volume']} м³"))
                cargo_data.insert(2, ("Плотность:", f"{params['density']} т/м³"))
            
            for i, (label, value) in enumerate(cargo_data):
                ws[f'A{row+i}'] = label
                ws[f'A{row+i}'].font = bold_cell_font
                ws[f'A{row+i}'].border = border
                ws[f'A{row+i}'].alignment = left_alignment
                
                ws[f'B{row+i}'] = value
                ws[f'B{row+i}'].font = cell_font
                ws[f'B{row+i}'].border = border
                ws[f'B{row+i}'].alignment = left_alignment
            
            row += len(cargo_data) + 1
            
            # Топливо
            ws.merge_cells(f'A{row}:H{row}')
            section_cell = ws[f'A{row}']
            section_cell.value = "⛽ ТОПЛИВО"
            section_cell.font = section_font
            section_cell.fill = section_fill
            section_cell.alignment = left_alignment
            section_cell.border = border
            
            row += 1
            fuel_data = self.calculate_fuel()
            
            fuel_info = [
                ("Расход топлива:", f"{params['fuel_rate']} л/100км"),
                ("Цена дизеля:", f"{params['fuel_price']} ₽/л"),
                ("Общий пробег:", f"{fuel_data['total_km']} км"),
                ("Всего топлива:", f"{fuel_data['total_fuel']:.1f} л"),
                ("Стоимость топлива:", f"{fuel_data['fuel_cost']:,.2f} ₽"),
            ]
            
            for i, (label, value) in enumerate(fuel_info):
                ws[f'A{row+i}'] = label
                ws[f'A{row+i}'].font = bold_cell_font
                ws[f'A{row+i}'].border = border
                ws[f'A{row+i}'].alignment = left_alignment
                
                ws[f'B{row+i}'] = value
                ws[f'B{row+i}'].font = cell_font
                ws[f'B{row+i}'].border = border
                ws[f'B{row+i}'].alignment = left_alignment
            
            row += len(fuel_info) + 1
            
            # Водитель
            ws.merge_cells(f'A{row}:H{row}')
            section_cell = ws[f'A{row}']
            section_cell.value = "👤 ВОДИТЕЛЬ"
            section_cell.font = section_font
            section_cell.fill = section_fill
            section_cell.alignment = left_alignment
            section_cell.border = border
            
            row += 1
            daily_pay = params["daily_rate"] * params["days"] if params["use_daily"] else 0
            
            driver_info = [
                ("Процент от выручки:", f"{params['driver_percent']}%"),
                ("Фиксированная ставка:", f"{params['driver_fixed']} ₽/рейс"),
                ("Суточные:", f"{params['daily_rate']} ₽/день" if params["use_daily"] else "не учитываются"),
                ("Количество дней:", params['days'] if params["use_daily"] else "-"),
                ("Всего суточные:", f"{daily_pay:,.2f} ₽" if params["use_daily"] else "0 ₽"),
            ]
            
            for i, (label, value) in enumerate(driver_info):
                ws[f'A{row+i}'] = label
                ws[f'A{row+i}'].font = bold_cell_font
                ws[f'A{row+i}'].border = border
                ws[f'A{row+i}'].alignment = left_alignment
                
                ws[f'B{row+i}'] = value
                ws[f'B{row+i}'].font = cell_font
                ws[f'B{row+i}'].border = border
                ws[f'B{row+i}'].alignment = left_alignment
            
            row += len(driver_info) + 2
            
            # Тарифы
            ws.merge_cells(f'A{row}:H{row}')
            section_cell = ws[f'A{row}']
            section_cell.value = "💰 СРАВНЕНИЕ ТАРИФОВ"
            section_cell.font = section_font
            section_cell.fill = section_fill
            section_cell.alignment = left_alignment
            section_cell.border = border
            
            row += 1
            
            # Заголовки таблицы
            headers = ["Тариф", "Ставка", "Выручка", "Топливо", "З/п (%)", "З/п (фикс)", "Суточные", "Прибыль"]
            for col, header in enumerate(headers, 1):
                cell = ws.cell(row=row, column=col, value=header)
                cell.font = header_font
                cell.fill = header_fill
                cell.alignment = center_alignment
                cell.border = border
            
            row += 1
            
            # Получаем результаты расчета
            results = []
            revenue_km = params["distance_ab"] * trips
            total_tons = tons_per_trip * trips
            daily_pay = params["daily_rate"] * params["days"] if params["use_daily"] else 0
            
            # За тонну
            if params["tariff_ton"]:
                revenue = total_tons * params["rate_ton"]
                driver_percent = revenue * params["driver_percent"] / 100
                driver_fixed = params["driver_fixed"] * trips
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_fixed - daily_pay
                
                # Строка для процента
                row_data = [
                    "За тонну (%)",
                    f"{params['rate_ton']:.2f} ₽/т",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_percent:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:  # Колонка с прибылью
                        if profit_percent > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
                
                row += 1
                
                # Строка для фикса
                row_data = [
                    "За тонну (фикс)",
                    f"{params['rate_ton']:.2f} ₽/т",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_fixed:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:
                        if profit_fixed > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
                
                row += 1
            
            # За тонно-км
            if params["tariff_tkm"]:
                revenue = tons_per_trip * trips * params["distance_ab"] * params["rate_tkm"]
                driver_percent = revenue * params["driver_percent"] / 100
                driver_fixed = params["driver_fixed"] * trips
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_fixed - daily_pay
                
                row_data = [
                    "За т/км (%)",
                    f"{params['rate_tkm']:.2f} ₽/т/км",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_percent:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:
                        if profit_percent > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
                
                row += 1
                
                row_data = [
                    "За т/км (фикс)",
                    f"{params['rate_tkm']:.2f} ₽/т/км",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_fixed:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:
                        if profit_fixed > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
                
                row += 1
            
            # Почасовой
            if params["tariff_hourly"]:
                revenue = params["hours"] * params["rate_hourly"]
                driver_percent = revenue * params["driver_percent"] / 100
                driver_fixed = params["driver_fixed"] * trips
                profit_percent = revenue - fuel_data['fuel_cost'] - driver_percent - daily_pay
                profit_fixed = revenue - fuel_data['fuel_cost'] - driver_fixed - daily_pay
                
                row_data = [
                    "Почасовая (%)",
                    f"{params['rate_hourly']:.2f} ₽/ч",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_percent:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:
                        if profit_percent > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
                
                row += 1
                
                row_data = [
                    "Почасовая (фикс)",
                    f"{params['rate_hourly']:.2f} ₽/ч",
                    f"{revenue:,.2f} ₽",
                    f"{fuel_data['fuel_cost']:,.2f} ₽",
                    f"{driver_percent:,.2f} ₽",
                    f"{driver_fixed:,.2f} ₽",
                    f"{daily_pay:,.2f} ₽",
                    f"{profit_fixed:,.2f} ₽"
                ]
                
                for col, value in enumerate(row_data, 1):
                    cell = ws.cell(row=row, column=col, value=value)
                    cell.font = cell_font
                    cell.alignment = right_alignment if col > 1 else left_alignment
                    cell.border = border
                    if col == 8:
                        if profit_fixed > 0:
                            cell.font = Font(name='Arial', size=10, bold=True, color="2E7D32")
                        else:
                            cell.font = Font(name='Arial', size=10, bold=True, color="B71C1C")
            
            # Автоподбор ширины колонок
            for col in range(1, 9):
                column_letter = get_column_letter(col)
                ws.column_dimensions[column_letter].width = 15
            ws.column_dimensions['A'].width = 20  # Колонка с названиями шире
            
            # Сохраняем файл
            wb.save(filename)
            
            QMessageBox.information(
                self,
                "Готово",
                f"✅ Расчет успешно экспортирован!\n\nФайл сохранен:\n{filename}"
            )
            
        except Exception as e:
            QMessageBox.critical(self, "Ошибка", f"Не удалось экспортировать:\n{str(e)}")