/**
 * 补货员相关API
 */
import { post, get, put } from '@/utils/request';
import { setToken, setReplenisherInfo, setUserType } from '@/utils/auth';

export interface WechatLoginParams {
  code: string;
}

export interface LoginResponse {
  token: string;
  userInfo: any;
}

/**
 * 补货员微信静默登录
 */
export async function loginByWechat(params: WechatLoginParams): Promise<LoginResponse> {
  const response = await post<LoginResponse>('/replenisher/login/wechat', params);
  // 保存登录信息
  setToken(response.token);
  setReplenisherInfo(response.userInfo);
  setUserType('replenisher');
  return response;
}

/**
 * 获取当前补货员信息
 */
export async function getMyInfo(): Promise<any> {
  return get('/replenisher/my-info');
}

/**
 * 获取补货员绑定的设备列表（含库存信息）
 */
export async function getDeviceList(): Promise<any[]> {
  return get('/replenisher/device/list');
}

/**
 * 获取设备库存详情
 * @param deviceId 设备SN号
 */
export async function getDeviceInventory(deviceId: string): Promise<any> {
  return get(`/replenisher/device/inventory/${deviceId}`);
}

export interface ReplenishItem {
  productId: number;
  productCode?: string;
  productName?: string;
  quantity: number;
  shelfNum?: number;
  position?: string;
}

export interface ReplenishParams {
  deviceId: string;
  items: ReplenishItem[];
  orderId?: string;
}

/**
 * 执行补货操作（支持关联补货单 orderId）
 */
export async function replenishStock(params: ReplenishParams): Promise<any> {
  return post('/replenisher/stock/replenish', params);
}

/**
 * 补货员扫码绑定微信
 * @param params 绑定参数（bindingCode + wechatCode）
 */
export async function bindWechat(params: { bindingCode: string; code: string }): Promise<LoginResponse> {
  const response = await post<LoginResponse>('/replenisher/login/bind', params);
  // 保存登录信息
  setToken(response.token);
  setReplenisherInfo(response.userInfo);
  setUserType('replenisher');
  return response;
}

// ==================== 补货单相关 ====================

/**
 * 获取设备待处理补货单列表（用于补货单切换）
 */
export async function getDevicePendingOrders(deviceId: string): Promise<any[]> {
  return get(`/replenisher/device/${deviceId}/pending-orders`);
}

/**
 * 补货员远程开门
 */
export async function openDeviceDoor(deviceId: string): Promise<void> {
  return post(`/replenisher/device/${deviceId}/open`);
}

/**
 * 查询设备门状态（轻量轮询）
 */
export async function getDeviceDoorStatus(deviceId: string): Promise<{ status: number; statusLabel: string }> {
  return get(`/replenisher/device/${deviceId}/status`);
}

/**
 * 获取补货员的补货单列表
 */
export async function getReplenisherOrders(params: { page?: number; pageSize?: number; status?: number }): Promise<any> {
  return get('/replenisher/orders', params);
}

/**
 * 获取补货单详情（含明细）
 */
export async function getReplenisherOrderDetail(id: string): Promise<any> {
  return get(`/replenisher/orders/${id}`);
}

/**
 * 批量生成补货单
 */
export async function batchGenerateOrders(params: { deviceIds: string[] }): Promise<any> {
  return post('/replenisher/orders/batch-generate', params);
}
