import { http } from "@/utils/http";

/** 通用响应结果 */
type Result<T = any> = {
  code: number;
  message: string;
  data?: T;
};

/** 分页响应结果 */
type ResultTable<T = any> = {
  code: number;
  message: string;
  data?: {
    /** 列表数据 */
    list: Array<T>;
    /** 总条目数 */
    total?: number;
    /** 每页显示条目个数 */
    pageSize?: number;
    /** 当前页数 */
    currentPage?: number;
  };
};

/** 后端分页数据结构 */
type PageResult<T = any> = {
  records: Array<T>;
  total: number;
  size: number;
  current: number;
  pages?: number;
};

/** 后端分页响应 */
type BasePageResponse<T = any> = {
  code: number;
  message: string;
  data: PageResult<T>;
};

// ==================== 权限管理 ====================

/** 权限对象 */
export type SysPermission = {
  id?: number;
  parentId?: number;
  permissionCode?: string;
  permissionName?: string;
  permissionType?: number;
  path?: string;
  component?: string;
  icon?: string;
  apiUrl?: string;
  apiMethod?: string;
  sortOrder?: number;
  visible?: number;
  status?: number;
  createTime?: string;
  updateTime?: string;
  deleted?: number;
};

/** 分页查询权限列表 */
export const getPermissionList = (params?: {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
}) => {
  return http.request<BasePageResponse<SysPermission>>(
    "get",
    "/api/v1/system/permission/list",
    { params }
  );
};

/** 查询权限树 */
export const getPermissionTree = () => {
  return http.request<Result<SysPermission[]>>(
    "get",
    "/api/v1/system/permission/tree"
  );
};

/** 根据ID查询权限 */
export const getPermissionById = (id: number) => {
  return http.request<Result<SysPermission>>(
    "get",
    `/api/v1/system/permission/${id}`
  );
};

/** 新增权限 */
export const addPermission = (data: SysPermission) => {
  return http.request<Result<number>>("post", "/api/v1/system/permission", {
    data
  });
};

/** 修改权限 */
export const updatePermission = (data: SysPermission) => {
  return http.request<Result<void>>("put", "/api/v1/system/permission", {
    data
  });
};

/** 删除权限 */
export const deletePermission = (id: number) => {
  return http.request<Result<void>>(
    "delete",
    `/api/v1/system/permission/${id}`
  );
};

// ==================== 角色管理 ====================

/** 角色对象 */
export type SysRole = {
  id?: number;
  roleCode?: string;
  roleName?: string;
  roleType?: string;
  description?: string;
  dataScope?: number;
  sortOrder?: number;
  status?: number;
  createBy?: number;
  createTime?: string;
  updateBy?: number;
  updateTime?: string;
  deleted?: number;
};

/** 分页查询角色列表 */
export const getRoleList = (params?: {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
}) => {
  return http.request<BasePageResponse<SysRole>>(
    "get",
    "/api/v1/system/role/list",
    { params }
  );
};

/** 查询所有角色（用于下拉选择） */
export const getAllRoleList = () => {
  return http.request<Result<SysRole[]>>("get", "/api/v1/system/role/all");
};

/** 根据ID查询角色 */
export const getRoleById = (id: number) => {
  return http.request<Result<SysRole>>("get", `/api/v1/system/role/${id}`);
};

/** 新增角色 */
export const addRole = (data: SysRole) => {
  return http.request<Result<number>>("post", "/api/v1/system/role", { data });
};

/** 修改角色 */
export const updateRole = (data: SysRole) => {
  return http.request<Result<void>>("put", "/api/v1/system/role", { data });
};

/** 删除角色 */
export const deleteRole = (id: number) => {
  return http.request<Result<void>>("delete", `/api/v1/system/role/${id}`);
};

/** 查询角色的权限列表（返回完整权限对象列表） */
export const getRolePermissions = (id: number) => {
  return http.request<Result<SysPermission[]>>(
    "get",
    `/api/v1/system/role/${id}/permissions`
  );
};

/** 为角色分配权限 */
export const assignRolePermissions = (id: number, permissionIds: number[]) => {
  return http.request<Result<void>>(
    "post",
    `/api/v1/system/role/${id}/permissions`,
    { data: permissionIds }
  );
};

