-- ============================================================
-- 采集分析日志表 + 采集周期汇总表（幂等迁移脚本）
-- 创建时间：2026-05-05
-- 说明：在 cnc_log 库中新增两张按月分区表
--       log_collect_analysis: 每次采集、每台机床的分析记录
--       log_collect_cycle: 每次采集周期的汇总信息
-- 执行前提：USE cnc_log; 已执行 01-init-schema.sql
-- ============================================================

USE cnc_log;

-- -----------------------------------------------------------
-- 1. 采集分析日志表 log_collect_analysis（按月分区）
-- 记录每次采集后对每台机床的数据变化分析
-- -----------------------------------------------------------
DROP TABLE IF EXISTS log_collect_analysis;
CREATE TABLE log_collect_analysis (
    id                  BIGINT AUTO_INCREMENT,
    analysis_time       DATETIME NOT NULL          COMMENT '分析时间（分区键）',
    raw_log_id          BIGINT NOT NULL             COMMENT '关联原始日志ID（log_collect_raw.id）',
    collect_address_id  INT NOT NULL                COMMENT '采集地址ID（关联cnc_collect_address）',
    machine_id          INT NOT NULL                COMMENT '机床ID（关联cnc_machine）',
    analysis_type       VARCHAR(30) NOT NULL        COMMENT '分析类型：NORMAL_UNCHANGED/PART_COUNT_INCREASE/PROGRAM_SWITCH/MANUAL_RESET/DEVICE_ONLINE/DEVICE_OFFLINE/NEW_DEVICE_FOUND/DATA_ANOMALY/COLLECTION_FAILED',
    previous_program    VARCHAR(200) NULL           COMMENT '上一次NC程序名',
    current_program     VARCHAR(200) NULL           COMMENT '本次NC程序名',
    previous_part_count DECIMAL(15,5) NULL          COMMENT '上一次零件计数',
    current_part_count  DECIMAL(15,5) NULL          COMMENT '本次零件计数',
    part_count_delta    DECIMAL(15,5) NULL          COMMENT '零件计数变化量（正=增加，负=减少）',
    previous_status     VARCHAR(20) NULL            COMMENT '上一次设备状态',
    current_status      VARCHAR(20) NULL            COMMENT '本次设备状态',
    analysis_summary    VARCHAR(500) NOT NULL       COMMENT '人类可读的分析摘要',
    analysis_detail     JSON NULL                   COMMENT '完整的字段级对比数据（JSON）',
    created_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id, analysis_time),
    INDEX idx_address_time (collect_address_id, analysis_time),
    INDEX idx_machine_time (machine_id, analysis_time),
    INDEX idx_type_time (analysis_type, analysis_time),
    INDEX idx_raw_log (raw_log_id),
    INDEX idx_program_time (current_program, analysis_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='采集分析日志表（按月分区，记录每次采集对每台机床的数据变化分析）'
  PARTITION BY RANGE (TO_DAYS(analysis_time)) (
    PARTITION p202605 VALUES LESS THAN (TO_DAYS('2026-06-01')),
    PARTITION p202606 VALUES LESS THAN (TO_DAYS('2026-07-01')),
    PARTITION p202607 VALUES LESS THAN (TO_DAYS('2026-08-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
  );

-- -----------------------------------------------------------
-- 2. 采集周期汇总表 log_collect_cycle（按月分区）
-- 记录每次采集周期（一个地址的一次完整采集）的汇总信息
-- -----------------------------------------------------------
DROP TABLE IF EXISTS log_collect_cycle;
CREATE TABLE log_collect_cycle (
    id                  BIGINT AUTO_INCREMENT,
    cycle_time          DATETIME NOT NULL           COMMENT '周期开始时间（分区键）',
    collect_address_id  INT NOT NULL                COMMENT '采集地址ID（关联cnc_collect_address）',
    raw_log_id          BIGINT NOT NULL             COMMENT '关联原始日志ID（log_collect_raw.id）',
    end_time            DATETIME NULL               COMMENT '周期结束时间',
    duration_ms         INT NULL                    COMMENT '本次采集总耗时（毫秒）',
    total_machines      INT NOT NULL DEFAULT 0      COMMENT '本周期采集的机床总数',
    success_count       INT NOT NULL DEFAULT 0      COMMENT '成功采集的机床数',
    fail_count          INT NOT NULL DEFAULT 0      COMMENT '失败采集的机床数',
    change_distribution JSON NULL                   COMMENT '变化类型分布（如 {"PROGRAM_SWITCH":2,"PART_COUNT_INCREASE":5,"NORMAL_UNCHANGED":3}）',
    has_anomaly         TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否存在异常（1=有异常：DATA_ANOMALY/COLLECTION_FAILED/DEVICE_OFFLINE）',
    cycle_summary       VARCHAR(500) NULL           COMMENT '人类可读的周期汇总',
    created_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id, cycle_time),
    INDEX idx_address_time (collect_address_id, cycle_time),
    INDEX idx_time (cycle_time),
    INDEX idx_anomaly_time (has_anomaly, cycle_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='采集周期汇总表（按月分区，每次采集周期的汇总信息）'
  PARTITION BY RANGE (TO_DAYS(cycle_time)) (
    PARTITION p202605 VALUES LESS THAN (TO_DAYS('2026-06-01')),
    PARTITION p202606 VALUES LESS THAN (TO_DAYS('2026-07-01')),
    PARTITION p202607 VALUES LESS THAN (TO_DAYS('2026-08-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
  );

-- -----------------------------------------------------------
-- 3. 为现有 log_collect_raw 表增加补充索引
-- 支持按采集成功/失败筛选，以及按响应时长分析
-- -----------------------------------------------------------
-- 检查索引是否已存在，若不存在则添加（幂等）
SET @exist := (SELECT COUNT(*) FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = 'cnc_log' AND TABLE_NAME = 'log_collect_raw' AND INDEX_NAME = 'idx_success_time');
SET @sqlstmt := IF(@exist = 0,
    'ALTER TABLE cnc_log.log_collect_raw ADD INDEX idx_success_time (is_success, request_time)',
    'SELECT ''索引 idx_success_time 已存在，跳过''');
PREPARE stmt FROM @sqlstmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
