import request from '@/utils/request';
import type {ApiResult, PageResult} from '@/api';
import type {Contract, ContractParam} from './model';

/**
 * 分页查询合同
 */
export async function pageContract(params: ContractParam) {
  const res = await request.get<ApiResult<PageResult<Contract>>>(
    '/tower/tower-contract/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询合同列表
 */
export async function listContract(params?: ContractParam) {
  const res = await request.get<ApiResult<Contract[]>>(
    '/tower/tower-contract',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询合同
 */
export async function getContract(id: number) {
  const res = await request.get<ApiResult<Contract>>(
    '/tower/tower-contract/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加合同
 */
export async function addContract(data: Contract) {
  const res = await request.post<ApiResult<unknown>>(
    '/tower/tower-contract',
    data
  );
  if (res.data.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改合同
 */
export async function updateContract(data: Contract) {
  const res = await request.put<ApiResult<unknown>>(
    '/tower/tower-contract',
    data
  );
  if (res.data.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量修改合同
 */
export async function updateBatchContract(data: Contract[]) {
  const res = await request.put<ApiResult<unknown>>(
    '/tower/tower-contract/batch',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除合同
 */
export async function removeContract(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    '/tower/tower-contract/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除合同
 */
export async function removeBatchContract(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    '/tower/tower-contract/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
