/**
* 批量创建任务工具
*/
import { ToolResult } from '../types';
import { ZenTaoClient } from '../client';
import { IBatchCreateTaskParams, IBatchOptions, IBatchResult } from '../types';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { LRUCache } from '../utils/cache';
export async function batchCreateTasks(
client: ZenTaoClient,
cache: LRUCache<string, any>,
items: IBatchCreateTaskParams[],
options?: IBatchOptions
): Promise<ToolResult> {
// Suppress unused parameter warning for cache (reserved for future use)
void cache;
const startTime = Date.now();
const maxConcurrency = options?.maxConcurrency || 10;
try {
// 验证输入
if (!items || items.length === 0) {
return {
content: [
{
type: 'text',
text: '错误:任务列表不能为空',
},
],
isError: true,
};
}
const total = items.length;
const results: IBatchResult<IBatchCreateTaskParams> = {
success: 0,
failed: 0,
total,
results: [],
duration: 0,
};
// 分批处理,每批最多 maxConcurrency 个
for (let i = 0; i < total; i += maxConcurrency) {
const batch = items.slice(i, i + maxConcurrency);
const batchPromises = batch.map((item) =>
processTask(client, item)
);
const batchResults = await Promise.allSettled(batchPromises);
batchResults.forEach((result, index) => {
const originalIndex = i + index;
const item = batch[index];
if (result.status === 'fulfilled') {
results.success++;
results.results.push({
item,
status: 'success',
id: result.value,
index: originalIndex,
});
} else {
results.failed++;
results.results.push({
item,
status: 'failed',
error: result.reason?.message || '未知错误',
index: originalIndex,
});
}
});
// 如果设置了继续出错的选项,可以继续处理
if (!options?.continueOnError && results.failed > 0) {
break;
}
// 批次间延迟
if (options?.delayBetweenBatches && i + maxConcurrency < total) {
await new Promise((resolve) => setTimeout(resolve, options?.delayBetweenBatches));
}
}
results.duration = Date.now() - startTime;
// 格式化输出
const output = `批量创建任务完成!\n\n统计信息:\n 总任务数: ${total}\n 成功: ${results.success}\n 失败: ${results.failed}\n 耗时: ${results.duration}ms\n\n${
options?.reportMode === 'detailed'
? `\n详细结果:\n${results.results
.map((r) =>
r.status === 'success'
? `✓ [${r.index}] ${r.item.name} - ID: ${r.id}`
: `✗ [${r.index}] ${r.item.name} - 错误: ${r.error}`
)
.join('\n')}`
: ''
}`;
return {
content: [
{
type: 'text',
text: output,
},
],
};
} catch (error: any) {
return {
content: [
{
type: 'text',
text: `批量创建任务失败: ${error.message || '未知错误'}`,
},
],
isError: true,
};
}
}
async function processTask(
client: ZenTaoClient,
item: IBatchCreateTaskParams
): Promise<number> {
const task = await client.post('/api.php/v1/tasks', item);
return task.id;
}