lefengyang
2026-08-20 d01a28cb030b2cb0ff1d42273c877a0f728519a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import {ApiUrlBase, IBidTask, IResp, ITask, TaskTypeKey, UseHistoryMockKey} from "/src-com";
import {StorageLocal} from "gs-br-ext";
import {Db} from "/src-com/db";
import {isNumber} from "gs-base";
 
const TaskKey = 'remoteTask';
 
export class RemoteTask {
    static async get(reserve: boolean = false): Promise<ITask | undefined> {
        // 检查是否开启模拟数据
        const useMock = await StorageLocal.getValue(UseHistoryMockKey);
        if (useMock !== false) {
            const data = await this.getMockTask(useMock);
            if (data) {
                return data;
            }
        }
 
        // 原有逻辑
        const taskType = await StorageLocal.getValue(TaskTypeKey)
        const url = new URL(`${ApiUrlBase}/task/get`);
        if (reserve) {
            url.searchParams.append('reserve', '1');
        }
        if (taskType) {
            url.searchParams.append('type', taskType);
        }
        const httpResp = await fetch(url);
        if (!httpResp.ok) {
            throw new Error(httpResp.statusText);
        }
        const resp: IResp<ITask> = await httpResp.json();
        if (resp.code != 200) {
            throw new Error(resp.message);
        }
        const {data} = resp || {} as IResp<ITask>;
        await StorageLocal.setValue(TaskKey, data);
        return data;
    }
 
    // noinspection JSUnusedLocalSymbols
    static async end(task: ITask): Promise<void> {
    }
 
    // 获取模拟任务数据
    private static async getMockTask(useMock: boolean | number): Promise<IBidTask | undefined> {
        try {
            // 从历史记录中随机获取一条数据
            const mockData = await Db.bidTaskAddedHistory.batchRead(async (store) => {
                if(isNumber(useMock)) {
                    return await store.get(useMock as number);
                }
                const count = await store.count();
                if (count === 0) return null;
                const randomIndex = Math.ceil(Math.random() * count);
                return await store.get(randomIndex);
            });
 
            if (!mockData) {
                return undefined;
            }
 
            // 转换为IBidTask类型
            const bidTask: IBidTask = {
                id: `mock-${Date.now()}`,
                type: mockData.taskType === 0 ? 'bid' : 'buyItNow',
                params: {
                    goodsId: mockData.goodsId,
                    bid: mockData.bid
                }
            };
 
            console.log('生成的模拟任务:', bidTask);
            await StorageLocal.setValue(TaskKey, bidTask);
            return bidTask;
        } catch (error) {
            console.error('获取模拟任务失败:', error);
            return undefined;
        }
    }
}