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

import { USE_MOCK } from '@/utils/config';
import { mockCheckinRecords, mockCheckinStats, mockTodayCheckin } from '@/mock/checkin';

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> {
  if (USE_MOCK) {
    const record: CheckinRecord = {
      id: 'checkin_' + Date.now(),
      type: params.type,
      typeName: params.type === CheckinType.INVENTORY_TALLY ? '理货盘点签到' : '补货确认签到',
      userId: 1,
      userName: '测试用户',
      userNo: 'EMP001',
      shopId: params.shopId,
      shopName: '测试门店',
      deviceId: params.deviceId,
      deviceName: params.deviceId ? '测试设备' : undefined,
      location: params.location,
      photos: params.photos,
      remark: params.remark || '',
      status: 'synced',
      createdAt: new Date().toISOString(),
      syncedAt: new Date().toISOString()
    };
    return Promise.resolve(record);
  }
  
  const { post } = await import('@/utils/request');
  return post('/checkin', params);
}

export async function getCheckinList(params: CheckinQueryParams = {}): Promise<CheckinListResponse> {
  if (USE_MOCK) {
    const { page = 1, pageSize = 10, type, startDate, endDate } = params;
    let list = [...mockCheckinRecords];
    
    if (type) {
      list = list.filter(item => item.type === type);
    }
    
    if (startDate) {
      list = list.filter(item => item.createdAt >= startDate);
    }
    
    if (endDate) {
      list = list.filter(item => item.createdAt <= endDate + ' 23:59:59');
    }
    
    const total = list.length;
    const startIndex = (page - 1) * pageSize;
    
    return Promise.resolve({
      list: list.slice(startIndex, startIndex + pageSize),
      total,
      page,
      pageSize
    });
  }
  
  const { get } = await import('@/utils/request');
  return get('/checkin', params);
}

export async function getCheckinDetail(id: string): Promise<CheckinRecord> {
  if (USE_MOCK) {
    const record = mockCheckinRecords.find(item => item.id === id);
    if (record) {
      return Promise.resolve(record);
    }
    return Promise.reject(new Error('签到记录不存在'));
  }
  
  const { get } = await import('@/utils/request');
  return get(`/checkin/${id}`);
}

export async function getCheckinStats(): Promise<CheckinStats> {
  if (USE_MOCK) {
    return Promise.resolve(mockCheckinStats);
  }
  
  const { get } = await import('@/utils/request');
  return get('/checkin/stats');
}

export async function getTodayCheckin(): Promise<TodayCheckin> {
  if (USE_MOCK) {
    return Promise.resolve(mockTodayCheckin);
  }
  
  const { get } = await import('@/utils/request');
  return get('/checkin/today');
}

export async function syncOfflineCheckins(records: CheckinRecord[]): Promise<{ success: number; failed: number }> {
  if (USE_MOCK) {
    return Promise.resolve({ success: records.length, failed: 0 });
  }
  
  const { post } = await import('@/utils/request');
  return post('/checkin/sync', { records });
}

export async function exportCheckinRecords(params: CheckinQueryParams): Promise<string> {
  if (USE_MOCK) {
    return Promise.resolve('https://example.com/export/checkin_records.xlsx');
  }
  
  const { get } = await import('@/utils/request');
  return get('/checkin/export', params);
}
