# -*- coding: utf-8 -*-
"""Dialog views for destructive actions, selection, remote connect, and KV editing."""

from util.runtime import *
from util.utils import node_host_only, _server_id_sort_key
from models.config import Config
from controllers.workers import ClearDatabaseThread, NodeStatusCheckWorker
from views.common import (
    ServerIdTableItem,
    NoWheelComboBox,
    apply_button_style,
    set_button_icon,
)

class NumericTableWidgetItem(QTableWidgetItem):
    """支持数字排序的表格项"""
    def __init__(self, text, sort_value):
        super().__init__(text)
        self.sort_value = sort_value
    
    def __lt__(self, other):
        if isinstance(other, NumericTableWidgetItem):
            return self.sort_value < other.sort_value
        return super().__lt__(other)


class ViewAccountsDialog(QDialog):
    """查看服务器账号对话框"""
    
    def __init__(self, config: Config, parent=None):
        super().__init__(parent)
        self.config = config
        self.setWindowTitle("查看服务器账号")
        self.setMinimumSize(900, 600)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # 服务器选择区域
        select_layout = QHBoxLayout()
        select_layout.addWidget(QLabel("选择服务器:"))
        
        self.server_combo = NoWheelComboBox()
        self.server_combo.setMinimumWidth(250)
        self._load_servers()
        select_layout.addWidget(self.server_combo)
        
        query_btn = QPushButton("查询")
        query_btn.clicked.connect(self.do_query)
        select_layout.addWidget(query_btn)
        
        select_layout.addStretch()
        layout.addLayout(select_layout)
        
        # 搜索区域
        search_layout = QHBoxLayout()
        search_layout.addWidget(QLabel("搜索:"))
        
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入角色名、角色ID或账号进行搜索...")
        self.search_input.returnPressed.connect(self.do_query)
        search_layout.addWidget(self.search_input)
        
        layout.addLayout(search_layout)
        
        # 数据库信息标签
        self.db_info_label = QLabel("")
        self.db_info_label.setStyleSheet("color: #aab4c3; padding: 5px;")
        layout.addWidget(self.db_info_label)
        
        # 表格显示
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(["角色ID", "角色名", "账号", "等级"])
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.table.setAlternatingRowColors(False)  # 不使用交替行颜色
        self.table.setSortingEnabled(True)  # 启用排序
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)  # 禁止编辑
        layout.addWidget(self.table)
        
        # 状态栏
        self.status_label = QLabel("请选择服务器并点击查询 (点击列头可排序)")
        layout.addWidget(self.status_label)
        
        # 关闭按钮
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.close)
        btn_layout.addWidget(close_btn)
        layout.addLayout(btn_layout)
    
    def _load_servers(self):
        """加载服务器列表"""
        run_dir = self.config.get('workspace', 'run_dir', default='')
        servers = get_server_list(run_dir)
        
        for category, server_list in servers.items():
            for server in sorted(server_list):
                self.server_combo.addItem(server, server)
    
    def do_query(self):
        """执行查询"""
        server_name = self.server_combo.currentData()
        if not server_name:
            self.status_label.setText("请先选择服务器")
            return
        
        search_text = self.search_input.text().strip()
        
        # 获取数据库配置
        try:
            import pymysql
        except ImportError:
            try:
                import mysql.connector as pymysql
            except ImportError:
                self.status_label.setText("错误: 需要安装 pymysql")
                return
        
        # 从合并配置获取数据库信息（kv.config > user.config > project.config > default.config）
        server_root = self.config.get('workspace', 'server_root', default='')
        run_dir = self.config.get('workspace', 'run_dir', default='')
        kv_config_file = Path(run_dir) / server_name / 'config' / 'kv.config'
        
        if not kv_config_file.exists():
            self.status_label.setText(f"找不到服务器配置: {kv_config_file}")
            return
        
        merged_cfg = read_merged_config(server_root, server_name) if server_root else read_config_file(str(kv_config_file))
        db_host = merged_cfg.get('db_host', '127.0.0.1')
        db_port = int(merged_cfg.get('db_port', '3306'))
        db_user = merged_cfg.get('db_user', 'root')
        db_pass = merged_cfg.get('db_pass', '')
        db_name = merged_cfg.get('db_game_name', '')
        
        if not db_name:
            self.status_label.setText("无法获取数据库名称")
            return
        
        self.db_info_label.setText(f"数据库: {db_name} @ {db_host}:{db_port}")
        
        try:
            conn = pymysql.connect(
                host=db_host,
                port=db_port,
                user=db_user,
                password=db_pass,
                database=db_name,
                charset='utf8mb4'
            )
            cursor = conn.cursor()
            
            if search_text:
                sql = """
                    SELECT role_id, role_name, fn_uid, level 
                    FROM role 
                    WHERE role_name LIKE %s OR CAST(role_id AS CHAR) LIKE %s OR fn_uid LIKE %s
                    ORDER BY level DESC, role_id
                    LIMIT 500
                """
                pattern = f'%{search_text}%'
                cursor.execute(sql, (pattern, pattern, pattern))
            else:
                sql = """
                    SELECT role_id, role_name, fn_uid, level 
                    FROM role 
                    ORDER BY level DESC, role_id
                    LIMIT 500
                """
                cursor.execute(sql)
            
            rows = cursor.fetchall()
            
            # 暂停排序更新
            self.table.setSortingEnabled(False)
            
            # 清空并填充表格
            self.table.setRowCount(len(rows))
            
            for row_idx, row in enumerate(rows):
                role_id, role_name, fn_uid, level = row
                
                # 角色ID - 使用数字排序
                id_item = NumericTableWidgetItem(str(role_id), int(role_id) if role_id else 0)
                self.table.setItem(row_idx, 0, id_item)
                
                # 角色名
                name_item = QTableWidgetItem(str(role_name or ''))
                self.table.setItem(row_idx, 1, name_item)
                
                # 账号
                uid_item = QTableWidgetItem(str(fn_uid or ''))
                self.table.setItem(row_idx, 2, uid_item)
                
                # 等级 - 使用数字排序
                level_item = NumericTableWidgetItem(str(level), int(level) if level else 0)
                self.table.setItem(row_idx, 3, level_item)
            
            # 恢复排序
            self.table.setSortingEnabled(True)
            
            status = f"查询完成: {len(rows)} 条记录"
            if search_text:
                status += f" (搜索: {search_text})"
            if len(rows) >= 500:
                status += " (结果已截断，最多显示500条)"
            status += " | 点击列头可排序"
            
            self.status_label.setText(status)
            
            cursor.close()
            conn.close()
            
        except Exception as e:
            self.table.setRowCount(0)
            self.status_label.setText(f"查询失败: {str(e)}")
