-- TSP智能助手数据库初始化脚本

-- 创建数据库（如果不存在）
CREATE DATABASE IF NOT EXISTS tsp_assistant CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 使用数据库
USE tsp_assistant;

-- 创建用户表
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('admin', 'user', 'operator') DEFAULT 'user',
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- 创建工单表
CREATE TABLE IF NOT EXISTS work_orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id VARCHAR(50) UNIQUE NOT NULL,
    title VARCHAR(200) NOT NULL,
    description TEXT NOT NULL,
    category VARCHAR(100) NOT NULL,
    priority VARCHAR(20) NOT NULL DEFAULT 'medium',
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    resolution TEXT,
    satisfaction_score FLOAT,

    -- 飞书集成字段
    feishu_record_id VARCHAR(100) UNIQUE,
    assignee VARCHAR(100),
    solution TEXT,
    ai_suggestion TEXT,

    -- 扩展飞书字段
    source VARCHAR(50),
    module VARCHAR(100),
    created_by VARCHAR(100),
    wilfulness VARCHAR(100),
    date_of_close TIMESTAMP NULL,
    vehicle_type VARCHAR(100),
    vin_sim VARCHAR(50),
    app_remote_control_version VARCHAR(100),
    hmi_sw VARCHAR(100),
    parent_record VARCHAR(100),
    has_updated_same_day VARCHAR(50),
    operating_time VARCHAR(100),

    -- 工单分发和权限管理字段
    assigned_module VARCHAR(50),
    module_owner VARCHAR(100),
    dispatcher VARCHAR(100),
    dispatch_time TIMESTAMP NULL,
    region VARCHAR(50),

    INDEX idx_order_id (order_id),
    INDEX idx_status (status),
    INDEX idx_priority (priority),
    INDEX idx_created_at (created_at),
    INDEX idx_assigned_module (assigned_module),
    INDEX idx_region (region),
    INDEX idx_feishu_record_id (feishu_record_id)
);

-- 创建预警表
CREATE TABLE IF NOT EXISTS alerts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    rule_name VARCHAR(100) NOT NULL,
    alert_type VARCHAR(50) NOT NULL,
    level VARCHAR(20) NOT NULL DEFAULT 'info',
    severity VARCHAR(20) NOT NULL DEFAULT 'medium',
    message TEXT NOT NULL,
    data TEXT,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    resolved_at TIMESTAMP NULL,
    INDEX idx_level (level),
    INDEX idx_alert_type (alert_type),
    INDEX idx_severity (severity),
    INDEX idx_is_active (is_active),
    INDEX idx_created_at (created_at)
);

-- 创建对话表
CREATE TABLE IF NOT EXISTS conversations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    work_order_id INT,
    user_message TEXT NOT NULL,
    assistant_response TEXT NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    confidence_score FLOAT,
    knowledge_used TEXT,
    response_time FLOAT,
    FOREIGN KEY (work_order_id) REFERENCES work_orders(id) ON DELETE CASCADE,
    INDEX idx_work_order_id (work_order_id),
    INDEX idx_timestamp (timestamp)
);

-- 创建知识库表
CREATE TABLE IF NOT EXISTS knowledge_entries (
    id INT AUTO_INCREMENT PRIMARY KEY,
    question TEXT NOT NULL,
    answer TEXT NOT NULL,
    category VARCHAR(100) NOT NULL,
    confidence_score FLOAT DEFAULT 0.0,
    usage_count INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE,
    is_verified BOOLEAN DEFAULT FALSE,
    verified_by VARCHAR(100),
    verified_at TIMESTAMP NULL,
    vector_embedding TEXT,
    INDEX idx_category (category),
    INDEX idx_is_active (is_active),
    INDEX idx_is_verified (is_verified)
);

-- 创建工单建议表
CREATE TABLE IF NOT EXISTS work_order_suggestions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    work_order_id INT NOT NULL,
    ai_suggestion TEXT,
    human_resolution TEXT,
    ai_similarity FLOAT,
    approved BOOLEAN DEFAULT FALSE,
    use_human_resolution BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (work_order_id) REFERENCES work_orders(id) ON DELETE CASCADE,
    INDEX idx_work_order_id (work_order_id),
    INDEX idx_approved (approved)
);

-- 创建工单处理过程记录表
CREATE TABLE IF NOT EXISTS work_order_process_history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    work_order_id INT NOT NULL,
    processor_name VARCHAR(100) NOT NULL,
    processor_role VARCHAR(50),
    processor_region VARCHAR(50),
    process_content TEXT NOT NULL,
    action_type VARCHAR(50) NOT NULL,
    previous_status VARCHAR(50),
    new_status VARCHAR(50),
    assigned_module VARCHAR(50),
    process_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (work_order_id) REFERENCES work_orders(id) ON DELETE CASCADE,
    INDEX idx_work_order_id (work_order_id),
    INDEX idx_process_time (process_time),
    INDEX idx_action_type (action_type),
    INDEX idx_processor_name (processor_name)
);

-- 创建系统配置表
CREATE TABLE IF NOT EXISTS system_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    key_name VARCHAR(100) UNIQUE NOT NULL,
    value TEXT,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- 插入默认管理员用户
INSERT IGNORE INTO users (username, email, password_hash, role) VALUES
('admin', 'admin@tsp.com', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPj4J/8K8K8K8', 'admin');

-- 插入默认系统配置
INSERT IGNORE INTO system_settings (key_name, value, description) VALUES
('system_name', 'TSP智能助手', '系统名称'),
('version', '2.0.0', '系统版本'),
('maintenance_mode', 'false', '维护模式'),
('max_concurrent_users', '100', '最大并发用户数'),
('session_timeout', '3600', '会话超时时间（秒）');

-- 创建分析统计表
CREATE TABLE IF NOT EXISTS analytics (
    id INT AUTO_INCREMENT PRIMARY KEY,
    date TIMESTAMP NOT NULL,
    total_orders INT DEFAULT 0,
    resolved_orders INT DEFAULT 0,
    avg_resolution_time FLOAT DEFAULT 0.0,
    satisfaction_avg FLOAT DEFAULT 0.0,
    knowledge_hit_rate FLOAT DEFAULT 0.0,
    category_distribution TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_date (date)
);

-- 创建车辆实时数据表（如果不存在）
CREATE TABLE IF NOT EXISTS vehicle_data (
    id INT AUTO_INCREMENT PRIMARY KEY,
    vehicle_id VARCHAR(50) NOT NULL,
    vehicle_vin VARCHAR(17),
    data_type VARCHAR(50) NOT NULL,
    data_value TEXT NOT NULL,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE,
    INDEX idx_vehicle_id (vehicle_id),
    INDEX idx_vehicle_vin (vehicle_vin),
    INDEX idx_data_type (data_type),
    INDEX idx_timestamp (timestamp)
);
