#!/bin/bash
# ============================================================
# 脚本名称：fix_charset.sh
# 功能说明：修复数据库字符集和乱码问题
# 作 者：pangu
# 创建时间：2026-01-31
# 使用方法：./fix_charset.sh
# ============================================================

set -e

# 数据库配置
DB_HOST="8.148.25.55"
DB_PORT="3306"
DB_USER="root"
DB_PASS="aly2024A"
DB_NAME="pguser-db"

echo "============================================================"
echo "数据库字符集检查与修复工具"
echo "============================================================"
echo ""

# 1. 检查数据库字符集
echo "1. 检查数据库字符集配置..."
mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 -e "
SHOW VARIABLES LIKE 'character_set%';
" 2>&1 | grep -v "Warning"

echo ""

# 2. 检查sys_menu表字符集
echo "2. 检查sys_menu表字符集..."
mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 "$DB_NAME" -e "
SELECT 
    TABLE_NAME,
    TABLE_COLLATION,
    COLUMN_NAME,
    COLUMN_TYPE,
    CHARACTER_SET_NAME,
    COLLATION_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = '$DB_NAME'
  AND TABLE_NAME = 'sys_menu'
  AND COLUMN_NAME IN ('menu_name', 'remark');
" 2>&1 | grep -v "Warning"

echo ""

# 3. 测试查询菜单数据
echo "3. 测试查询菜单数据（检查是否有乱码）..."
mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 "$DB_NAME" -e "
SELECT menu_id, menu_name, remark 
FROM sys_menu 
WHERE parent_id = 0 
ORDER BY order_num;
" 2>&1 | grep -v "Warning"

echo ""
echo "4. 如果上面显示有乱码，是否修复表字符集？(y/n): "
read -p "" confirm

if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    echo ""
    echo "正在修复sys_menu表字符集..."
    
    # 备份表
    echo "  - 创建备份表..."
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 "$DB_NAME" -e "
    CREATE TABLE IF NOT EXISTS sys_menu_backup_charset AS SELECT * FROM sys_menu;
    " 2>&1 | grep -v "Warning"
    
    # 转换表字符集
    echo "  - 转换表字符集为utf8mb4..."
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 "$DB_NAME" -e "
    ALTER TABLE sys_menu CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
    " 2>&1 | grep -v "Warning"
    
    echo ""
    echo "✅ 字符集修复完成！"
    echo ""
    echo "验证修复结果："
    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" --default-character-set=utf8mb4 "$DB_NAME" -e "
    SELECT menu_id, menu_name, remark 
    FROM sys_menu 
    WHERE parent_id = 0 
    ORDER BY order_num;
    " 2>&1 | grep -v "Warning"
else
    echo ""
    echo "❌ 操作已取消"
fi

echo ""
echo "============================================================"
echo "检查完成！"
echo "============================================================"
