import request from '@/utils/request';
import { withCreditUserScope } from '@/api/credit/utils/data-scope';

import type { ApiResult, PageResult } from '@/api';
import type { CreditUser, CreditUserParam } from './model';

/**
 * 分页查询招投标信息表
 */
export async function pageCreditUser(params: CreditUserParam) {
  const res = await request.get<ApiResult<PageResult<CreditUser>>>(
    '/credit/credit-user/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询招投标信息表列表
 */
export async function listCreditUser(params?: CreditUserParam) {
  const res = await request.get<ApiResult<CreditUser[]>>(
    '/credit/credit-user', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加招投标信息表
 */
export async function addCreditUser(data: CreditUser) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-user',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改招投标信息表
 */
export async function updateCreditUser(data: CreditUser) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-user',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除招投标信息表
 */
export async function removeCreditUser(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-user/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除招投标信息表
 */
export async function removeBatchCreditUser(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-user/batch',
    data);
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询招投标信息表
 */
export async function getCreditUser(id: number) {
  const res = await request.get<ApiResult<CreditUser>>(
    '/credit/credit-user/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入招投标
 */
export async function importCreditUsers(file: File, companyId?: number) {
  const formData = new FormData();
  formData.append('file', file);
  if (companyId != null) {
    formData.append('companyId', String(companyId));
  }
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-user/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
