import { PORT_NONE } from "@/api/config/servicePort";
import http from "@/api";
import type { ResultData } from "@/api/interface";

/**
 * 子账号与角色管理相关接口
 */

// 菜单项接口类型
export interface MenuItem {
  menuId: number;
  menuName: string;
  parentId: number;
  menuType: string;
  menuSort: number;
  level: number;
  path: string;
  component: string;
  perms: string | null;
  icon: string;
  status: string;
  visible: string;
  isFrame: string;
  isCache: string;
  delFlag: string;
  createBy: string;
  createdTime: string;
  updateBy: string;
  updatedTime: string;
  remark: string | null;
  children?: MenuItem[];
}

// 菜单树响应接口（后端返回的完整响应结构）
export interface MenuTreeResponse {
  code: number;
  success: boolean;
  data: MenuItem[];
  msg: string;
}

// 创建角色请求参数
export interface CreateRoleDto {
  description?: string;
  menulds?: number[]; // 注意：后端字段名是 menulds
  remark?: string;
  roleName: string;
  roleNameEn?: string;
  roleSort?: number;
  roleType?: string;
  status?: string;
}

// 更新角色请求参数
export interface UpdateRoleDto {
  roleId: number;
  roleName: string;
  menuIds?: number[];
  storeId?: number;
  description?: string;
  remark?: string;
}

// 更新子账号请求参数
export interface UpdateAccountDto {
  accountName: string;
  phone: string;
  roleId: number;
  storeId: number;
  userId: number;
  id: number;
}

// 通用响应接口
export interface ApiResponse {
  code: number;
  success: boolean;
  msg: string;
  data?: any;
}

// 角色权限项接口（扁平格式）
export interface RolePermissionItem {
  level1Permission: string | null;
  level2Permission: string | null;
  level3Permission: string | null;
}

// 角色项接口
export interface RoleItem {
  id: number;
  roleId?: number; // 兼容可能的 roleId 字段
  roleName: string;
  description?: string;
}

/**
 * 获取菜单列表（树形结构）
 * @returns Promise<ResultData<MenuItem[]>>
 */
export const getMenuTree = (): Promise<ResultData<MenuItem[]>> => {
  return http.get<MenuItem[]>(PORT_NONE + `/platform/menu/getMenuTree`, {}, { loading: false });
};

/**
 * 创建角色（包含权限分配）
 * @param createRoleDto 创建角色的数据
 * @returns Promise<ResultData<ApiResponse>>
 */
export const createRole = (createRoleDto: CreateRoleDto): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(PORT_NONE + `/platform/role/createRole`, createRoleDto, { loading: false });
};
// 编辑角色
export const updateRole = (updateRoleDto: UpdateRoleDto): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(PORT_NONE + `/platform/role/updateRole`, updateRoleDto, { loading: false });
};

// 角色管理列表
export const getRolePage = (page: number, size: number, storeId: number): Promise<ResultData<MenuItem[]>> => {
  return http.get<MenuItem[]>(PORT_NONE + `/platform/role/getRolePage`, { page, size, storeId }, { loading: false });
};
// 查询所有正常状态的角色列表
export const getAllNormalRoles = ({ storeId }: { storeId: number }): Promise<ResultData<RoleItem[]>> => {
  return http.get<RoleItem[]>(PORT_NONE + `/platform/role/getAllNormalRoles`, { storeId }, { loading: false });
};

// 查询角色权限表
export const getRolePermissionTable = (params: { roleId: number }): Promise<ResultData<RolePermissionItem[]>> => {
  return http.get<RolePermissionItem[]>(PORT_NONE + `/platform/role/getRolePermissionTable`, params, { loading: false });
};
// 创建账号并分配角色
export const createAccountAndAssignRole = ({ accountName, phone, roleId, storeId }): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(
    PORT_NONE + `/platform/user-role/createAccountAndAssignRole`,
    { accountName, phone, roleId, storeId },
    { loading: false }
  );
};
// 查询当前店铺下的子账号列表
export const querySubAccounts = (
  storeId: number,
  accountName: string,
  phone: string,
  roleName: string
): Promise<ResultData<ApiResponse>> => {
  return http.get<ApiResponse>(
    PORT_NONE + `/platform/user-role/querySubAccounts`,
    { storeId, accountName, phone, roleName },
    { loading: false }
  );
};

// 删除角色
export const deleteRoleWithCheck = (roleId: number): Promise<ResultData<ApiResponse>> => {
  return http.delete<ApiResponse>(PORT_NONE + `/platform/role/deleteRoleWithCheck`, { roleId }, { loading: false });
};
// 分页查询操作记录（已废弃，请使用 operationLog）
export const uoperationLogPage = ({
  page,
  size,
  account,
  endTime,
  module,
  startTime
}: {
  page: number;
  size: number;
  account?: string;
  endTime?: string;
  module?: string;
  startTime?: string;
}): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(
    PORT_NONE + `/platform/operationLog/page`,
    { page, size, account, endTime, module, startTime },
    { loading: false }
  );
};
// 查询子账号详情
export const getSubAccountDetail = (storeId: number, userId: number, roleIdNew: Number): Promise<ResultData<MenuItem[]>> => {
  return http.get<MenuItem[]>(
    PORT_NONE + `/platform/user-role/getSubAccountDetail`,
    { storeId, userId, roleIdNew },
    { loading: false }
  );
};

// 删除子账号
export const removeRole = (roleId: number, storeId: number, userId: number): Promise<ResultData<ApiResponse>> => {
  return http.get<ApiResponse>(PORT_NONE + `/platform/user-role/removeRole`, { roleId, storeId, userId }, { loading: false });
};
// 批量删除子账号 userIds数组 storeId商家id
export const batchDeleteSubAccounts = (storeId: number, userIds: number[]): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(
    PORT_NONE + `/platform/user-role/batchDeleteSubAccounts`,
    { storeId, userIds },
    { loading: false }
  );
};

// 操作记录项接口
export interface OperationLogItem {
  id: number;
  operationModule: string;
  operationType: string;
  operationContent: string;
  operationParams?: string;
  operatorId?: string;
  operatorAccount?: string;
  operatorName?: string;
  userType?: string;
  requestMethod?: string;
  requestPath?: string;
  ipAddress?: string;
  operationTime: string;
}

// 操作记录分页响应
export interface OperationLogPageResponse {
  records: OperationLogItem[];
  total: number;
  size: number;
  current: number;
  orders: any[];
  searchCount: boolean;
  pages: number;
}

// 历史记录列表
export const operationLog = (params: {
  page: number;
  size: number;
  account?: string;
  endTime?: string;
  module?: string;
  startTime?: string;
}): Promise<ResultData<OperationLogPageResponse>> => {
  return http.get<OperationLogPageResponse>(PORT_NONE + `/platform/operationLog/page`, params, { loading: false });
};
// 编辑子账号
export const updateSubAccount = (updateAccountDto: UpdateAccountDto): Promise<ResultData<ApiResponse>> => {
  return http.post<ApiResponse>(PORT_NONE + `/platform/user-role/updateSubAccountNew`, updateAccountDto, { loading: false });
};
