ALTER TABLE audit_task
    ADD COLUMN sla_deadline_at DATETIME DEFAULT NULL AFTER opinion,
    ADD COLUMN timeout_level TINYINT NOT NULL DEFAULT 0 AFTER sla_deadline_at;

CREATE TABLE IF NOT EXISTS audit_transfer_log (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    task_id BIGINT UNSIGNED NOT NULL,
    from_user_id BIGINT UNSIGNED DEFAULT NULL,
    to_user_id BIGINT UNSIGNED NOT NULL,
    reason VARCHAR(500) DEFAULT NULL,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_tenant_task_time (tenant_id, task_id, created_at),
    KEY idx_tenant_to_user_time (tenant_id, to_user_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

UPDATE audit_task
SET sla_deadline_at = DATE_ADD(created_at, INTERVAL 24 HOUR)
WHERE sla_deadline_at IS NULL;

UPDATE audit_task
SET timeout_level = CASE
    WHEN status='PENDING' AND sla_deadline_at IS NOT NULL AND TIMESTAMPDIFF(HOUR, sla_deadline_at, NOW()) >= 24 THEN 3
    WHEN status='PENDING' AND sla_deadline_at IS NOT NULL AND TIMESTAMPDIFF(HOUR, sla_deadline_at, NOW()) >= 12 THEN 2
    WHEN status='PENDING' AND sla_deadline_at IS NOT NULL AND TIMESTAMPDIFF(HOUR, sla_deadline_at, NOW()) >= 4 THEN 1
    ELSE 0 END;

INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1043, 'audit.transfer', '审核转审', 'audit'),
    (1044, 'audit.remind', '审核催办', 'audit'),
    (1045, 'audit.sla.read', '查看审核SLA统计', 'audit')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
VALUES
    (44, 1, 101, 1043),
    (45, 1, 101, 1044),
    (46, 1, 101, 1045)
ON DUPLICATE KEY UPDATE permission_id = VALUES(permission_id);
