-- ====================================================
-- 数据统计模块 V2 数据库变更脚本
-- 扩展日/月统计表字段，新增同步日志表
-- 发布日期：2026-06-11
-- ====================================================

-- ----------------------------
-- 1. t_daily_stat 新增字段
-- ----------------------------
DROP PROCEDURE IF EXISTS add_daily_stat_columns;
DELIMITER //
CREATE PROCEDURE add_daily_stat_columns()
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'total_refund'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `total_refund` INT NOT NULL DEFAULT 0 COMMENT '总退款金额（分）' AFTER `total_income`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'recharge_count'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `recharge_count` INT NOT NULL DEFAULT 0 COMMENT '充值笔数' AFTER `cross_expend`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'refund_count'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `refund_count` INT NOT NULL DEFAULT 0 COMMENT '退款笔数' AFTER `recharge_count`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'active_user_count'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `active_user_count` INT NOT NULL DEFAULT 0 COMMENT '活跃用户数（当日有订单的用户）' AFTER `registrations`;
    END IF;

    -- 添加唯一索引（支持 REPLACE INTO upsert）
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.STATISTICS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND INDEX_NAME = 'uk_station_date'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD UNIQUE INDEX `uk_station_date` (`station_id`, `stat_date`);
    END IF;
END //
DELIMITER ;
CALL add_daily_stat_columns();
DROP PROCEDURE IF EXISTS add_daily_stat_columns;

-- ----------------------------
-- 2. t_month_stat 新增字段
-- ----------------------------
DROP PROCEDURE IF EXISTS add_month_stat_columns;
DELIMITER //
CREATE PROCEDURE add_month_stat_columns()
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'total_refund'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `total_refund` INT NOT NULL DEFAULT 0 COMMENT '总退款金额（分）' AFTER `total_income`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'platform_fee'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `platform_fee` INT NOT NULL DEFAULT 0 COMMENT '平台服务费（分）' AFTER `cross_expend`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'recharge_count'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `recharge_count` INT NOT NULL DEFAULT 0 COMMENT '充值笔数' AFTER `platform_fee`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'refund_count'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `refund_count` INT NOT NULL DEFAULT 0 COMMENT '退款笔数' AFTER `recharge_count`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'active_user_count'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `active_user_count` INT NOT NULL DEFAULT 0 COMMENT '月活跃用户数' AFTER `registrations`;
    END IF;

    -- 添加唯一索引（支持 REPLACE INTO upsert）
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.STATISTICS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND INDEX_NAME = 'uk_station_month'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD UNIQUE INDEX `uk_station_month` (`station_id`, `stat_month`);
    END IF;
END //
DELIMITER ;
CALL add_month_stat_columns();
DROP PROCEDURE IF EXISTS add_month_stat_columns;

-- ----------------------------
-- 3. 新增统计同步日志表
-- ----------------------------
CREATE TABLE IF NOT EXISTS `t_stat_sync_log` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `stat_type` VARCHAR(10) NOT NULL COMMENT '统计类型：DAILY, MONTHLY',
    `stat_key` VARCHAR(10) NOT NULL COMMENT '统计键：日期(YYYY-MM-DD)或月份(YYYY-MM)',
    `station_id` VARCHAR(64) NOT NULL COMMENT '站点ID',
    `sync_status` TINYINT NOT NULL DEFAULT 0 COMMENT '同步状态：0-进行中，1-成功，2-失败',
    `sync_by` BIGINT DEFAULT NULL COMMENT '操作人ID（系统自动为NULL）',
    `sync_by_name` VARCHAR(50) DEFAULT NULL COMMENT '操作人名称',
    `error_msg` VARCHAR(500) DEFAULT NULL COMMENT '错误信息',
    `start_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '开始时间',
    `end_time` DATETIME 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_stat_type_key` (`stat_type`, `stat_key`),
    KEY `idx_station_id` (`station_id`),
    KEY `idx_sync_status` (`sync_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统计同步日志表';

-- ----------------------------
-- 4. 新增权限
-- ----------------------------
-- 先确保父菜单"数据统计"权限存在
INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '数据统计', 'statistics', 0, 6
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'statistics');

-- 获取"数据统计"权限ID并插入子权限
-- 注意：如果上面INSERT是新插入的，LAST_INSERT_ID()会返回新ID；如果已存在，需要手动查询
SET @statistics_pid = (SELECT id FROM `t_permission` WHERE `value` = 'statistics' LIMIT 1);

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '日统计列表', 'dailyStat.list', @statistics_pid, 1
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'dailyStat.list');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '日统计同步', 'dailyStat.sync', @statistics_pid, 2
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'dailyStat.sync');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '月统计列表', 'monthStat.list', @statistics_pid, 3
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'monthStat.list');

INSERT INTO `t_permission` (`name`, `value`, `pid`, `weight`)
SELECT '月统计同步', 'monthStat.sync', @statistics_pid, 4
WHERE NOT EXISTS (SELECT 1 FROM `t_permission` WHERE `value` = 'monthStat.sync');
