/**
 * 签到功能相关API
 */

import { get, post } from '@/utils/request';

export enum CheckinType {
  INVENTORY_TALLY = 'inventory_tally',
  DELIVERY_REPLENISH = 'delivery_replenish'
}

export enum CheckinTypeLabel {
  INVENTORY_TALLY = '理货盘点签到',
  DELIVERY_REPLENISH = '补货确认签到'
}

export interface LocationInfo {
  latitude: number;
  longitude: number;
  address: string;
  accuracy: number;
}

export interface CheckinPhoto {
  id: string;
  path: string;
  watermarkPath?: string;
  timestamp: number;
  location: LocationInfo;
}

export interface CheckinRecord {
  id: string;
  type: CheckinType;
  typeName: string;
  userId: number;
  userName: string;
  userNo: string;
  shopId?: number;
  shopName?: string;
  deviceId?: number;
  deviceName?: string;
  location: LocationInfo;
  photos: CheckinPhoto[];
  remark: string;
  status: 'pending' | 'synced' | 'failed';
  createdAt: string;
  syncedAt?: string;
  offlineId?: string;
}

export interface CheckinParams {
  type: CheckinType;
  shopId?: number;
  deviceId?: number;
  location: LocationInfo;
  photos: CheckinPhoto[];
  remark?: string;
  offlineId?: string;
}

export interface CheckinQueryParams {
  page?: number;
  pageSize?: number;
  type?: CheckinType;
  userId?: number;
  shopId?: number;
  startDate?: string;
  endDate?: string;
  status?: string;
}

export interface CheckinListResponse {
  list: CheckinRecord[];
  total: number;
  page: number;
  pageSize: number;
}

export interface CheckinStats {
  todayCount: number;
  weekCount: number;
  monthCount: number;
  inventoryTallyCount: number;
  deliveryReplenishCount: number;
  pendingSyncCount: number;
}

export interface TodayCheckin {
  hasInventoryTally: boolean;
  hasDeliveryReplenish: boolean;
  inventoryTallyTime?: string;
  deliveryReplenishTime?: string;
}

export async function submitCheckin(params: CheckinParams): Promise<CheckinRecord> {
  return post('/checkin', params);
}

export async function getCheckinList(params: CheckinQueryParams = {}): Promise<CheckinListResponse> {
  return get('/checkin', params);
}

export async function getCheckinDetail(id: string): Promise<CheckinRecord> {
  return get(`/checkin/${id}`);
}

export async function getCheckinStats(): Promise<CheckinStats> {
  return get('/checkin/stats');
}

export async function getTodayCheckin(): Promise<TodayCheckin> {
  return get('/checkin/today');
}

export async function syncOfflineCheckins(records: CheckinRecord[]): Promise<{ success: number; failed: number }> {
  return post('/checkin/sync', { records });
}

export async function exportCheckinRecords(params: CheckinQueryParams): Promise<string> {
  return get('/checkin/export', params);
}
