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

import type { ApiResult, PageResult } from '@/api';
import type { CreditSupplier, CreditSupplierParam } from './model';

/**
 * 分页查询供应商
 */
export async function pageCreditSupplier(params: CreditSupplierParam) {
  const res = await request.get<ApiResult<PageResult<CreditSupplier>>>(
    '/credit/credit-supplier/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询供应商列表
 */
export async function listCreditSupplier(params?: CreditSupplierParam) {
  const res = await request.get<ApiResult<CreditSupplier[]>>(
    '/credit/credit-supplier', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加供应商
 */
export async function addCreditSupplier(data: CreditSupplier) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-supplier',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改供应商
 */
export async function updateCreditSupplier(data: CreditSupplier) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-supplier',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除供应商
 */
export async function removeCreditSupplier(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-supplier/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除供应商
 */
export async function removeBatchCreditSupplier(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-supplier/batch',
    data);
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询供应商
 */
export async function getCreditSupplier(id: number) {
  const res = await request.get<ApiResult<CreditSupplier>>(
    '/credit/credit-supplier/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入供应商
 */
export async function importCreditSupplier(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-supplier/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
