ALTER TABLE `tb_document_import_batch`
    ADD COLUMN `uploaded_count` int NOT NULL DEFAULT 0 COMMENT '已上传数' AFTER `pending_count`,
    ADD COLUMN `skipped_count` int NOT NULL DEFAULT 0 COMMENT '跳过数' AFTER `uploaded_count`,
    ADD COLUMN `cancelled_count` int NOT NULL DEFAULT 0 COMMENT '取消数' AFTER `skipped_count`,
    ADD COLUMN `retryable_failed_count` int NOT NULL DEFAULT 0 COMMENT '可重试失败数' AFTER `cancelled_count`;

ALTER TABLE `tb_document_import_batch_item`
    ADD COLUMN `retryable` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否允许批量重试' AFTER `error_summary`,
    ADD COLUMN `attempt_count` int NOT NULL DEFAULT 0 COMMENT '重试次数' AFTER `retryable`,
    DROP INDEX `idx_document_import_batch_item_batch_status`,
    ADD INDEX `idx_document_import_batch_item_batch_status` (`batch_id`, `status`, `modified`) USING BTREE;

ALTER TABLE `tb_document_import_task`
    ADD INDEX `idx_document_import_task_phase_status_modified`
        (`phase`, `status`, `modified`, `batch_id`, `created`) USING BTREE;

UPDATE `tb_document_import_batch` batch
SET batch.`uploaded_count` = (
        SELECT COUNT(*)
        FROM `tb_document_import_batch_item` item
        WHERE item.`batch_id` = batch.`id`
          AND item.`status` = 'UPLOADED'
    ),
    batch.`skipped_count` = (
        SELECT COUNT(*)
        FROM `tb_document_import_batch_item` item
        WHERE item.`batch_id` = batch.`id`
          AND item.`status` = 'SKIPPED'
    ),
    batch.`cancelled_count` = (
        SELECT COUNT(*)
        FROM `tb_document_import_batch_item` item
        WHERE item.`batch_id` = batch.`id`
          AND item.`status` = 'CANCELLED'
    ),
    batch.`retryable_failed_count` = (
        SELECT COUNT(*)
        FROM `tb_document_import_batch_item` item
        WHERE item.`batch_id` = batch.`id`
          AND item.`status` = 'FAILED'
          AND item.`retryable` = 1
    );
