-- ====================================================
-- 结算方案 V2 数据库变更脚本
-- 按月结算模式：每月15日结算上月
-- 发布日期：2026-05-14
-- 修订日期：2026-05-26（V2.1 充值配置站点化 + 跨店分账含赠款）
-- ====================================================

-- ----------------------------
-- 1. 新增结算记录表
-- ----------------------------
CREATE TABLE IF NOT EXISTS `t_settlement_record` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `station_id` VARCHAR(64) NOT NULL COMMENT '站点ID',
    `settlement_period` VARCHAR(7) NOT NULL COMMENT '结算周期，如 2026-05',
    `total_recharge` INT NOT NULL DEFAULT 0 COMMENT '总充值（分）',
    `total_refund` INT NOT NULL DEFAULT 0 COMMENT '总退款（分）',
    `total_cross_income` INT NOT NULL DEFAULT 0 COMMENT '跨店收入（分）',
    `total_cross_expend` INT NOT NULL DEFAULT 0 COMMENT '跨店支出（分）',
    `opening_pending_balance` INT NOT NULL DEFAULT 0 COMMENT '期初待结算余额（分）',
    `closing_pending_balance` INT NOT NULL DEFAULT 0 COMMENT '期末待结算余额（分）',
    `platform_fee_base` INT NOT NULL DEFAULT 0 COMMENT '平台费基数（分）',
    `platform_fee` INT NOT NULL DEFAULT 0 COMMENT '平台费（分）',
    `settlement_amount` INT NOT NULL DEFAULT 0 COMMENT '结算金额（分）',
    `status` TINYINT NOT NULL DEFAULT 0 COMMENT '状态：0-待结算，1-已结算，2-异常结算',
    `remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    KEY `idx_station_id` (`station_id`),
    KEY `idx_settlement_period` (`settlement_period`),
    KEY `idx_status` (`status`),
    UNIQUE KEY `uk_station_period` (`station_id`, `settlement_period`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='站点结算记录表';

-- ----------------------------
-- 2. t_station_account 新增可提现金额
-- ----------------------------
-- MySQL 不支持 IF NOT EXISTS 用于 ALTER ADD COLUMN，采用条件判断方式
DROP PROCEDURE IF EXISTS add_available_balance;
DELIMITER //
CREATE PROCEDURE add_available_balance()
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_station_account'
          AND COLUMN_NAME = 'available_balance'
    ) THEN
        ALTER TABLE `t_station_account`
            ADD COLUMN `available_balance` INT DEFAULT 0 COMMENT '可提现金额（分）— V2结算后更新的可提现额'
            AFTER `station_id`;
    END IF;
END //
DELIMITER ;
CALL add_available_balance();
DROP PROCEDURE IF EXISTS add_available_balance;

-- ----------------------------
-- 3. 开发环境数据清理（生产环境请勿执行）
-- ----------------------------
-- TRUNCATE TABLE `t_station_account`;
-- TRUNCATE TABLE `t_split_record`;
-- TRUNCATE TABLE `t_withdrawn_record`;
-- DELETE FROM `t_station_fee_rate`;
-- DELETE FROM `t_platform_fee_rate` WHERE name != '默认费率';
-- INSERT INTO `t_platform_fee_rate` (name, fee_rate, withdrawal_fee_rate) VALUES ('默认费率', 0.1, 0.006);

-- ----------------------------
-- 4. 新增平台账户表
-- ----------------------------
CREATE TABLE IF NOT EXISTS `t_platform_account` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `total_revenue` INT NOT NULL DEFAULT 0 COMMENT '累计服务费收入（分）',
    `available_balance` INT NOT NULL DEFAULT 0 COMMENT '可用余额（分）',
    `withdrawn_frozen_amount` INT NOT NULL DEFAULT 0 COMMENT '提现冻结金额（分）',
    `withdrawn_amount` INT NOT NULL DEFAULT 0 COMMENT '已提现金额（分）',
    `version` INT NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
    `company_id` BIGINT DEFAULT NULL COMMENT '公司（租户）ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台账户表';

-- 初始化平台账户（仅当表为空时插入）
INSERT INTO `t_platform_account` (`id`, `total_revenue`, `available_balance`, `withdrawn_frozen_amount`, `withdrawn_amount`, `version`)
SELECT 1, 0, 0, 0, 0, 0
WHERE NOT EXISTS (SELECT 1 FROM `t_platform_account` LIMIT 1);

-- ----------------------------
-- 5. 新增平台收入记录表
-- ----------------------------
CREATE TABLE IF NOT EXISTS `t_platform_revenue_record` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `settlement_record_id` BIGINT NOT NULL COMMENT '关联结算单ID',
    `station_id` VARCHAR(64) NOT NULL COMMENT '费用来源站点ID',
    `settlement_period` VARCHAR(7) NOT NULL COMMENT '结算周期',
    `amount` INT NOT NULL DEFAULT 0 COMMENT '收入金额（分）',
    `company_id` BIGINT DEFAULT NULL COMMENT '公司（租户）ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    KEY `idx_settlement_record_id` (`settlement_record_id`),
    KEY `idx_station_id` (`station_id`),
    KEY `idx_settlement_period` (`settlement_period`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='平台服务费收入记录表';

-- ----------------------------
-- 6. 清除虚拟站点（开发环境）
-- ----------------------------
-- DELETE FROM `t_station_account` WHERE `station_id` = '0';

-- ----------------------------
-- 7. V2.1 充值配置站点化（2026-05-26）
-- ----------------------------
ALTER TABLE `t_recharge_config`
    ADD COLUMN `station_id` VARCHAR(64) DEFAULT NULL COMMENT '站点ID，NULL表示平台默认配置'
    AFTER `label`;

-- 为现有配置追加唯一索引（不包含NULL值）
-- CREATE UNIQUE INDEX `uk_station_recharge_amount` ON `t_recharge_config` (`station_id`, `recharge_amount`);

-- ----------------------------
-- 8. V2.1 充值配置权限初始化（2026-05-26）
-- ----------------------------
INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '充值配置列表', 'rechargeConfig.list', 0, 1
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'rechargeConfig.list');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '充值配置新增', 'rechargeConfig.add', 0, 2
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'rechargeConfig.add');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '充值配置修改', 'rechargeConfig.modify', 0, 3
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'rechargeConfig.modify');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '充值配置删除', 'rechargeConfig.remove', 0, 4
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'rechargeConfig.remove');

-- 注意：执行完上述权限记录插入后，需在管理后台「角色管理」中为对应角色勾选充值配置权限
-- 角色权限存储在 t_role.permissions 字段（JSON格式），无法直接通过SQL安全合并

-- ====================================================
-- 9. V2.2 充值配置分组化（2026-05-26）
-- ====================================================

-- 9a. 创建配置分组表
CREATE TABLE IF NOT EXISTS `t_recharge_config_group` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `name` VARCHAR(64) DEFAULT NULL COMMENT '分组名称',
    `is_default` TINYINT(1) DEFAULT 0 COMMENT '是否默认分组（未分配站点的自动使用）',
    `company_id` BIGINT DEFAULT NULL COMMENT '公司（租户）ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='充值配置分组表';

-- 9b. 创建分组-站点关联表
CREATE TABLE IF NOT EXISTS `t_recharge_config_station_group` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `group_id` BIGINT NOT NULL COMMENT '分组ID',
    `station_id` VARCHAR(64) NOT NULL COMMENT '站点ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_station_id` (`station_id`),
    KEY `idx_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='充值配置分组-站点关联表';

-- 9c. 确保 t_recharge_config 有 station_id 列（兼容 V2.1 未执行的情况）
DROP PROCEDURE IF EXISTS add_station_id_if_missing;
DELIMITER //
CREATE PROCEDURE add_station_id_if_missing()
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_recharge_config'
          AND COLUMN_NAME = 'station_id'
    ) THEN
        ALTER TABLE `t_recharge_config`
            ADD COLUMN `station_id` VARCHAR(64) DEFAULT NULL COMMENT '站点ID，NULL表示平台默认配置'
            AFTER `label`;
    END IF;
END //
DELIMITER ;
CALL add_station_id_if_missing();
DROP PROCEDURE IF EXISTS add_station_id_if_missing;

-- 9d. 为已有的 station_id 创建分组（每个唯一 station_id 一个分组）
INSERT INTO `t_recharge_config_group` (`name`, `is_default`, `create_time`, `update_time`)
SELECT DISTINCT NULL, IF(`station_id` IS NULL, 1, 0), NOW(), NOW()
FROM `t_recharge_config`
WHERE NOT EXISTS (
    SELECT 1 FROM `t_recharge_config_group`
);

-- 9e. 确保平台默认分组存在并标记为默认
INSERT INTO `t_recharge_config_group` (`name`, `is_default`, `create_time`, `update_time`)
SELECT NULL, 1, NOW(), NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM `t_recharge_config_group` WHERE `is_default` = 1
);

-- 9f. 将旧 station_id 数据迁入关联表（非NULL的station_id）
INSERT INTO `t_recharge_config_station_group` (`group_id`, `station_id`, `create_time`, `update_time`)
SELECT g.id, c.`station_id`, NOW(), NOW()
FROM (SELECT DISTINCT `station_id` FROM `t_recharge_config` WHERE `station_id` IS NOT NULL) c
INNER JOIN `t_recharge_config_group` g ON IFNULL(g.name, '') = '' AND g.`is_default` = 0
WHERE NOT EXISTS (
    SELECT 1 FROM `t_recharge_config_station_group` sg WHERE sg.`station_id` = c.`station_id`
);

-- 如果上面的 INSERT 未分配成功（group 匹配不上），则为每个非NULL station_id 各自创建分组并关联
INSERT INTO `t_recharge_config_group` (`name`, `is_default`, `create_time`, `update_time`)
SELECT DISTINCT c.`station_id`, 0, NOW(), NOW()
FROM `t_recharge_config` c
WHERE c.`station_id` IS NOT NULL
  AND NOT EXISTS (SELECT 1 FROM `t_recharge_config_station_group` sg WHERE sg.`station_id` = c.`station_id`)
  AND NOT EXISTS (SELECT 1 FROM `t_recharge_config_group` g WHERE g.`name` = c.`station_id`);

INSERT INTO `t_recharge_config_station_group` (`group_id`, `station_id`, `create_time`, `update_time`)
SELECT g.id, g.`name`, NOW(), NOW()
FROM `t_recharge_config_group` g
WHERE g.`is_default` = 0
  AND NOT EXISTS (SELECT 1 FROM `t_recharge_config_station_group` sg WHERE sg.`group_id` = g.id);

-- 9g. t_recharge_config 新增 group_id 列
ALTER TABLE `t_recharge_config`
    ADD COLUMN `group_id` BIGINT DEFAULT NULL COMMENT '所属分组ID'
    AFTER `id`;

-- 9h. 回填 group_id：通过旧 station_id 匹配到关联表的 group_id
UPDATE `t_recharge_config` c
    INNER JOIN `t_recharge_config_station_group` sg ON c.`station_id` = sg.`station_id`
SET c.`group_id` = sg.`group_id`;

-- 9i. station_id 为 NULL 的行归入默认分组
UPDATE `t_recharge_config`
SET `group_id` = (SELECT id FROM `t_recharge_config_group` WHERE `is_default` = 1 LIMIT 1)
WHERE `group_id` IS NULL;

-- 9j. group_id 设为 NOT NULL
ALTER TABLE `t_recharge_config`
    MODIFY COLUMN `group_id` BIGINT NOT NULL COMMENT '所属分组ID';

-- 9k. 删除旧 station_id 列
DROP PROCEDURE IF EXISTS drop_station_id;
DELIMITER //
CREATE PROCEDURE drop_station_id()
BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_recharge_config'
          AND COLUMN_NAME = 'station_id'
    ) THEN
        ALTER TABLE `t_recharge_config` DROP COLUMN `station_id`;
    END IF;
END //
DELIMITER ;
CALL drop_station_id();
DROP PROCEDURE IF EXISTS drop_station_id;

-- 9l. 组内金额唯一约束
ALTER TABLE `t_recharge_config`
    ADD INDEX `idx_group_id` (`group_id`),
    ADD UNIQUE INDEX `uk_group_recharge_amount` (`group_id`, `recharge_amount`);
