-- ============================================================
-- 用户表架构迁移脚本
-- 从旧 user_main 表迁移数据到新 User + user_sensitive_data 表
-- 
-- 执行顺序：
--   1. 先执行 python manage.py migrate（创建新表）
--   2. 再执行本 SQL 脚本（迁移数据）
--   3. 最后删除旧表（确认无误后）
-- ============================================================

-- ============================================================
-- 第1步：从 user_main 迁移数据到 User 表
-- ============================================================

-- User 表：核心身份字段
INSERT INTO `User` (
    `UserUUID`,
    `UserName`,
    `UserPassword`,
    `UserPositionStatus`,
    `UserPersonalSignature`,
    `UserEmail`,
    `UserEmailVerify`,
    `UserAccountLicense`,
    `UserGender`,
    `UserTele`,
    `UserCreateTime`,
    `UserLastLoginDate`,
    `IsStaff`,
    `IsSuperuser`,
    `YonghuID`,
    `UserAvatar`,
    `UserType`
)
SELECT
    UNHEX(REPLACE(UUID(), '-', '')),           -- 生成 16 字节 UUID
    COALESCE(yonghuid, openid),                 -- UserName = yonghuid 或 openid
    COALESCE(password, ''),                     -- UserPassword
    0,                                          -- UserPositionStatus
    '',                                         -- UserPersonalSignature
    '',                                         -- UserEmail
    0,                                          -- UserEmailVerify
    1,                                          -- UserAccountLicense (启用)
    -1,                                         -- UserGender
    phone,                                      -- UserTele
    create_time,                                -- UserCreateTime
    COALESCE(last_login_time, create_time),     -- UserLastLoginDate
    CASE WHEN user_type = 'admin' THEN 1 ELSE 0 END,  -- IsStaff
    CASE WHEN user_type = 'admin' THEN 1 ELSE 0 END,  -- IsSuperuser
    yonghuid,                                   -- YonghuID
    COALESCE(avatar, 'a_long/morentouxiang.jpg'), -- UserAvatar
    user_type                                   -- UserType
FROM `user_main`
WHERE yonghuid IS NOT NULL AND yonghuid != '';

-- ============================================================
-- 第2步：迁移敏感数据到 user_sensitive_data 表
-- ============================================================

INSERT INTO `user_sensitive_data` (
    `UserUUID_id`,
    `OpenID`,
    `UnionID`,
    `Password`,
    `PhoneVerified`,
    `Zhifu`,
    `SKZhanghao`,
    `IP`,
    `create_time`,
    `update_time`
)
SELECT
    u.`UserUUID`,
    um.openid,
    um.unionid,
    um.password,
    um.shoujihao_renzheng,
    um.zhifu,
    um.skzhanghao,
    um.ip,
    um.create_time,
    NOW()
FROM `user_main` um
JOIN `User` u ON u.`YonghuID` = um.yonghuid;

-- ============================================================
-- 第3步：更新扩展表的外键引用
-- 扩展表（user_dashou, user_shangjia 等）的 user_id 原来指向 user_main.id（自增整数）
-- 现在需要改为指向 User.UserUUID（16字节二进制）
-- ============================================================

-- user_boss
UPDATE `user_boss` ub
JOIN `user_main` um ON um.id = ub.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET ub.user_id = u.`UserUUID`;

-- user_dashou
UPDATE `user_dashou` ud
JOIN `user_main` um ON um.id = ud.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET ud.user_id = u.`UserUUID`;

-- user_shangjia
UPDATE `user_shangjia` us
JOIN `user_main` um ON um.id = us.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET us.user_id = u.`UserUUID`;

-- user_guanshi
UPDATE `user_guanshi` ug
JOIN `user_main` um ON um.id = ug.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET ug.user_id = u.`UserUUID`;

-- user_zuzhang
UPDATE `user_zuzhang` uz
JOIN `user_main` um ON um.id = uz.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET uz.user_id = u.`UserUUID`;

-- user_shenheguan
UPDATE `user_shenheguan` ush
JOIN `user_main` um ON um.id = ush.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET ush.user_id = u.`UserUUID`;

-- admin_profile
UPDATE `admin_profile` ap
JOIN `user_main` um ON um.id = ap.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET ap.user_id = u.`UserUUID`;

-- user_kefu
UPDATE `user_kefu` uk
JOIN `user_main` um ON um.id = uk.user_id
JOIN `User` u ON u.`YonghuID` = um.yonghuid
SET uk.user_id = u.`UserUUID`;

-- ============================================================
-- 第4步：更新 yonghu_dianpu_bangding 表的 to_field 引用
-- 原来用 to_field='yonghuid' 关联 user_main.yonghuid
-- 现在用 to_field='YonghuID' 关联 User.YonghuID
-- 数据本身不需要变（yonghuid 值相同），但需要确认列名
-- ============================================================

-- yonghu_dianpu_bangding 的 yonghu_id 列存储的是 yonghuid 字符串值
-- 新模型 to_field='YonghuID'，列名变为 yonghu_id（Django 自动生成）
-- 如果旧列名也是 yonghu_id，则数据不需要迁移

-- ============================================================
-- 第5步：验证数据完整性
-- ============================================================

-- 验证 User 表行数 = user_main 表行数
SELECT 'User count' AS check_name, COUNT(*) AS cnt FROM `User`
UNION ALL
SELECT 'user_main count', COUNT(*) FROM `user_main`
UNION ALL
SELECT 'user_sensitive_data count', COUNT(*) FROM `user_sensitive_data`
UNION ALL
SELECT 'user_dashou count', COUNT(*) FROM `user_dashou`
UNION ALL
SELECT 'user_shangjia count', COUNT(*) FROM `user_shangjia`;

-- 验证所有扩展表的 user_id 都能匹配到 User 表
SELECT 'orphan user_dashou' AS check_name, COUNT(*) AS cnt
FROM `user_dashou` ud LEFT JOIN `User` u ON u.`UserUUID` = ud.user_id
WHERE u.`UserUUID` IS NULL
UNION ALL
SELECT 'orphan user_shangjia', COUNT(*)
FROM `user_shangjia` us LEFT JOIN `User` u ON u.`UserUUID` = us.user_id
WHERE u.`UserUUID` IS NULL;

-- ============================================================
-- 第6步：确认无误后删除旧表（手动执行）
-- ============================================================
-- DROP TABLE IF EXISTS `user_main`;
-- 注意：删除前请确保所有数据已正确迁移！
