import { axios, type Page, type PageResult } from "timi-web"; import type { EventItem } from "@/types/EventItem"; import { getCurrentStoreId, withCurrentStoreId, withCurrentStorePage } from "@/utils/store"; const BASE_URI = "/gao/event"; const eventOrderMap: NonNullable["orderMap"]> = { sort: "ASC", createdAt: "ASC" }; type ListOptions = { allStores?: boolean; storeId?: string; }; /** * 为所有事件分页查询补充统一排序,避免后端未传排序参数时按数据库默认顺序返回。 */ function withEventOrder(page: Page): Page { return { ...page, orderMap: { ...eventOrderMap, ...(page.orderMap || {}) } }; } /** * 按事件排序值升序排列,缺少排序值的历史数据放到列表末尾。 */ function sortEventList(list: EventItem[]): EventItem[] { return [...list].sort((left, right) => { const leftSort = left.sort ?? Number.MAX_SAFE_INTEGER; const rightSort = right.sort ?? Number.MAX_SAFE_INTEGER; if (leftSort !== rightSort) { return leftSort - rightSort; } return (left.createdAt ?? Number.MAX_SAFE_INTEGER) - (right.createdAt ?? Number.MAX_SAFE_INTEGER); }); } async function list(req: Page, options?: ListOptions): Promise> { const orderedPage = withEventOrder(req); if (options?.allStores) { return await axios.post(`${BASE_URI}/list`, orderedPage); } if (options?.storeId) { return await axios.post(`${BASE_URI}/list`, { ...orderedPage, equalsExample: { ...(orderedPage.equalsExample || {}), storeId: options.storeId } }); } return await axios.post(`${BASE_URI}/list`, withCurrentStorePage(orderedPage)); } async function listValid(): Promise { const list = await axios.post(`${BASE_URI}/list/valid`, undefined, { params: { storeId: getCurrentStoreId() } }) as unknown as EventItem[]; return sortEventList(list); } async function detail(id: string): Promise { return await axios.post(`${BASE_URI}/detail`, undefined, { params: { id } }); } async function create(event: EventItem): Promise { return await axios.post(`${BASE_URI}/create`, withCurrentStoreId(event)); } async function update(event: EventItem): Promise { return await axios.post(`${BASE_URI}/update`, withCurrentStoreId(event)); } async function sort(idList: string[]): Promise { return await axios.post(`${BASE_URI}/sort`, idList); } async function remove(id: string): Promise { return await axios.post(`${BASE_URI}/delete`, undefined, { params: { id } }); } export default { list, listValid, detail, create, update, sort, remove };