-- 拆分账户信息表：账户基础信息保留在 ccdi_account_info，动态交易画像迁移到 ccdi_account_result。
-- 执行说明：涉及中文内容时请使用 bin/mysql_utf8_exec.sh 执行，确保会话字符集为 utf8mb4。

CREATE TABLE IF NOT EXISTS `ccdi_account_result` (
  `result_id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键，唯一标识',
  `account_no` VARCHAR(240) NOT NULL COMMENT '账户号码(加密存储)',
  `is_self_account` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否本人实控账户：0-否 1-是',
  `monthly_avg_trans_count` INT DEFAULT 0 COMMENT '近6个月平均交易笔数',
  `monthly_avg_trans_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '近6个月平均交易金额',
  `trans_freq_type` VARCHAR(20) DEFAULT 'MEDIUM' COMMENT 'LOW:低频, MEDIUM:中频, HIGH:高频',
  `dr_max_single_amount` DECIMAL(18,2) COMMENT '借方单笔交易最高额',
  `cr_max_single_amount` DECIMAL(18,2) COMMENT '贷方单笔交易最高额',
  `dr_max_daily_amount` DECIMAL(18,2) COMMENT '借方日累计交易最高额',
  `cr_max_daily_amount` DECIMAL(18,2) COMMENT '贷方日累计交易最高额',
  `trans_risk_level` VARCHAR(10) DEFAULT 'LOW' COMMENT '交易风险等级',
  `create_by` VARCHAR(64) DEFAULT NULL COMMENT '创建者',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` VARCHAR(64) DEFAULT NULL COMMENT '更新者',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`result_id`),
  UNIQUE KEY `uk_ccdi_account_result_account_no` (`account_no`),
  KEY `idx_ccdi_account_result_risk_level` (`trans_risk_level`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='账户结果表';

DELIMITER //

DROP PROCEDURE IF EXISTS `migrate_ccdi_account_info_split`//
CREATE PROCEDURE `migrate_ccdi_account_info_split`()
BEGIN
  DECLARE dynamic_column_count INT DEFAULT 0;

  SELECT COUNT(*)
    INTO dynamic_column_count
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ccdi_account_info'
    AND COLUMN_NAME IN (
      'is_self_account',
      'monthly_avg_trans_count',
      'monthly_avg_trans_amount',
      'trans_freq_type',
      'dr_max_single_amount',
      'cr_max_single_amount',
      'dr_max_daily_amount',
      'cr_max_daily_amount',
      'trans_risk_level'
    );

  IF dynamic_column_count = 9 THEN
    INSERT INTO `ccdi_account_result` (
      `account_no`,
      `is_self_account`,
      `monthly_avg_trans_count`,
      `monthly_avg_trans_amount`,
      `trans_freq_type`,
      `dr_max_single_amount`,
      `cr_max_single_amount`,
      `dr_max_daily_amount`,
      `cr_max_daily_amount`,
      `trans_risk_level`,
      `create_by`,
      `create_time`,
      `update_by`,
      `update_time`
    )
    SELECT
      `account_no`,
      COALESCE(`is_self_account`, 1),
      COALESCE(CAST(`monthly_avg_trans_count` AS SIGNED), 0),
      COALESCE(`monthly_avg_trans_amount`, 0.00),
      COALESCE(`trans_freq_type`, 'MEDIUM'),
      `dr_max_single_amount`,
      `cr_max_single_amount`,
      `dr_max_daily_amount`,
      `cr_max_daily_amount`,
      COALESCE(`trans_risk_level`, 'LOW'),
      `create_by`,
      COALESCE(`create_time`, CURRENT_TIMESTAMP),
      `update_by`,
      COALESCE(`update_time`, CURRENT_TIMESTAMP)
    FROM `ccdi_account_info`
    ON DUPLICATE KEY UPDATE
      `is_self_account` = VALUES(`is_self_account`),
      `monthly_avg_trans_count` = VALUES(`monthly_avg_trans_count`),
      `monthly_avg_trans_amount` = VALUES(`monthly_avg_trans_amount`),
      `trans_freq_type` = VALUES(`trans_freq_type`),
      `dr_max_single_amount` = VALUES(`dr_max_single_amount`),
      `cr_max_single_amount` = VALUES(`cr_max_single_amount`),
      `dr_max_daily_amount` = VALUES(`dr_max_daily_amount`),
      `cr_max_daily_amount` = VALUES(`cr_max_daily_amount`),
      `trans_risk_level` = VALUES(`trans_risk_level`),
      `update_by` = VALUES(`update_by`),
      `update_time` = VALUES(`update_time`);

    ALTER TABLE `ccdi_account_info`
      DROP COLUMN `is_self_account`,
      DROP COLUMN `monthly_avg_trans_count`,
      DROP COLUMN `monthly_avg_trans_amount`,
      DROP COLUMN `trans_freq_type`,
      DROP COLUMN `dr_max_single_amount`,
      DROP COLUMN `cr_max_single_amount`,
      DROP COLUMN `dr_max_daily_amount`,
      DROP COLUMN `cr_max_daily_amount`,
      DROP COLUMN `trans_risk_level`;
  ELSEIF dynamic_column_count <> 0 THEN
    SIGNAL SQLSTATE '45000'
      SET MESSAGE_TEXT = 'ccdi_account_info dynamic columns are partially migrated; please check schema before running this migration.';
  END IF;
END//

CALL `migrate_ccdi_account_info_split`()//
DROP PROCEDURE IF EXISTS `migrate_ccdi_account_info_split`//

DELIMITER ;

DELIMITER //

DROP PROCEDURE IF EXISTS `add_ccdi_account_info_bank_scope`//
CREATE PROCEDURE `add_ccdi_account_info_bank_scope`()
BEGIN
  DECLARE column_count INT DEFAULT 0;

  SELECT COUNT(*)
    INTO column_count
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'ccdi_account_info'
    AND COLUMN_NAME = 'bank_scope';

  IF column_count = 0 THEN
    ALTER TABLE `ccdi_account_info`
      ADD COLUMN `bank_scope` VARCHAR(20) NOT NULL DEFAULT 'INTERNAL' COMMENT '账户范围：INTERNAL-行内，EXTERNAL-行外'
      AFTER `account_type`;
  END IF;

  UPDATE `ccdi_account_info`
     SET `bank_scope` = 'INTERNAL'
   WHERE `bank_scope` IS NULL
      OR `bank_scope` = '';
END//

CALL `add_ccdi_account_info_bank_scope`()//
DROP PROCEDURE IF EXISTS `add_ccdi_account_info_bank_scope`//

DELIMITER ;
