import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type {
  CompanyUser,
  CompanyUserParam
} from '@/api/oa/company/user/model';
import { MODULES_API_URL } from '@/config/setting';

/**
 * 分页查询企业成员
 */
export async function pageCompanyUser(params: CompanyUserParam) {
  const res = await request.get<ApiResult<PageResult<CompanyUser>>>(
    MODULES_API_URL + '/oa/company-user/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询企业成员列表
 */
export async function listCompanyUser(params?: CompanyUserParam) {
  const res = await request.get<ApiResult<CompanyUser[]>>(
    MODULES_API_URL + '/oa/company-user',
    {
      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 getCompanyUser(id: number) {
  const res = await request.get<ApiResult<CompanyUser>>(
    MODULES_API_URL + '/oa/company-user/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加企业成员
 */
export async function addCompanyUser(data: CompanyUser) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/company-user',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改企业成员
 */
export async function updateCompanyUser(data: CompanyUser) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/company-user',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除企业成员
 */
export async function removeCompanyUser(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/company-user/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除企业成员
 */
export async function removeBatchCompanyUser(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/company-user/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 检查IP是否存在
 */
export async function checkExistence(
  field: string,
  value: string,
  id?: number
) {
  const res = await request.get<ApiResult<unknown>>(
    MODULES_API_URL + '/oa/company-user/existence',
    {
      params: { field, value, id }
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
