import { requestClient } from '#/api/request';
import { getBagCodeByCode, resolveTraceType } from '#/api/mes/pro/bagCode';
import { getPalletByCode } from '#/api/mes/pro/pallet';
import { getBatchByCode } from '#/api/mes/pro/batch';
import { can, extractCode } from './access';
import type { MesProScanEventApi } from '#/api/mes/pro/scanEvent';
export interface TraceObject {
  id?: number; code?: string; businessCode?: string; tempCode?: string; itemName?: string; itemId?: number;
  batchId?: number; batchCode?: string; lineName?: string; produceDate?: string;
  palletId?: number; palletCode?: string; bagCount?: number; bagQuantity?: number; status?: number;
  batchStatus?: number;
  inboundTime?: string; inboundBagQuantity?: number; pendingBagQuantity?: number;
}
export async function lookup(raw: string) {
  const code = extractCode(raw);
  const type = await resolveTraceType(code);
  if (!type) throw new Error('未找到对应袋码、托盘或批次');
  const permission = { bag: 'mes:pro-bag-code:query', pallet: 'mes:pro-pallet:query', batch: 'mes:pro-batch:query' }[type];
  if (!can(permission)) throw new Error('当前账号没有该码类型的查询权限');
  const data: TraceObject = await ({ bag: getBagCodeByCode, pallet: getPalletByCode, batch: getBatchByCode }[type])(code);
  if (!data?.id) throw new Error('未找到对象信息');
  return { code, type, data };
}
export type TraceResult = Awaited<ReturnType<typeof lookup>>;
export function writeBlockReason(trace: TraceResult) {
  const canceled={bag:30,pallet:20,batch:40}[trace.type];
  if(trace.data.status===canceled)return '该'+{bag:'袋码',pallet:'托盘',batch:'批次'}[trace.type]+'已作废，不可执行写操作';
  if(trace.data.batchStatus===40)return '该对象所属批次已作废，不可执行写操作';
  return '';
}
export function myRecords(params: { pageNo: number; pageSize: number; status?: string; eventId?: string; receivedTime?: string[] }) {
  return requestClient.get<{ list: MesProScanEventApi.ScanEvent[]; total: number }>('/mes/pro/scan-in/my-page', { params });
}
export function myEvent(eventId: string) {
  return requestClient.get<MesProScanEventApi.ScanEvent | null>('/mes/pro/scan-in/my-event', { params: { eventId } });
}
export function errorText(error: unknown) {
  const e = error as { message?: string; data?: { msg?: string }; response?: { data?: { msg?: string } } };
  return e?.response?.data?.msg || e?.data?.msg || e?.message || '请求失败，请稍后重试';
}
