/**
 * 补货员相关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[];
}

/**
 * 执行补货操作
 */
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;
}
