#!/usr/bin/env python3
"""
修复数据库中的中文乱码问题
重新插入正确的中文数据
"""
import asyncio
import aiomysql
from pathlib import Path
import sys

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

async def fix_chinese_data():
    """修复中文数据"""
    print("🔧 开始修复数据库中的中文乱码问题...")
    
    # 正确的课程数据
    correct_courses = [
        {
            "id": 1,
            "name": "皮肤生理学基础",
            "description": "学习皮肤结构、功能和常见问题，为专业护理打下基础",
            "category": "technology",
            "status": "published",
            "duration_hours": 16.0,
            "difficulty_level": 2,
            "tags": ["皮肤学", "基础理论", "必修课"],
            "sort_order": 100,
            "is_featured": True
        },
        {
            "id": 2,
            "name": "医美产品知识与应用",
            "description": "全面了解各类医美产品的成分、功效和适用人群",
            "category": "technology",
            "status": "published",
            "duration_hours": 20.0,
            "difficulty_level": 3,
            "tags": ["产品知识", "医美", "专业技能"],
            "sort_order": 110,
            "is_featured": True
        },
        {
            "id": 3,
            "name": "美容仪器操作与维护",
            "description": "掌握各类美容仪器的操作方法、注意事项和日常维护",
            "category": "technology",
            "status": "published",
            "duration_hours": 24.0,
            "difficulty_level": 3,
            "tags": ["仪器操作", "实操技能", "设备维护"],
            "sort_order": 120,
            "is_featured": False
        },
        {
            "id": 4,
            "name": "医美项目介绍与咨询",
            "description": "详细了解各类医美项目的原理、效果和适应症",
            "category": "technology",
            "status": "published",
            "duration_hours": 30.0,
            "difficulty_level": 4,
            "tags": ["医美项目", "专业咨询", "风险告知"],
            "sort_order": 170,
            "is_featured": True
        },
        {
            "id": 5,
            "name": "轻医美销售技巧",
            "description": "学习专业的销售话术、客户需求分析和成交技巧",
            "category": "business",
            "status": "published",
            "duration_hours": 16.0,
            "difficulty_level": 2,
            "tags": ["销售技巧", "客户沟通", "业绩提升"],
            "sort_order": 130,
            "is_featured": True
        },
        {
            "id": 6,
            "name": "客户服务与投诉处理",
            "description": "提升服务意识，掌握客户投诉处理的方法和技巧",
            "category": "business",
            "status": "published",
            "duration_hours": 12.0,
            "difficulty_level": 2,
            "tags": ["客户服务", "危机处理", "沟通技巧"],
            "sort_order": 140,
            "is_featured": False
        },
        {
            "id": 7,
            "name": "社媒营销与私域运营",
            "description": "学习如何通过社交媒体进行品牌推广和客户维护",
            "category": "business",
            "status": "published",
            "duration_hours": 16.0,
            "difficulty_level": 2,
            "tags": ["社媒营销", "私域流量", "客户维护"],
            "sort_order": 180,
            "is_featured": False
        },
        {
            "id": 8,
            "name": "门店运营管理",
            "description": "学习门店日常管理、团队建设和业绩管理",
            "category": "management",
            "status": "published",
            "duration_hours": 20.0,
            "difficulty_level": 3,
            "tags": ["门店管理", "团队管理", "运营策略"],
            "sort_order": 160,
            "is_featured": False
        },
        {
            "id": 9,
            "name": "卫生消毒与感染控制",
            "description": "学习医美机构的卫生标准和消毒流程，确保服务安全",
            "category": "general",
            "status": "published",
            "duration_hours": 8.0,
            "difficulty_level": 1,
            "tags": ["卫生安全", "消毒规范", "合规管理"],
            "sort_order": 150,
            "is_featured": True
        },
        {
            "id": 10,
            "name": "Python编程基础",
            "description": "Python语言入门课程，适合零基础学员",
            "category": "technology",
            "status": "published",
            "duration_hours": 40.0,
            "difficulty_level": 2,
            "tags": ["Python", "编程基础", "入门"],
            "sort_order": 200,
            "is_featured": False
        },
        {
            "id": 11,
            "name": "数据分析基础",
            "description": "学习数据分析方法和工具，提升数据驱动决策能力",
            "category": "technology",
            "status": "published",
            "duration_hours": 32.0,
            "difficulty_level": 3,
            "tags": ["数据分析", "Excel", "可视化"],
            "sort_order": 210,
            "is_featured": False
        }
    ]
    
    # 正确的岗位数据
    correct_positions = [
        {"id": 1, "name": "区域经理", "code": "region_manager", "description": "负责多家门店的运营管理和业绩达成", "status": "active", "skills": ["团队管理", "业绩分析", "战略规划", "客户关系"], "level": "expert", "sort_order": 10},
        {"id": 2, "name": "店长", "code": "store_manager", "description": "负责门店日常运营管理，团队建设和业绩达成", "status": "active", "skills": ["门店管理", "团队建设", "销售管理", "客户维护"], "level": "senior", "sort_order": 20},
        {"id": 3, "name": "美容顾问", "code": "beauty_consultant", "description": "为客户提供专业的美容咨询和方案设计", "status": "active", "skills": ["产品知识", "销售技巧", "方案设计", "客户沟通"], "level": "intermediate", "sort_order": 30},
        {"id": 4, "name": "医美咨询师", "code": "medical_beauty_consultant", "description": "提供医疗美容项目咨询和方案制定", "status": "active", "skills": ["医美知识", "风险评估", "方案设计", "合规意识"], "level": "senior", "sort_order": 35},
        {"id": 5, "name": "美容技师", "code": "beauty_therapist", "description": "为客户提供专业的美容护理服务", "status": "active", "skills": ["护肤技术", "仪器操作", "手法技巧", "服务意识"], "level": "intermediate", "sort_order": 40},
        {"id": 6, "name": "护士", "code": "nurse", "description": "协助医生进行医美项目操作，负责术后护理", "status": "active", "skills": ["护理技术", "无菌操作", "应急处理", "医疗知识"], "level": "intermediate", "sort_order": 45},
        {"id": 7, "name": "前台接待", "code": "receptionist", "description": "负责客户接待、预约管理和前台事务", "status": "active", "skills": ["接待礼仪", "沟通能力", "信息管理", "服务意识"], "level": "junior", "sort_order": 50},
        {"id": 8, "name": "市场专员", "code": "marketing_specialist", "description": "负责门店营销活动策划和执行", "status": "active", "skills": ["活动策划", "社媒运营", "数据分析", "创意设计"], "level": "intermediate", "sort_order": 60}
    ]
    
    # 正确的用户数据
    correct_users = [
        {"id": 1, "username": "superadmin", "full_name": "超级管理员"},
        {"id": 2, "username": "admin", "full_name": "系统管理员"},
        {"id": 3, "username": "testuser", "full_name": "测试学员"}
    ]
    
    try:
        # 连接数据库
        conn = await aiomysql.connect(
            host="localhost",
            port=3306,
            user="root",
            password="root",
            db="kaopeilian",
            charset="utf8mb4",
            use_unicode=True,
            init_command="SET character_set_client=utf8mb4, character_set_connection=utf8mb4, character_set_results=utf8mb4"
        )
        cursor = await conn.cursor()
        
        print("✅ 数据库连接成功")
        
        # 开始事务
        await cursor.execute("START TRANSACTION")
        
        # 更新课程数据
        print("\n📚 更新课程数据...")
        for course in correct_courses:
            sql = """
                UPDATE courses SET 
                    name = %s, 
                    description = %s, 
                    tags = %s,
                    updated_at = NOW()
                WHERE id = %s
            """
            tags_json = str(course["tags"]).replace("'", '"')
            await cursor.execute(sql, (course["name"], course["description"], tags_json, course["id"]))
            print(f"  ✅ 更新课程: {course['name']}")
        
        # 更新岗位数据
        print("\n👥 更新岗位数据...")
        for position in correct_positions:
            sql = """
                UPDATE positions SET 
                    name = %s, 
                    description = %s, 
                    skills = %s,
                    updated_at = NOW()
                WHERE id = %s
            """
            skills_json = str(position["skills"]).replace("'", '"')
            await cursor.execute(sql, (position["name"], position["description"], skills_json, position["id"]))
            print(f"  ✅ 更新岗位: {position['name']}")
        
        # 更新用户数据
        print("\n👤 更新用户数据...")
        for user in correct_users:
            sql = """
                UPDATE users SET 
                    full_name = %s,
                    updated_at = NOW()
                WHERE id = %s
            """
            await cursor.execute(sql, (user["full_name"], user["id"]))
            print(f"  ✅ 更新用户: {user['full_name']}")
        
        # 提交事务
        await cursor.execute("COMMIT")
        print("\n✅ 所有数据更新完成！")
        
        # 验证更新结果
        print("\n🔍 验证更新结果...")
        await cursor.execute("SELECT id, name FROM courses LIMIT 3")
        courses = await cursor.fetchall()
        for course_id, course_name in courses:
            print(f"  课程 {course_id}: {course_name}")
        
        await cursor.execute("SELECT id, name FROM positions LIMIT 3")
        positions = await cursor.fetchall()
        for pos_id, pos_name in positions:
            print(f"  岗位 {pos_id}: {pos_name}")
        
        await cursor.execute("SELECT id, full_name FROM users LIMIT 3")
        users = await cursor.fetchall()
        for user_id, user_name in users:
            print(f"  用户 {user_id}: {user_name}")
        
        await cursor.close()
        conn.close()
        
        print("\n🎉 中文乱码修复完成！")
        
    except Exception as e:
        print(f"❌ 修复失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(fix_chinese_data())
