-- 检查并修复 study_student_status 字典重复数据
-- 1. 检查是否有重复的字典数据
SELECT 
    dict_type,
    dict_value,
    COUNT(*) as count,
    GROUP_CONCAT(dict_code ORDER BY dict_code) as dict_codes
FROM sys_dict_data
WHERE dict_type = 'study_student_status'
GROUP BY dict_type, dict_value
HAVING COUNT(*) > 1;

-- 2. 查看所有 study_student_status 字典数据
SELECT * FROM sys_dict_data WHERE dict_type = 'study_student_status' ORDER BY dict_sort, dict_code;

-- 3. 删除重复的字典数据（保留 dict_sort 最小的记录）
-- 注意：执行前请先备份数据！
DELETE d1 FROM sys_dict_data d1
INNER JOIN sys_dict_data d2 
WHERE d1.dict_type = 'study_student_status'
  AND d2.dict_type = 'study_student_status'
  AND d1.dict_value = d2.dict_value
  AND d1.dict_code > d2.dict_code;

-- 4. 确保字典数据唯一性（如果还有重复，使用这个更严格的清理）
-- 删除所有重复项，只保留 dict_code 最小的
DELETE d1 FROM sys_dict_data d1
INNER JOIN (
    SELECT dict_type, dict_value, MIN(dict_code) as min_dict_code
    FROM sys_dict_data
    WHERE dict_type = 'study_student_status'
    GROUP BY dict_type, dict_value
    HAVING COUNT(*) > 1
) d2 ON d1.dict_type = d2.dict_type 
    AND d1.dict_value = d2.dict_value
    AND d1.dict_code > d2.min_dict_code;

-- 5. 验证清理后的结果
SELECT * FROM sys_dict_data WHERE dict_type = 'study_student_status' ORDER BY dict_sort, dict_code;

-- 6. 如果字典数据被完全删除，重新插入正确的数据
-- 在押
INSERT INTO `sys_dict_data` (`dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `remark`) 
SELECT 1, '在押', 'incarcerated', 'study_student_status', '', 'primary', 'Y', '0', 'admin', NOW(), '在押状态'
WHERE NOT EXISTS (
    SELECT 1 FROM sys_dict_data 
    WHERE dict_type = 'study_student_status' AND dict_value = 'incarcerated'
);

-- 已释放
INSERT INTO `sys_dict_data` (`dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `remark`) 
SELECT 2, '已释放', 'released', 'study_student_status', '', 'success', 'N', '0', 'admin', NOW(), '已释放状态'
WHERE NOT EXISTS (
    SELECT 1 FROM sys_dict_data 
    WHERE dict_type = 'study_student_status' AND dict_value = 'released'
);

