-- 创建设备导入任务表
-- 用于记录设备批量导入的任务状态和处理结果

CREATE TABLE IF NOT EXISTS tb_device_import_task (
    -- 基础字段
    id BIGSERIAL PRIMARY KEY,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP,
    creator BIGINT,
    updater BIGINT,

    -- 任务标识
    task_no VARCHAR(50) NOT NULL UNIQUE,
    batch_no VARCHAR(100),

    -- 文件信息
    storage_key VARCHAR(500),
    file_name VARCHAR(255),

    -- 任务状态: 1-待处理 2-处理中 3-已完成 4-失败
    status INT NOT NULL DEFAULT 1,

    -- 处理结果统计
    total_count INT DEFAULT 0,
    success_count INT DEFAULT 0,
    skip_count INT DEFAULT 0,
    fail_count INT DEFAULT 0,

    -- 处理详情（JSONB 存储跳过和失败的记录）
    skipped_items JSONB,
    failed_items JSONB,

    -- 错误信息
    error_message TEXT,

    -- 时间戳
    started_at TIMESTAMP,
    completed_at TIMESTAMP
);

-- 索引
CREATE INDEX idx_device_import_task_status ON tb_device_import_task(status);
CREATE INDEX idx_device_import_task_batch_no ON tb_device_import_task(batch_no);
CREATE INDEX idx_device_import_task_created_at ON tb_device_import_task(created_at);
CREATE INDEX idx_device_import_task_deleted_at ON tb_device_import_task(deleted_at);

-- 字段注释
COMMENT ON TABLE tb_device_import_task IS '设备导入任务表';
COMMENT ON COLUMN tb_device_import_task.id IS '主键ID';
COMMENT ON COLUMN tb_device_import_task.created_at IS '创建时间';
COMMENT ON COLUMN tb_device_import_task.updated_at IS '更新时间';
COMMENT ON COLUMN tb_device_import_task.deleted_at IS '删除时间（软删除）';
COMMENT ON COLUMN tb_device_import_task.creator IS '创建人ID';
COMMENT ON COLUMN tb_device_import_task.updater IS '更新人ID';
COMMENT ON COLUMN tb_device_import_task.task_no IS '任务编号（唯一）';
COMMENT ON COLUMN tb_device_import_task.batch_no IS '批次号';
COMMENT ON COLUMN tb_device_import_task.storage_key IS '对象存储文件路径';
COMMENT ON COLUMN tb_device_import_task.file_name IS '原始文件名';
COMMENT ON COLUMN tb_device_import_task.status IS '任务状态: 1-待处理 2-处理中 3-已完成 4-失败';
COMMENT ON COLUMN tb_device_import_task.total_count IS '总记录数';
COMMENT ON COLUMN tb_device_import_task.success_count IS '成功数';
COMMENT ON COLUMN tb_device_import_task.skip_count IS '跳过数';
COMMENT ON COLUMN tb_device_import_task.fail_count IS '失败数';
COMMENT ON COLUMN tb_device_import_task.skipped_items IS '跳过记录详情（JSON数组）';
COMMENT ON COLUMN tb_device_import_task.failed_items IS '失败记录详情（JSON数组）';
COMMENT ON COLUMN tb_device_import_task.error_message IS '错误信息';
COMMENT ON COLUMN tb_device_import_task.started_at IS '开始处理时间';
COMMENT ON COLUMN tb_device_import_task.completed_at IS '完成时间';
