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

import type { ApiResult, PageResult } from '@/api';
import type { CreditJudiciary, CreditJudiciaryParam } from './model';

/**
 * 分页查询司法案件
 */
export async function pageCreditJudiciary(params: CreditJudiciaryParam) {
  const res = await request.get<ApiResult<PageResult<CreditJudiciary>>>(
    '/credit/credit-judiciary/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询司法案件列表
 */
export async function listCreditJudiciary(params?: CreditJudiciaryParam) {
  const res = await request.get<ApiResult<CreditJudiciary[]>>(
    '/credit/credit-judiciary', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加司法案件
 */
export async function addCreditJudiciary(data: CreditJudiciary) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-judiciary',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改司法案件
 */
export async function updateCreditJudiciary(data: CreditJudiciary) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-judiciary',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除司法案件
 */
export async function removeCreditJudiciary(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-judiciary/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

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

/**
 * 根据id查询司法案件
 */
export async function getCreditJudiciary(id: number) {
  const res = await request.get<ApiResult<CreditJudiciary>>(
    '/credit/credit-judiciary/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入司法案件
 */
export async function importCreditJudiciaries(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-judiciary/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