// ==================== 用户管理 ====================

/** 用户对象 */
export type SysUser = {
  id?: number;
  username?: string;
  password?: string;
  realName?: string;
  nickname?: string;
  avatar?: string;
  gender?: number;
  phone?: string;
  email?: string;
  deptId?: number;
  position?: string;
  employeeNo?: string;
  entryDate?: string;
  status?: number;
  lastLoginTime?: string;
  lastLoginIp?: string;
  createBy?: number;
  createTime?: string;
  updateBy?: number;
  updateTime?: string;
  deleted?: number;
};

/** 分页查询用户列表 */
export const getUserList = (params?: {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
}) => {
  return http.request<BasePageResponse<SysUser>>(
    "get",
    "/api/v1/system/user/list",
    { params }
  );
};

/** 根据ID查询用户 */
export const getUserById = (id: number) => {
  return http.request<Result<SysUser>>("get", `/api/v1/system/user/${id}`);
};

/** 新增用户 */
export const addUser = (data: SysUser) => {
  return http.request<Result<number>>("post", "/api/v1/system/user", { data });
};

/** 修改用户 */
export const updateUser = (data: SysUser) => {
  return http.request<Result<void>>("put", "/api/v1/system/user", { data });
};

/** 删除用户 */
export const deleteUser = (id: number) => {
  return http.request<Result<void>>("delete", `/api/v1/system/user/${id}`);
};

/** 查询用户的角色列表 */
export const getUserRoles = (id: number) => {
  return http.request<Result<SysRole[]>>(
    "get",
    `/api/v1/system/user/${id}/roles`
  );
};

/** 为用户绑定角色 */
export const assignUserRoles = (id: number, roleIds: number[]) => {
  return http.request<Result<void>>("post", `/api/v1/system/user/${id}/roles`, {
    data: roleIds
  });
};

/** 查询用户角色ID列表（用于回显） */
export const getUserRoleIds = (id: number) => {
  return http.request<Result<number[]>>(
    "get",
    `/api/v1/system/user/${id}/roleIds`
  );
};

// ==================== 项目初始化 ====================

/** 项目信息 */
export type ProjectInfo = {
  project_name?: string;
  project_type?: string;
  description?: string;
  objectives?: string;
  plan_start_date?: string;
  plan_end_date?: string;
  budget?: number;
  currency?: string;
  priority?: string;
  tags?: string[];
};

/** 里程碑信息 */
export type MilestoneInfo = {
  milestone_name?: string;
  description?: string;
  plan_date?: string;
  deliverables?: string;
  owner_role?: string;
};

/** 任务信息 */
export type TaskInfo = {
  task_id?: string;
  task_name?: string;
  parent_task_id?: string;
  description?: string;
  plan_start_date?: string;
  plan_end_date?: string;
  estimated_hours?: number;
  priority?: string;
  assignee_role?: string;
  dependencies?: string[];
  deliverables?: string;
};

/** 成员信息 */
export type MemberInfo = {
  name?: string;
  role_code?: string;
  responsibility?: string;
  department?: string;
  weekly_hours?: number;
};

/** 资源信息 */
export type ResourceInfo = {
  resource_name?: string;
  resource_type?: string;
  quantity?: number;
  unit?: string;
  unit_price?: number;
  supplier?: string;
};

/** 风险信息 */
export type RiskInfo = {
  risk_name?: string;
  category?: string;
  description?: string;
  probability?: number;
  impact?: number;
  mitigation_plan?: string;
};

/** 时间节点信息 */
export type TimelineNodeInfo = {
  node_name?: string;
  node_type?: string;
  plan_date?: string;
  description?: string;
  kb_scope?: string[];
};

/** 项目初始化结果 */
export type ProjectInitResult = {
  project: ProjectInfo;
  milestones: MilestoneInfo[];
  tasks: TaskInfo[];
  members: MemberInfo[];
  resources: ResourceInfo[];
  risks: RiskInfo[];
  timeline_nodes: TimelineNodeInfo[];
};

/** 上传文件并生成项目初始化预览数据 */
export const previewProjectInit = (file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  return http.request<Result<ProjectInitResult>>(
    "post",
    "/api/v1/project-init/preview",
    { data: formData }
  );
};

