-- =====================================================
-- 为 work_order 表添加 supplement 字段
-- 用于管理师补充陪伴员反馈内容
-- 执行日期：2026-01-26
-- =====================================================

-- 方式1：使用存储过程安全添加字段（推荐）
DELIMITER $$

DROP PROCEDURE IF EXISTS add_supplement_column$$

CREATE PROCEDURE add_supplement_column()
BEGIN
    -- 检查字段是否存在
    IF NOT EXISTS (
        SELECT 1 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 'work_order'
          AND COLUMN_NAME = 'supplement'
    ) THEN
        -- 字段不存在，添加字段
        ALTER TABLE `work_order` 
        ADD COLUMN `supplement` TEXT COMMENT '管理师补充内容' AFTER `result`;
        
        SELECT '✅ supplement 字段添加成功' AS result;
    ELSE
        -- 字段已存在
        SELECT '⚠️ supplement 字段已存在，无需添加' AS result;
    END IF;
END$$

DELIMITER ;

-- 执行存储过程
CALL add_supplement_column();

-- 删除存储过程
DROP PROCEDURE IF EXISTS add_supplement_column;

-- =====================================================
-- 验证字段是否添加成功
-- =====================================================
SELECT 
    COLUMN_NAME AS '字段名',
    COLUMN_TYPE AS '字段类型',
    IS_NULLABLE AS '是否可空',
    COLUMN_COMMENT AS '字段注释'
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'work_order'
    AND COLUMN_NAME = 'supplement';

-- =====================================================
-- 可选：数据迁移
-- 如果之前有数据保存在 solution 字段，可以迁移到 supplement
-- =====================================================
-- 查看需要迁移的数据
SELECT 
    id,
    work_type,
    solution,
    supplement
FROM 
    `work_order`
WHERE 
    work_type = 'feedback' 
    AND solution IS NOT NULL 
    AND solution != ''
    AND (supplement IS NULL OR supplement = '');

-- 执行数据迁移（取消注释后执行）
-- UPDATE `work_order` 
-- SET `supplement` = `solution`
-- WHERE 
--     work_type = 'feedback' 
--     AND solution IS NOT NULL 
--     AND solution != ''
--     AND (supplement IS NULL OR supplement = '');

-- =====================================================
-- 完成提示
-- =====================================================
SELECT '✅ 数据库迁移完成！' AS message;
