-- ====================================================
-- 数据统计表补充 BaseEntity 基础字段（company_id, create_time, update_time）
-- 发布日期：2026-06-11
-- ====================================================

DROP PROCEDURE IF EXISTS add_stat_base_columns;
DELIMITER //
CREATE PROCEDURE add_stat_base_columns()
BEGIN
    -- t_daily_stat 补字段
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'company_id'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `company_id` BIGINT DEFAULT NULL COMMENT '公司（租户）ID' AFTER `orders_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 = 'create_time'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `company_id`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_daily_stat'
          AND COLUMN_NAME = 'update_time'
    ) THEN
        ALTER TABLE `t_daily_stat`
            ADD COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' AFTER `create_time`;
    END IF;

    -- t_month_stat 补字段
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'company_id'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `company_id` BIGINT DEFAULT NULL COMMENT '公司（租户）ID' AFTER `orders_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 = 'create_time'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `company_id`;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 't_month_stat'
          AND COLUMN_NAME = 'update_time'
    ) THEN
        ALTER TABLE `t_month_stat`
            ADD COLUMN `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' AFTER `create_time`;
    END IF;
END //
DELIMITER ;
CALL add_stat_base_columns();
DROP PROCEDURE IF EXISTS add_stat_base_columns;