/** 确认并保存项目初始化数据 */
export const confirmProjectInit = (data: ProjectInitResult) => {
  return http.request<Result<ProjectInitResult>>(
    "post",
    "/api/v1/project-init/confirm",
    { data }
  );
};

// ==================== 部门管理 ====================

/** 部门对象 */
export type SysDept = {
  id?: number;
  parentId?: number;
  deptName?: string;
  deptCode?: string;
  leader?: string;
  phone?: string;
  email?: string;
  sortOrder?: number;
  status?: number;
  createTime?: string;
};

/** 获取部门列表（树形结构） */
export const getDeptList = () => {
  return http.request<Result<SysDept[]>>("get", "/api/v1/system/dept/tree");
};

/** 获取部门详情 */
export const getDeptById = (id: number) => {
  return http.request<Result<SysDept>>("get", `/api/v1/system/dept/${id}`);
};

/** 新增部门 */
export const addDept = (data: SysDept) => {
  return http.request<Result<number>>("post", "/api/v1/system/dept", { data });
};

/** 修改部门 */
export const updateDept = (data: SysDept) => {
  return http.request<Result<void>>("put", "/api/v1/system/dept", { data });
};

/** 删除部门 */
export const deleteDept = (id: number) => {
  return http.request<Result<void>>("delete", `/api/v1/system/dept/${id}`);
};

// ==================== 菜单管理 ====================

/** 菜单对象 */
export type SysMenu = {
  id?: number;
  parentId?: number;
  menuName?: string;
  menuType?: number;
  icon?: string;
  path?: string;
  component?: string;
  permission?: string;
  sortOrder?: number;
  status?: number;
  visible?: number;
  keepAlive?: number;
  createTime?: string;
};

/** 获取菜单列表（树形结构） */
export const getMenuList = () => {
  return http.request<Result<SysMenu[]>>("get", "/api/v1/system/menu/tree");
};

/** 获取菜单详情 */
export const getMenuById = (id: number) => {
  return http.request<Result<SysMenu>>("get", `/api/v1/system/menu/${id}`);
};

/** 新增菜单 */
export const addMenu = (data: SysMenu) => {
  return http.request<Result<number>>("post", "/api/v1/system/menu", { data });
};

/** 修改菜单 */
export const updateMenu = (data: SysMenu) => {
  return http.request<Result<void>>("put", "/api/v1/system/menu", { data });
};

/** 删除菜单 */
export const deleteMenu = (id: number) => {
  return http.request<Result<void>>("delete", `/api/v1/system/menu/${id}`);
};

/** 获取系统监控-在线用户列表 */
export const getOnlineLogsList = (data?: object) => {
  return http.request<ResultTable>("post", "/online-logs", { data });
};

/** 获取系统监控-登录日志列表 */
export const getLoginLogsList = (data?: object) => {
  return http.request<ResultTable>("post", "/login-logs", { data });
};

/** 获取系统监控-操作日志列表 */
export const getOperationLogsList = (data?: object) => {
  return http.request<ResultTable>("post", "/operation-logs", { data });
};

/** 获取系统监控-系统日志列表 */
export const getSystemLogsList = (data?: object) => {
  return http.request<ResultTable>("post", "/system-logs", { data });
};

/** 获取系统监控-系统日志-根据 id 查日志详情 */
export const getSystemLogsDetail = (data?: object) => {
  return http.request<Result>("post", "/system-logs-detail", { data });
};

/** 获取角色管理-权限-菜单权限 */
export const getRoleMenu = () => {
  return http.request<Result<SysMenu[]>>("get", "/api/v1/system/menu/tree");
};

/** 获取角色管理-权限-菜单权限-根据角色 id 查对应菜单 */
export const getRoleMenuIds = (roleId: number) => {
  return http.request<Result<number[]>>(
    "get",
    `/api/v1/system/role/${roleId}/menu-ids`
  );
};

/** 为角色分配菜单权限 */
export const assignRoleMenus = (roleId: number, menuIds: number[]) => {
  return http.request<Result<void>>(
    "post",
    `/api/v1/system/role/${roleId}/menus`,
    { data: menuIds }
  );
};
