import request from '@/utils/request';
import type { ApiResult } from '@/api/index';
import type { Menu, MenuParam } from './model';
import {SERVER_API_URL} from "@/utils/server";

/**
 * 查询菜单列表
 */
export async function listMenus(params: MenuParam) {
  const res = await request.get<ApiResult<Menu[]>>(
    SERVER_API_URL + '/system/menu',
    {
      params
    }
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加菜单
 */
export async function addMenu(data: Menu) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改菜单
 */
export async function updateMenu(data: Menu) {
  const res = await request.put<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除菜单
 */
export async function removeMenu(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

// 菜单克隆
export async function clone(data: Menu) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu/clone',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 制作插件
 */
export async function createPlug(data: Menu) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu/plug',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

// 安装插件
export async function installPlug(id?: number) {
  const res = await request.get<ApiResult<unknown>>(
    SERVER_API_URL + '/system/menu/install/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
