import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { ShopStoreUser, ShopStoreUserParam } from './model';

/**
 * 分页查询店员
 */
export async function pageShopStoreUser(params: ShopStoreUserParam) {
  const res = await request.get<ApiResult<PageResult<ShopStoreUser>>>(
    '/shop/shop-store-user/page',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询店员列表
 */
export async function listShopStoreUser(params?: ShopStoreUserParam) {
  const res = await request.get<ApiResult<ShopStoreUser[]>>(
    '/shop/shop-store-user',
    params
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加店员
 */
export async function addShopStoreUser(data: ShopStoreUser) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-store-user',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改店员
 */
export async function updateShopStoreUser(data: ShopStoreUser) {
  const res = await request.put<ApiResult<unknown>>(
    '/shop/shop-store-user',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除店员
 */
export async function removeShopStoreUser(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/shop/shop-store-user/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除店员
 */
export async function removeBatchShopStoreUser(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    '/shop/shop-store-user/batch',
    {
      data
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询店员
 */
export async function getShopStoreUser(id: number) {
  const res = await request.get<ApiResult<ShopStoreUser>>(
    '/shop/shop-store-user/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询当前登录用户的店员信息
 * 用于小程序端判断当前用户是否为门店经理/店员
 * 返回店员记录（含 storeName 等关联字段），非店员返回 null
 */
export async function getMyClerk() {
  const res = await request.get<ApiResult<any>>(
    '/shop/shop-store-user/my'
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return null;
}
