-- =============================================
-- CNC机床数据采集系统 - 数据库初始化脚本
-- MariaDB 11.8 + UTF8MB4
-- 生成时间: 2026-04-28
-- =============================================

-- 创建数据库
CREATE DATABASE IF NOT EXISTS cnc_business DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS cnc_log DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- =============================================
-- 业务库 cnc_business（17张表）
-- =============================================
USE cnc_business;

-- 2.1 车间表
CREATE TABLE IF NOT EXISTS cnc_workshop (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    name        VARCHAR(100) NOT NULL UNIQUE,
    sort_order  INT NOT NULL DEFAULT 0,
    is_enabled  TINYINT(1) NOT NULL DEFAULT 1,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='车间表';

-- 2.2 品牌模板表
CREATE TABLE IF NOT EXISTS cnc_brand (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    brand_name      VARCHAR(50) NOT NULL UNIQUE,
    device_field    VARCHAR(50) NOT NULL DEFAULT 'device',
    tags_path       VARCHAR(100) NOT NULL DEFAULT 'tags',
    is_enabled      TINYINT(1) NOT NULL DEFAULT 1,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CNC品牌模板表';

-- 2.3 品牌字段映射表
CREATE TABLE IF NOT EXISTS cnc_brand_field_mapping (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    brand_id        INT NOT NULL,
    standard_field  VARCHAR(50) NOT NULL,
    field_name      VARCHAR(50) NOT NULL,
    match_by        VARCHAR(20) NOT NULL DEFAULT 'id',
    data_type       VARCHAR(20) NOT NULL DEFAULT 'string',
    is_required     TINYINT(1) NOT NULL DEFAULT 0,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (brand_id) REFERENCES cnc_brand(id) ON DELETE CASCADE,
    UNIQUE KEY uk_brand_standard (brand_id, standard_field)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='品牌字段映射表';

-- 2.4 采集地址表
CREATE TABLE IF NOT EXISTS cnc_collect_address (
    id                INT AUTO_INCREMENT PRIMARY KEY,
    name              VARCHAR(100) NOT NULL,
    url               VARCHAR(500) NOT NULL,
    brand_id          INT NOT NULL,
    collect_interval  INT NOT NULL DEFAULT 30,
    is_enabled        TINYINT(1) NOT NULL DEFAULT 1,
    last_collect_time DATETIME NULL,
    last_collect_status VARCHAR(20) NULL,
    fail_count        INT NOT NULL DEFAULT 0,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (brand_id) REFERENCES cnc_brand(id),
    INDEX idx_brand (brand_id),
    INDEX idx_enabled (is_enabled)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采集地址表';

-- 2.5 机床表
CREATE TABLE IF NOT EXISTS cnc_machine (
    id                  INT AUTO_INCREMENT PRIMARY KEY,
    device_code         VARCHAR(100) NOT NULL,
    name                VARCHAR(100) NOT NULL,
    workshop_id         INT NOT NULL,
    collect_address_id  INT NOT NULL,
    ip_address          VARCHAR(50) NOT NULL,
    brand_id            INT NOT NULL,
    is_enabled          TINYINT(1) NOT NULL DEFAULT 1,
    is_online           TINYINT(1) NOT NULL DEFAULT 0,
    last_ping_time      DATETIME NULL,
    last_collect_time   DATETIME NULL,
    last_device_status  VARCHAR(20) NULL,
    last_run_status     VARCHAR(20) NULL,
    last_program_name   VARCHAR(200) NULL,
    last_part_count     DECIMAL(15,5) NULL,
    last_total_part_count DECIMAL(15,5) NULL,
    last_operate_mode   VARCHAR(20) NULL,
    last_machining_status VARCHAR(20) NULL,
    created_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (workshop_id) REFERENCES cnc_workshop(id),
    FOREIGN KEY (collect_address_id) REFERENCES cnc_collect_address(id),
    FOREIGN KEY (brand_id) REFERENCES cnc_brand(id),
    UNIQUE KEY uk_device_code (device_code),
    INDEX idx_workshop (workshop_id),
    INDEX idx_collect_address (collect_address_id),
    INDEX idx_enabled_online (is_enabled, is_online),
    INDEX idx_enabled_address (is_enabled, collect_address_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='CNC机床表';

-- 2.6 工人表
CREATE TABLE IF NOT EXISTS cnc_worker (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    name        VARCHAR(50) NOT NULL,
    code        VARCHAR(50) NOT NULL UNIQUE,
    is_enabled  TINYINT(1) NOT NULL DEFAULT 1,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工人表';

-- 2.7 工人-机床绑定表
CREATE TABLE IF NOT EXISTS cnc_worker_machine (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    worker_id   INT NOT NULL,
    machine_id  INT NOT NULL,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (worker_id) REFERENCES cnc_worker(id) ON DELETE CASCADE,
    FOREIGN KEY (machine_id) REFERENCES cnc_machine(id) ON DELETE CASCADE,
    UNIQUE KEY uk_machine (machine_id),
    INDEX idx_worker (worker_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工人-机床绑定表';

-- 2.8 采集结构化记录表（按月分区）
-- 注意：分区键collect_time必须包含在PRIMARY KEY中，分区表不支持FOREIGN KEY
CREATE TABLE IF NOT EXISTS cnc_collect_record (
    id                    BIGINT AUTO_INCREMENT,
    machine_id            INT NOT NULL,
    collect_time          DATETIME NOT NULL,
    device_time           DATETIME NULL,
    program_name          VARCHAR(200) NULL,
    part_count            DECIMAL(15,5) NULL,
    total_part_count      DECIMAL(15,5) NULL,
    device_status         VARCHAR(20) NULL,
    run_status            VARCHAR(20) NULL,
    operate_mode          VARCHAR(20) NULL,
    spindle_speed_set     DECIMAL(15,5) NULL,
    feed_speed_set        DECIMAL(15,5) NULL,
    spindle_speed_actual  DECIMAL(15,5) NULL,
    feed_speed_actual     DECIMAL(15,5) NULL,
    spindle_load          DECIMAL(15,5) NULL,
    spindle_override      DECIMAL(5,2) NULL,
    power_on_time         DECIMAL(15,2) NULL,
    run_time              DECIMAL(15,2) NULL,
    cutting_time          DECIMAL(15,2) NULL,
    cycle_time            DECIMAL(15,2) NULL,
    machining_status      VARCHAR(20) NULL,
    extra_data            JSON NULL,
    created_at            DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id, collect_time),
    INDEX idx_machine_time (machine_id, collect_time),
    INDEX idx_collect_time (collect_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='采集结构化记录表（按月分区，90天自动清理）'
  PARTITION BY RANGE (TO_DAYS(collect_time)) (
    PARTITION p202604 VALUES LESS THAN (TO_DAYS('2026-05-01')),
    PARTITION p202605 VALUES LESS THAN (TO_DAYS('2026-06-01')),
    PARTITION p202606 VALUES LESS THAN (TO_DAYS('2026-07-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- 2.9 产量分段记录表
CREATE TABLE IF NOT EXISTS cnc_production_segment (
    id                BIGINT AUTO_INCREMENT PRIMARY KEY,
    machine_id        INT NOT NULL,
    program_name      VARCHAR(200) NOT NULL,
    production_date   DATE NOT NULL,
    start_time        DATETIME NOT NULL,
    end_time          DATETIME NULL,
    start_part_count  DECIMAL(15,5) NOT NULL,
    end_part_count    DECIMAL(15,5) NULL,
    quantity          DECIMAL(15,5) NULL,
    is_settled        TINYINT(1) NOT NULL DEFAULT 0,
    close_reason      VARCHAR(30) NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (machine_id) REFERENCES cnc_machine(id),
    INDEX idx_machine_date (machine_id, production_date),
    INDEX idx_machine_date_program (machine_id, production_date, program_name),
    INDEX idx_active (machine_id, is_settled, end_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='产量分段记录表';

-- 2.10 机床日状态表
CREATE TABLE IF NOT EXISTS cnc_machine_daily_status (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    machine_id      INT NOT NULL,
    production_date DATE NOT NULL,
    data_status     VARCHAR(20) NOT NULL DEFAULT 'normal',
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (machine_id) REFERENCES cnc_machine(id),
    UNIQUE KEY uk_machine_date (machine_id, production_date),
    INDEX idx_date_status (production_date, data_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='机床日状态表';

-- 2.11 日汇总表（按机床+程序）
CREATE TABLE IF NOT EXISTS cnc_daily_production (
    id                INT AUTO_INCREMENT PRIMARY KEY,
    machine_id        INT NOT NULL,
    production_date   DATE NOT NULL,
    program_name      VARCHAR(200) NOT NULL,
    total_quantity    DECIMAL(15,5) NOT NULL DEFAULT 0,
    segment_count     INT NOT NULL DEFAULT 1,
    total_run_time    DECIMAL(15,2) NULL,
    total_cutting_time DECIMAL(15,2) NULL,
    total_cycle_time  DECIMAL(15,2) NULL,
    is_adjusted       TINYINT(1) NOT NULL DEFAULT 0,
    adjusted_quantity DECIMAL(15,5) NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (machine_id) REFERENCES cnc_machine(id),
    UNIQUE KEY uk_machine_date_program (machine_id, production_date, program_name),
    INDEX idx_date (production_date),
    INDEX idx_date_program (production_date, program_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='日汇总表(按机床+程序)';

-- 2.12 工人日汇总表
CREATE TABLE IF NOT EXISTS cnc_worker_daily_summary (
    id                INT AUTO_INCREMENT PRIMARY KEY,
    worker_id         INT NOT NULL,
    production_date   DATE NOT NULL,
    total_quantity    DECIMAL(15,5) NOT NULL DEFAULT 0,
    machine_count     INT NOT NULL DEFAULT 0,
    program_count     INT NOT NULL DEFAULT 0,
    is_adjusted       TINYINT(1) NOT NULL DEFAULT 0,
    adjusted_quantity DECIMAL(15,5) NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (worker_id) REFERENCES cnc_worker(id) ON DELETE CASCADE,
    UNIQUE KEY uk_worker_date (worker_id, production_date),
    INDEX idx_date (production_date),
    INDEX idx_date_quantity (production_date, total_quantity)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工人日汇总表';

-- 2.13 产量修正审计表
CREATE TABLE IF NOT EXISTS cnc_production_adjustment (
    id                BIGINT AUTO_INCREMENT PRIMARY KEY,
    target_table      VARCHAR(30) NOT NULL,
    target_id         INT NOT NULL,
    field_name        VARCHAR(50) NOT NULL,
    old_value         DECIMAL(15,5) NULL,
    new_value         DECIMAL(15,5) NOT NULL,
    reason            VARCHAR(500) NOT NULL,
    operator_ip       VARCHAR(50) NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_target (target_table, target_id),
    INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='产量修正审计表';

-- 2.14 告警表
CREATE TABLE IF NOT EXISTS cnc_alert (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    alert_type      VARCHAR(30) NOT NULL,
    machine_id      INT NULL,
    collect_address_id INT NULL,
    title           VARCHAR(200) NOT NULL,
    detail          TEXT NULL,
    is_resolved     TINYINT(1) NOT NULL DEFAULT 0,
    resolved_at     DATETIME NULL,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (machine_id) REFERENCES cnc_machine(id) ON DELETE SET NULL,
    FOREIGN KEY (collect_address_id) REFERENCES cnc_collect_address(id) ON DELETE SET NULL,
    INDEX idx_type_resolved (alert_type, is_resolved),
    INDEX idx_machine_time (machine_id, created_at),
    INDEX idx_created (created_at),
    INDEX idx_unresolved (is_resolved, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='告警表';

-- 2.15 系统配置表
CREATE TABLE IF NOT EXISTS cnc_sys_config (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    config_key  VARCHAR(100) NOT NULL UNIQUE,
    config_value TEXT NOT NULL,
    value_type  VARCHAR(20) NOT NULL DEFAULT 'string',
    description VARCHAR(200) NULL,
    updated_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';

-- 2.16 大屏配置表
CREATE TABLE IF NOT EXISTS cnc_screen_config (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    card_key        VARCHAR(50) NOT NULL UNIQUE,
    card_type       VARCHAR(30) NOT NULL,
    title           VARCHAR(100) NOT NULL,
    metric          VARCHAR(50) NOT NULL,
    dimension       VARCHAR(30) NULL,
    sort_order      INT NOT NULL DEFAULT 0,
    is_enabled      TINYINT(1) NOT NULL DEFAULT 1,
    chart_config    JSON NULL,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大屏卡片配置表';

-- 2.17 大屏筛选配置表
CREATE TABLE IF NOT EXISTS cnc_screen_filter (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    screen_key      VARCHAR(50) NOT NULL,
    filter_type     VARCHAR(30) NOT NULL,
    filter_value    VARCHAR(100) NOT NULL,
    is_default      TINYINT(1) NOT NULL DEFAULT 0,
    sort_order      INT NOT NULL DEFAULT 0,
    UNIQUE KEY uk_screen_filter (screen_key, filter_type, filter_value)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大屏筛选配置表';

-- =============================================
-- 日志库 cnc_log（3张表）
-- =============================================
USE cnc_log;

-- 3.1 原始采集JSON表（按月分区）
-- 注意：分区键request_time必须包含在PRIMARY KEY中
CREATE TABLE IF NOT EXISTS log_collect_raw (
    id                BIGINT AUTO_INCREMENT,
    collect_address_id INT NOT NULL,
    request_time      DATETIME NOT NULL,
    response_time     DATETIME NOT NULL,
    response_duration INT NULL,
    is_success        TINYINT(1) NOT NULL DEFAULT 1,
    status_code       INT NULL,
    raw_json          MEDIUMTEXT NOT NULL,
    error_message     VARCHAR(500) NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id, request_time),
    INDEX idx_address_time (collect_address_id, request_time),
    INDEX idx_request_time (request_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='原始采集JSON表（按月分区，90天自动清理）'
  PARTITION BY RANGE (TO_DAYS(request_time)) (
    PARTITION p202604 VALUES LESS THAN (TO_DAYS('2026-05-01')),
    PARTITION p202605 VALUES LESS THAN (TO_DAYS('2026-06-01')),
    PARTITION p202606 VALUES LESS THAN (TO_DAYS('2026-07-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- 3.2 系统日志表（按月分区）
-- 注意：分区键created_at必须包含在PRIMARY KEY中
CREATE TABLE IF NOT EXISTS log_system (
    id              BIGINT AUTO_INCREMENT,
    log_level       VARCHAR(10) NOT NULL,
    source          VARCHAR(50) NOT NULL,
    message         TEXT NOT NULL,
    stack_trace     TEXT NULL,
    extra_data      JSON NULL,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id, created_at),
    INDEX idx_level_time (log_level, created_at),
    INDEX idx_source_time (source, created_at),
    INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='系统日志表（按月分区，30天自动清理）'
  PARTITION BY RANGE (TO_DAYS(created_at)) (
    PARTITION p202604 VALUES LESS THAN (TO_DAYS('2026-05-01')),
    PARTITION p202605 VALUES LESS THAN (TO_DAYS('2026-06-01')),
    PARTITION p202606 VALUES LESS THAN (TO_DAYS('2026-07-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- 3.3 采集服务心跳表
CREATE TABLE IF NOT EXISTS log_collector_heartbeat (
    id                BIGINT AUTO_INCREMENT PRIMARY KEY,
    service_id        VARCHAR(50) NOT NULL DEFAULT 'CncCollector',
    status            VARCHAR(20) NOT NULL,
    collect_address_id INT NULL,
    last_collect_time DATETIME NULL,
    success_count     INT NOT NULL DEFAULT 0,
    fail_count        INT NOT NULL DEFAULT 0,
    uptime_seconds    BIGINT NULL,
    detail            JSON NULL,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_service_time (service_id, created_at),
    INDEX idx_address_time (collect_address_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采集服务心跳表（7天自动清理）';
