# -*- coding: utf-8 -*-
"""Main tab views."""

from util.runtime import *
from util.utils import node_host_only, _server_id_sort_key
from models.config import Config, apply_terminal_launch_config
from controllers.workers import (
    CommandRunner,
    GroupedNodeStatusCheckWorker,
    NodeStatusCheckWorker,
    StopServerWorker,
)
from views.common import (
    NoWheelComboBox,
    NoWheelDateTimeEdit,
    NoWheelSpinBox,
    ServerIdTableItem,
    apply_button_style,
    make_line_icon,
    set_button_icon,
)
from views.console import OutputConsole
from views.dialogs import (
    ClearDatabaseDialog,
    KvConfigEditDialog,
    RemoteConnectDialog,
    ServerSelectDialog,
    ViewAccountsDialog,
)


class ServerManageUiMixin:

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        layout.setContentsMargins(10, 10, 10, 10)

        run_dir = self.config.get('workspace', 'run_dir', default='')
        if not run_dir and self.config.get('workspace', 'server_root', default=''):
            run_dir = str(Path(self.config.get('workspace', 'server_root', default='')) / 'run')

        path_bar = QFrame()
        path_bar.setObjectName("serverManagePathBar")
        path_bar.setStyleSheet("""
            QFrame#serverManagePathBar {
                background-color: #242932;
                border: 1px solid #3a4352;
                border-radius: 8px;
            }
        """)
        path_layout = QHBoxLayout(path_bar)
        path_layout.setContentsMargins(14, 8, 14, 8)
        path_layout.setSpacing(10)
        path_icon = QLabel()
        path_icon.setPixmap(make_line_icon("folder", "#4f8cff", 18).pixmap(18, 18))
        path_layout.addWidget(path_icon)
        path_label = QLabel(f"运行目录：  {run_dir or '未配置'}")
        path_label.setStyleSheet("color: #aab4c3; font-size: 12px;")
        path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        path_layout.addWidget(path_label, 1)
        layout.addWidget(path_bar)
        
        # 服务器列表选项卡
        self.server_tabs = QTabWidget()
        self.server_tabs.setStyleSheet("""
            QTabWidget::pane {
                border: 1px solid #3a4352;
                border-radius: 8px;
                background-color: #242932;
            }
            QTabBar::tab {
                background-color: #242932;
                color: #aab4c3;
                padding: 9px 20px;
                margin-right: 4px;
                border-bottom: 2px solid transparent;
            }
            QTabBar::tab:selected {
                color: #4f8cff;
                border-bottom: 2px solid #4f8cff;
            }
            QTabBar::tab:hover:!selected {
                color: #4f8cff;
            }
        """)
        
        # === 本地服务器选项卡 ===
        local_widget = QWidget()
        local_layout = QVBoxLayout(local_widget)
        local_layout.setSpacing(10)
        local_layout.setContentsMargins(10, 10, 10, 10)
        
        # 刷新按钮行
        refresh_layout = QHBoxLayout()
        
        refresh_btn = QPushButton("刷新列表")
        refresh_btn.clicked.connect(self.refresh_server_list)
        self._style_toolbar_button(refresh_btn)
        set_button_icon(refresh_btn, "refresh", "#242932", 16)
        refresh_layout.addWidget(refresh_btn)
        
        self.refresh_status_btn = QPushButton("刷新状态")
        self._style_toolbar_button(self.refresh_status_btn)
        set_button_icon(self.refresh_status_btn, "refresh", "#242932", 16)
        self.refresh_status_btn.clicked.connect(self._refresh_server_status)
        refresh_layout.addWidget(self.refresh_status_btn)
        
        self.local_status_label = QLabel("")
        self.local_status_label.setStyleSheet("color: #aab4c3;")
        refresh_layout.addWidget(self.local_status_label)
        refresh_layout.addStretch()
        
        local_layout.addLayout(refresh_layout)
        
        self.server_list = QTableWidget(0, 5)
        self.server_list.setHorizontalHeaderLabels(["服务器名称", "类型", "状态", "配置", "操作"])
        for col in range(5):
            self.server_list.horizontalHeader().setSectionResizeMode(col, QHeaderView.ResizeMode.Fixed)
        self.server_list.verticalHeader().setVisible(False)
        self.server_list.verticalHeader().setDefaultSectionSize(52)
        self.server_list.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.server_list.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        self.server_list.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.server_list.setAlternatingRowColors(False)
        self.server_list.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        self.server_list.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.server_list.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.server_list.setHorizontalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.server_list.installEventFilter(self)
        self.server_list.viewport().installEventFilter(self)
        self.server_list.itemDoubleClicked.connect(self._on_local_server_double_clicked)
        local_layout.addWidget(self.server_list)
        
        # 保存服务器数据用于状态刷新
        self.local_servers_data = {}
        
        self.server_tabs.addTab(local_widget, "本地服务器")
        
        # === 远程服务器选项卡 ===
        remote_widget = QWidget()
        remote_layout = QVBoxLayout(remote_widget)
        remote_layout.setSpacing(10)
        remote_layout.setContentsMargins(10, 10, 10, 10)
        
        # 加载按钮和刷新状态按钮（列表从登录服 RPC 加载，见工具设置中的登录服节点与 Cookie）
        remote_btn_layout = QHBoxLayout()
        load_remote_btn = QPushButton("从登录服加载")
        load_remote_btn.clicked.connect(self._load_remote_servers)
        self._style_toolbar_button(load_remote_btn)
        set_button_icon(load_remote_btn, "download", "#242932", 16)
        remote_btn_layout.addWidget(load_remote_btn)
        
        self.refresh_remote_status_btn = QPushButton("刷新状态")
        self._style_toolbar_button(self.refresh_remote_status_btn)
        set_button_icon(self.refresh_remote_status_btn, "refresh", "#242932", 16)
        self.refresh_remote_status_btn.clicked.connect(self._refresh_remote_server_status)
        remote_btn_layout.addWidget(self.refresh_remote_status_btn)
        
        self.remote_status_label = QLabel("")
        self.remote_status_label.setStyleSheet("font-size: 11px;")
        remote_btn_layout.addWidget(self.remote_status_label)
        remote_btn_layout.addStretch()
        
        remote_layout.addLayout(remote_btn_layout)
        
        # 保存远程服务器数据用于状态刷新
        self.remote_servers_data = {}
        
        # 搜索框
        search_layout = QHBoxLayout()
        search_label = QLabel("搜索:")
        search_layout.addWidget(search_label)
        self.remote_search_input = QLineEdit()
        self.remote_search_input.setPlaceholderText("输入服务器ID、名称或节点过滤...")
        self.remote_search_input.textChanged.connect(self._filter_remote_servers)
        search_layout.addWidget(self.remote_search_input)
        remote_layout.addLayout(search_layout)
        
        self.remote_server_list = QTableWidget(0, 3)
        self.remote_server_list.setHorizontalHeaderLabels(["服务器ID", "服务器名称", "服务器节点"])
        self.remote_server_list.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.remote_server_list.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.remote_server_list.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.remote_server_list.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.remote_server_list.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        self.remote_server_list.setAlternatingRowColors(False)
        self.remote_server_list.setSortingEnabled(True)
        self.remote_server_list.itemDoubleClicked.connect(self._on_remote_server_double_clicked)
        remote_layout.addWidget(self.remote_server_list)
        
        self.server_tabs.addTab(remote_widget, "远程服务器")
        
        list_card = QFrame()
        list_card.setObjectName("serverListCard")
        list_card.setStyleSheet("""
            QFrame#serverListCard {
                background-color: #242932;
                border: 1px solid #3a4352;
                border-radius: 8px;
            }
        """)
        list_card_layout = QVBoxLayout(list_card)
        list_card_layout.setContentsMargins(14, 10, 14, 12)
        list_card_layout.setSpacing(8)
        list_title = QLabel("服务器列表")
        list_title.setStyleSheet("color: #e8eef7; font-size: 14px; font-weight: 700;")
        list_header = QHBoxLayout()
        list_header.setSpacing(8)
        list_icon = QLabel()
        list_icon.setPixmap(make_line_icon("server", "#4f8cff", 18).pixmap(18, 18))
        list_header.addWidget(list_icon)
        list_header.addWidget(list_title)
        list_header.addStretch()
        list_card_layout.addLayout(list_header)
        list_card_layout.addWidget(self.server_tabs, 1)
        layout.addWidget(list_card, 1)
        
        # 连接选项卡切换信号
        self.server_tabs.currentChanged.connect(self._on_tab_changed)
        
        # === 本地服务器操作按钮 ===
        self.local_ops_group = QFrame()
        self.local_ops_group.setObjectName("serverOpsCard")
        local_ops_layout = QGridLayout(self.local_ops_group)
        local_ops_layout.setSpacing(10)
        local_ops_layout.setContentsMargins(14, 10, 14, 10)
        local_ops_layout.setColumnStretch(0, 1)
        self.local_ops_group.setStyleSheet("""
            QFrame#serverOpsCard {
                border: 1px solid #3a4352;
                border-radius: 8px;
                background-color: #242932;
            }
        """)
        
        ops_title = QLabel("服务器操作")
        ops_title.setStyleSheet("color: #e8eef7; font-size: 13px; font-weight: 700;")
        local_ops_layout.addWidget(ops_title, 0, 0)

        generate_btn = self._create_button("生成", self.regenerate_all_server_configs, "#4f8cff")
        generate_btn.setToolTip("重新生成全部本地服务器配置")
        set_button_icon(generate_btn, "refresh", "#242932", 16)
        local_ops_layout.addWidget(generate_btn, 0, 1)

        delete_btn = self._create_button("删除", self.delete_server, "#ff5c6a")
        delete_btn.setToolTip("删除当前选中的服务器")
        set_button_icon(delete_btn, "trash", "#ff5c6a", 16)
        local_ops_layout.addWidget(delete_btn, 0, 2)
        
        layout.addWidget(self.local_ops_group)
        
        # === 远程服务器操作按钮 ===
        self.remote_ops_group = QFrame()
        self.remote_ops_group.setObjectName("remoteOpsCard")
        remote_ops_layout = QHBoxLayout(self.remote_ops_group)
        remote_ops_layout.setSpacing(10)
        remote_ops_layout.setContentsMargins(14, 10, 14, 10)
        self.remote_ops_group.setStyleSheet("""
            QFrame#remoteOpsCard {
                border: 1px solid #3a4352;
                border-radius: 8px;
                background-color: #242932;
            }
        """)
        
        remote_title = QLabel("远程操作")
        remote_title.setStyleSheet("color: #e8eef7; font-size: 13px; font-weight: 700;")
        remote_ops_layout.addWidget(remote_title)
        remote_ops_layout.addStretch()
        remote_remsh_btn = self._create_button("连接", self._remsh_remote_server, "#4f8cff")
        remote_remsh_btn.setToolTip("远程连接")
        set_button_icon(remote_remsh_btn, "link", "#242932", 16)
        remote_ops_layout.addWidget(remote_remsh_btn)
        
        layout.addWidget(self.remote_ops_group)
        self.remote_ops_group.hide()  # 默认隐藏远程操作按钮
        
        # 初始加载服务器列表
        self.refresh_server_list()
        QTimer.singleShot(0, self._apply_local_server_column_widths)

    def eventFilter(self, obj, event):
        if (
            hasattr(self, 'server_list')
            and obj in (self.server_list, self.server_list.viewport())
            and event.type() == QEvent.Type.Resize
        ):
            QTimer.singleShot(0, self._apply_local_server_column_widths)
        return super().eventFilter(obj, event)

    def _apply_local_server_column_widths(self):
        """按当前表格宽度比例分配本地服务器列宽。"""
        if not hasattr(self, 'server_list'):
            return
        width = self.server_list.viewport().width()
        if width <= 0:
            return

        used = 0
        last_col = self.server_list.columnCount() - 1
        for col, ratio in enumerate(self.LOCAL_COLUMN_RATIOS):
            if col == last_col:
                col_width = max(1, width - used)
            else:
                col_width = max(1, int(width * ratio))
                used += col_width
            self.server_list.setColumnWidth(col, col_width)
    
    def _create_button(self, text, callback, color="#3c3c3c"):
        variant = "outline"
        if str(color).lower() in ("#ff5c6a", "#ff5c6a"):
            variant = "danger"
        elif str(color).lower() in ("#25c889", "#1fad75"):
            variant = "success"
        elif str(color).lower() in ("#4f8cff", "#4f8cff"):
            variant = "primary"
        btn = QPushButton(text)
        btn.clicked.connect(callback)
        btn.setFixedHeight(40)
        btn.setMinimumWidth(120)
        btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        apply_button_style(btn, variant)
        return btn

    def _style_toolbar_button(self, btn, color="#4f8cff"):
        variant = "primary" if str(color).lower() in ("#4f8cff", "#4f8cff") else "outline"
        btn.setFixedHeight(35)
        btn.setMinimumWidth(95)
        apply_button_style(btn, variant, compact=True)
    
    def _get_erl_path(self) -> str:
        """获取配置的 Erlang 路径"""
        return self.config.get('erlang', 'r25_path', default='')
