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

import type { ApiResult, PageResult } from '@/api';
import type { CreditExternal, CreditExternalParam } from './model';

/**
 * 分页查询对外投资
 */
export async function pageCreditExternal(params: CreditExternalParam) {
  const res = await request.get<ApiResult<PageResult<CreditExternal>>>(
    '/credit/credit-external/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询对外投资列表
 */
export async function listCreditExternal(params?: CreditExternalParam) {
  const res = await request.get<ApiResult<CreditExternal[]>>(
    '/credit/credit-external', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加对外投资
 */
export async function addCreditExternal(data: CreditExternal) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-external',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改对外投资
 */
export async function updateCreditExternal(data: CreditExternal) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-external',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除对外投资
 */
export async function removeCreditExternal(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-external/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

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

/**
 * 根据id查询对外投资
 */
export async function getCreditExternal(id: number) {
  const res = await request.get<ApiResult<CreditExternal>>(
    '/credit/credit-external/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入对外投资
 */
export async function importCreditExternal(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-external/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
