-- ================================
-- 纪检初核系统 - 员工表字段迁移脚本
-- 功能: 将 org_no 字段改为 dept_id
-- 创建日期: 2026-01-28
-- ================================

-- 备份说明：执行前请先备份数据库

USE `discipline-prelim-check`;

-- ----------------------------
-- 步骤1: 删除旧索引（如果存在）
-- ----------------------------
-- 使用存储过程检查并删除索引
DROP PROCEDURE IF EXISTS drop_index_if_exists;
DELIMITER //
CREATE PROCEDURE drop_index_if_exists()
BEGIN
    DECLARE index_count INT;
    SELECT COUNT(*) INTO index_count
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = 'discipline-prelim-check'
      AND TABLE_NAME = 'ccdi_employee'
      AND INDEX_NAME = 'idx_org_no';

    IF index_count > 0 THEN
        ALTER TABLE `ccdi_employee` DROP INDEX `idx_org_no`;
    END IF;
END //
DELIMITER ;

CALL drop_index_if_exists();
DROP PROCEDURE IF EXISTS drop_index_if_exists;

-- ----------------------------
-- 步骤2: 修改字段名和类型
-- ----------------------------
ALTER TABLE `ccdi_employee`
  CHANGE COLUMN `org_no` `dept_id` BIGINT DEFAULT NULL COMMENT '所属部门ID';

-- ----------------------------
-- 步骤3: 创建新索引
-- ----------------------------
CREATE INDEX `idx_dept_id` ON `ccdi_employee` (`dept_id`);

-- ----------------------------
-- 验证脚本
-- ----------------------------
-- 检查字段是否修改成功
SELECT
  COLUMN_NAME,
  DATA_TYPE,
  COLUMN_TYPE,
  IS_NULLABLE,
  COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'discipline-prelim-check'
  AND TABLE_NAME = 'ccdi_employee'
  AND COLUMN_NAME = 'dept_id';

-- 检查索引是否创建成功
SELECT
  INDEX_NAME,
  COLUMN_NAME
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'discipline-prelim-check'
  AND TABLE_NAME = 'ccdi_employee'
  AND INDEX_NAME = 'idx_dept_id';
