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

import type { ApiResult, PageResult } from '@/api';
import type { CreditPatent, CreditPatentParam } from './model';

/**
 * 分页查询专利
 */
export async function pageCreditPatent(params: CreditPatentParam) {
  const res = await request.get<ApiResult<PageResult<CreditPatent>>>(
    '/credit/credit-patent/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询专利列表
 */
export async function listCreditPatent(params?: CreditPatentParam) {
  const res = await request.get<ApiResult<CreditPatent[]>>(
    '/credit/credit-patent', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加专利
 */
export async function addCreditPatent(data: CreditPatent) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-patent',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改专利
 */
export async function updateCreditPatent(data: CreditPatent) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-patent',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

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

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

/**
 * 根据id查询专利
 */
export async function getCreditPatent(id: number) {
  const res = await request.get<ApiResult<CreditPatent>>(
    '/credit/credit-patent/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

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