import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { App, AppParam } from './model';
import { Menu } from '@/api/system/menu/model';

/**
 * 分页查询应用
 */
export async function pageApp(params: AppParam) {
  const res = await request.get<ApiResult<PageResult<App>>>('/oa/app/page', {
    params
  });
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询应用列表
 */
export async function listApp(params?: AppParam) {
  const res = await request.get<ApiResult<App[]>>('/oa/app', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加应用
 */
export async function addApp(data: App) {
  const res = await request.post<ApiResult<unknown>>('/oa/app', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改应用
 */
export async function updateApp(data: App) {
  const res = await request.put<ApiResult<unknown>>('/oa/app', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除应用
 */
export async function removeApp(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/oa/app/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除应用
 */
export async function removeBatchApp(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>('/oa/app/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>>('/oa/app/existence', {
    params: { field, value, id }
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

// 添加菜单
export async function saveMenu(data: App) {
  const res = await request.post<ApiResult<unknown>>('/oa/app/saveMenu', data);
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

// 添加菜单按钮
export async function saveAuthority(data: Menu[]) {
  const res = await request.post<ApiResult<unknown>>(
    '/oa/app/saveAuthority',
    data
  );
  if (res.data.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.data.message));
}
