/**
 * Namespace Api
 *
 * All backend api type
 */
declare namespace Api {
  namespace Common {
    /** common params of paginating */
    interface PaginatingCommonParams {
      total: number;
      pageNum: number;
      pageSize: number;
    }

    /** common params of paginating query list data */
    // interface PaginatingQueryRecord<T = any> extends PaginatingCommonParams {
    //   records: T[];
    // }

    interface PaginatingQueryRecord<T = any> {
      total: number; // 总条数
      data: T[]; // 数据列表
    }

    /** common search params of table */
    type CommonSearchParams = Pick<Common.PaginatingCommonParams, 'pageNum' | 'pageSize'>;

    /**
     * enable status
     *
     * - "1": enabled
     * - "2": disabled
     */
    type EnableStatus = '1' | '2';

    /**
     * 特殊的 启用状态，主要是迁移若依的后端奇葩的启用状态
     *
     * - "0": 启用
     * - "1": 禁用
     */
    type SpecialEnableStatus = '0' | '1';

    /** common record */
    type CommonRecord<T = any> = {
      /** record id */
      // id: number;
      [key: string]: any; // 添加索引签名
      /** record creator */
      createBy?: string;
      /** record create time */
      createTime?: string;
      /** record updater */
      updateBy?: string;
      /** record update time */
      updateTime?: string;
      /** record status */
      status?: EnableStatus | SpecialEnableStatus;
    } & T;

    // 适用于 时间范围查询的参数类型，例如：
    type ParamsTime<T extends string = 'Time'> = {
      [K in `begin${Capitalize<T>}` | `end${Capitalize<T>}`]?: string;
    };
  }

  /**
   * namespace Auth
   *
   * backend api module: "auth"
   */
  namespace Auth {
    interface LoginToken {
      token: string;
      refreshToken: string;
    }

    interface UserInfo {
      user: Partial<UserInfoObj>; // 使用 Partial 将 UserInfoObj 中的字段全部变为可选
      roles: string[];
      permissions: string[];
    }

    interface UserInfoObj {
      userId: number;
      userName: string;
      email?: string;
      phonenumber?: string;
      sex?: string;
      status?: string;
      avatar?: string;
      loginDate?: string;
      dept?: DeptInfo;
      roles?: RoleInfo[];
      admin?: boolean;
      [key: string]: any; // 允许额外的字段
    }

    interface DeptInfo {
      deptId: string;
      roleId: number;
      deptName?: string;
      [key: string]: any;
    }

    interface RoleInfo {
      roleId: number;
      roleKey: string;
      roleName: string;
      admin?: boolean;
      [key: string]: any;
    }

    interface Captcha {
      img: string;
      uuid: string;
    }
  }

  /**
   * namespace Route
   *
   * backend api module: "route"
   */
  namespace Route {
    type ElegantConstRoute = import('@elegant-router/types').ElegantConstRoute;

    interface MenuRoute extends ElegantConstRoute {
      id: string;
    }

    interface UserRoute {
      routes: MenuRoute[];
      home?: import('@elegant-router/types').LastLevelRouteKey;
    }
  }
  /**
   * namespace RouYiRoute
   *
   * 后端若依的路由
   */
  namespace RouYiRoute {
    // 定义 Meta 信息
    interface RouteMeta {
      title: string; // 菜单标题
      icon?: string; // 图标，可选
      noCache?: boolean; // 是否缓存，可选
      link?: string | null; // 外链地址，可选
    }

    // 定义子路由
    interface ChildRoute {
      name: string; // 路由名称
      path: string; // 路由路径
      hidden?: boolean; // 是否隐藏
      component?: string; // 组件路径，可选（动态加载时的字符串形式）
      meta: RouteMeta; // 路由的元信息
      children?: ChildRoute[]; // 子路由列表，可递归
    }

    // 主路由
    interface RYRoute extends ChildRoute {
      redirect?: string; // 重定向地址，可选
      alwaysShow?: boolean; // 是否总是显示子菜单
    }
  }

  /**
   * namespace SystemManage
   *
   * backend api module: "systemManage"
   */
  namespace SystemManage {
    type CommonSearchParams = Pick<Common.PaginatingCommonParams, 'pageNum' | 'pageSize'>;

    type TreeKey = string | number;

    /** role */
    type Role = Common.CommonRecord<{
      /** 是否是超级管理员 */
      admin?: boolean;
      /** role name */
      roleName: string;
      /** 权限字符 */
      roleKey: string;

      roleId: string | number;
      createTime?: string;
      flag?: boolean;
      dataScope?: string;
      status?: Common.SpecialEnableStatus;
      roleSort?: number;
      menuIds?: TreeKey[];
      deptIds?: TreeKey[];
      menuCheckStrictly?: boolean;
      deptCheckStrictly?: boolean;
      remark?: string;
    }>;

    /** role search params：CommonType.RecordNullable：将null添加到所有属性 */
    type RoleSearchParams = CommonType.RecordNullable<
      Pick<Api.SystemManage.Role, 'roleName' | 'roleKey' | 'status'> & CommonSearchParams
    >;

    /** role list */
    type RoleList = Common.PaginatingQueryRecord<Role>;

    /** all role */
    type AllRole = Pick<Role, 'roleId' | 'roleName' | 'roleKey'>;

    /**
     * user gender
     *
     * - "1": "male"
     * - "2": "female"
     */
    type UserGender = '0' | '1' | '2';

    /** user */
    type User = Common.CommonRecord<{
      userId: string | number;
      avatar?: string;
      deptId?: string;
      nickName?: string;
      userName?: string;
      phonenumber?: string;
      password?: string;
      email?: string;
      sex?: string;
      createTime?: string;
      status?: Common.SpecialEnableStatus;
      remark?: string;
      dept?: Dept;
      postIds?: string[];
      roleIds?: string[];
    }>;

    /** user search params */
    type UserSearchParams = CommonType.RecordNullable<
      Pick<Api.SystemManage.User, 'deptId' | 'nickName' | 'phonenumber' | 'status'> & CommonSearchParams
    >;

    /** user list */
    type UserList = Common.PaginatingQueryRecord<User>;

    /**
     * menu type
     *
     * - "M": 目录
     * - "C": 菜单
     * - "F": 按钮
     */
    type MenuType = 'M' | 'C' | 'F';

    type MenuButton = {
      /**
       * button code
       *
       * it can be used to control the button permission
       */
      code: string;
      /** button description */
      desc: string;
    };

    /**
     * icon type
     *
     * - "1": iconify icon
     * - "2": local icon
     */
    type IconType = '1' | '2';

    type MenuPropsOfRoute = Pick<
      import('vue-router').RouteMeta,
      | 'i18nKey'
      | 'keepAlive'
      | 'constant'
      | 'order'
      | 'orderNum'
      | 'href'
      | 'hideInMenu'
      | 'activeMenu'
      | 'multiTab'
      | 'fixedIndexInTab'
      | 'query'
    >;

    type Menu = Common.CommonRecord<{
      menuId: number | null | undefined;
      /** parent menu id */
      parentId: number;
      /** menu type */
      menuType: MenuType;
      /** menu name */
      menuName: string;
      /** route name */
      routeName: string;
      /** route path */
      routePath: string;
      /** component */
      component?: string;
      /** iconify icon name or local icon name */
      icon: string;
      /** icon type */
      iconType?: Api.SystemManage.IconType;
      /** 权限标识 */
      perms: string;
      /** 路由路径 --若依 */
      path: string;
      /** buttons */
      buttons?: MenuButton[] | null;
      /** children menu */
      children?: Menu[] | null;
      status?: Common.SpecialEnableStatus;
      constant?: boolean | null;
      hideInMenu?: boolean;
      keepAlive?: boolean;
    }> &
      MenuPropsOfRoute;

    /** menu list */
    type MenuList = Common.PaginatingQueryRecord<Menu>;

    /** 菜单搜索参数 */
    type MenuSearchParams = CommonType.RecordNullable<
      Pick<Api.SystemManage.Menu, 'menuName' | 'status'> & CommonSearchParams
    >;

    type MenuTree = {
      id: number;
      label: string;
      pId: number;
      children?: MenuTree[];
    };

    /** dept */
    type Dept = Common.CommonRecord<{
      deptId: string;
      parentId?: string;
      deptName?: string;
      orderNum?: number;
      leader?: string;
      phone?: string;
      email?: string;
      status?: Common.SpecialEnableStatus;
      children?: Dept[];
    }>;

    /** 部门列表 */
    type DeptList = Common.PaginatingQueryRecord<Dept>;
    /** 部门搜索参数 */
    type DeptSearchParams = CommonType.RecordNullable<
      Pick<Api.SystemManage.Dept, 'deptName' | 'status'> & CommonSearchParams
    >;

    /** 岗位 */
    type Post = Common.CommonRecord<{
      postId: string;
      postCode?: string;
      postName?: string;
      postSort?: number;
      status?: Common.SpecialEnableStatus;
      remark?: string;
    }>;
    /** 岗位列表 */
    type PostList = Common.PaginatingQueryRecord<Post>;
    /** 岗位搜索参数 */
    type PostSearchParams = CommonType.RecordNullable<
      Pick<Post, 'postCode' | 'postName' | 'status'> & CommonSearchParams
    >;

    /** 字典 */
    type Dict = Common.CommonRecord<{
      dictId: string;
      dictName: string;
      dictType: string;
      status?: Common.SpecialEnableStatus;
      remark?: string;
    }>;
    /** 字典列表 */
    type DictList = Common.PaginatingQueryRecord<Dict>;
    /** 字典搜索参数 */
    type DictSearchParams = CommonType.RecordNullable<
      Pick<Dict, 'dictName' | 'dictType' | 'status'> & CommonSearchParams
    >;
    /** 字典详情 */
    type DictInfo = Common.CommonRecord<{
      dictCode?: string;
      dictSort?: number;
      dictLabel: string;
      dictValue: string;
      dictType: Dict['dictType'];
      status: Common.SpecialEnableStatus;
      cssClass?: string;
      listClass?: 'default' | 'primary' | 'success' | 'info' | 'warning' | 'error' | 'danger'; // Ntag没有danger，需要转
      remark?: string;
    }>;
    /** 字典详情列表 */
    type DictInfoList = Common.PaginatingQueryRecord<DictInfo>;
    /** 字典详情搜索参数 */
    type DictInfoSearchParams = CommonType.RecordNullable<
      Pick<DictInfo, 'dictLabel' | 'dictType' | 'status'> & CommonSearchParams
    >;

    /** 参数设置 */
    type Config = Common.CommonRecord<{
      configId: number | string;
      configKey: string; // 参数键名
      configName: string; // 参数名称
      configType: 'Y' | 'N'; // 是否系统内置 (Y是, N否)
      configValue: string; // 参数键值
      remark: string;
      params: Common.ParamsTime | [];
    }>;

    /** 参数列表 */
    type ConfigList = Common.PaginatingQueryRecord<Config>;
    /** 参数搜索参数 */
    type ConfigSearchParams = CommonType.RecordNullable<
      Pick<Config, 'configName' | 'configKey' | 'configType' | 'params'> & CommonSearchParams
    >;

    /** 定时任务 */
    type Job = Common.CommonRecord<{
      jobId: number | string;
      jobName: string;
      jobGroup: Common.EnableStatus; // 任务组名(1默认,2系统
      invokeTarget: string; // 调用方法
      cronExpression: string; // cron表达式
      concurrent: Common.SpecialEnableStatus; // 是否并发执行 (0允许,1禁止)
      misfirePolicy: '1' | '2' | '3'; // 错误策略[1立即执行,2执行一次,3放弃执行]
      status: Common.SpecialEnableStatus; // 状态 (0开启, 1关闭)
      nextValidTime: string; // 下一次执行时间
    }>;

    /** 参数列表 */
    type JobList = Common.PaginatingQueryRecord<Job>;
    /** 参数搜索参数 */
    type JobSearchParams = CommonType.RecordNullable<Pick<Job, 'jobName' | 'jobGroup' | 'status'> & CommonSearchParams>;

    /** 调度日志 */
    type JobLog = Common.CommonRecord<{
      jobLogId: number | string;
      jobMessage: string; // 日志信息
      exceptionInfo: string; // 异常信息
      status: Common.SpecialEnableStatus; // 状态 (0成功, 1失败)
      params: Common.ParamsTime | [];
    }> &
      Pick<Job, 'jobName' | 'jobGroup' | 'invokeTarget'>;

    /** 参数列表 */
    type JobLogList = Common.PaginatingQueryRecord<JobLog>;
    /** 参数搜索参数 */
    type JobLogSearchParams = CommonType.RecordNullable<
      Pick<JobLog, 'jobName' | 'jobGroup' | 'status' | 'params'> & CommonSearchParams
    >;

    // 操作日志
    type Operlog = {
      operId: number; // 日志Id
      title: string; // 系统模块
      operName: string; // 操作人员
      businessType: string; // 操作类型
      errorMsg: string; // 错误消息
      jsonResult: string; // 返回参数
      method: string; // 操作方法
      operIp: string; // 操作地址
      operLocation: string; // 操作地点
      operParam: string; // 请求参数
      operTime: string; // 操作时间
      operUrl: string; // 请求地址
      requestMethod: import('axios').Method; // 请求方式
      status: Common.SpecialEnableStatus; // 操作状态
    };

    type OperlogList = Common.PaginatingQueryRecord<Operlog>;
    type OperlogSearchParams = CommonType.RecordNullable<
      Pick<Operlog, 'title' | 'operName' | 'businessType' | 'status'> &
        Common.CommonSearchParams & {
          params: Common.ParamsTime | [];
          orderByColumn: string;
          isAsc: 'desc' | 'asc'; // 排列 desc或者asc
        }
    >;

    // 登录日志
    type Loginlog = {
      infoId: number; // 访问ID
      userName: string; // 用户账号
      ipaddr: string; // 登录IP地址
      loginLocation: string; // 登录地点
      browser: string; // l浏览器类型
      os: string; // 操作系统
      status: Common.SpecialEnableStatus; // 状态
      msg: string; // 操作消息
      loginTime: string; // 访问时间
    };

    type LoginlogList = Common.PaginatingQueryRecord<Loginlog>;
    type LoginlogSearchParams = CommonType.RecordNullable<
      Pick<Loginlog, 'ipaddr' | 'userName' | 'status'> &
        Common.CommonSearchParams & {
          params: Common.ParamsTime | [];
          orderByColumn: string;
          isAsc: 'desc' | 'asc'; // 排列 desc或者asc
        }
    >;

    type Oss = {
      ossId: number; // 云存储主键
      fileName: string; // 文件名称
      originalName: string; // 原名
      fileSuffix: string; // 文件后缀
      url: string; // 文件展示
      createTime: string; // 上传时间
      createBy: string; // 上传用户
      service: string; // 服务商
    };

    type OssList = Common.PaginatingQueryRecord<Oss>;
    type OssSearchParams = CommonType.RecordNullable<
      Pick<Oss, 'fileName' | 'originalName' | 'fileSuffix' | 'service' | 'createBy'> &
        Common.CommonSearchParams & {
          params: Common.ParamsTime<'CreateTime'> | [];
        }
    >;

    type OssConfig = {
      ossConfigId: number; // 配置ID
      configKey: string; // 配置Key
      endpoint: string; // 访问站点
      bucketName: string; // 存储桶名称
      prefix: string; // 前缀
      region: string; // 域
      status: Common.SpecialEnableStatus; // 状态
      accessKey: string; // accessKey
      secretKey: string; // 秘钥
      isHttps: 'Y' | 'N'; // 是否使用HTTPS
      remark: string | null; // 备注
    };

    type OssConfigList = Common.PaginatingQueryRecord<OssConfig>;
    type OssConfigSearchParams = CommonType.RecordNullable<
      Pick<OssConfig, 'bucketName' | 'configKey' | 'status'> & Common.CommonSearchParams
    >;

    type Online = {
      browser: string; // 浏览器类型
      deptName: string | null; // 部门名称（允许null）
      ipaddr: string; // 登录IP地址
      loginLocation: string; // 登录地点
      loginTime: number; // 登录时间戳（单位：毫秒）
      os: string; // 操作系统
      tokenId: string; // 登录令牌
      userName: string; // 用户名
    };

    // 对应的列表类型
    type OnlineList = Common.PaginatingQueryRecord<Online>;

    // 搜索参数类型（参考现有模式）
    type OnlineSearchParams = CommonType.RecordNullable<
      Pick<Online, 'userName' | 'ipaddr'> & Common.CommonSearchParams
    >;
  }

  /** namespace SystemTool */
  namespace SystemTool {
    /** 代码生成 */
    type GenInfo = Common.CommonRecord<{
      subTableName?: string;
      subTableFkName?: string;
      tplWebType?: string;
      tplCategory?: string;
      packageName?: string;
      moduleName?: string;
      businessName?: string;
      functionName?: string;
      treeName?: string;
      genType?: string;
      parentMenuId?: string;
      genPath?: string;
      treeCode?: string;
      treeParentCode?: string;
      tableId: string;
      tableName?: string;
      tableComment?: string;
      className?: string;
      functionAuthor?: string;
      remark?: string;
    }>;
    /** 代码生成列表 */
    type GenInfoList = Common.PaginatingQueryRecord<GenInfo>;
    /** 代码生成搜索参数 */
    type GenInfoSearchParams = CommonType.RecordNullable<
      Pick<GenInfo, 'tableName' | 'tableComment'> & Common.CommonSearchParams
    >;
    type GenEColumn = {
      columnName?: string;
      columnComment?: string;
    };
    type GenTColumn = {
      tableName?: string;
      tableComment?: string;
      columns?: GenEColumn[];
    };

    // 查询db数据库列表
    type DbInfo = Common.CommonRecord<{
      tableName: string;
      tableComment: string;
    }>;
    type DbInfoList = Common.PaginatingQueryRecord<DbInfo>;
    type DbInfoSearchParams = CommonType.RecordNullable<
      Pick<DbInfo, 'tableName' | 'tableComment'> & Common.CommonSearchParams
    >;
  }

  namespace ModelConfig {
    /** 合同模型配置对象 */
    type ContractModelConfigVo = {
      id: string; // 配置ID
      modelName: string; // 模型名称
      modelUrl: string; // 模型地址
      modelKey: string; // 模型密钥
      modelType: string | null; // 模型类型
      modelVersion: string | null; // 模型版本
    };
    /** 合同模型配置分页列表 */
    type ContractModelConfigList = Common.PaginatingQueryRecord<ContractModelConfigVo>;
    /** 合同模型配置搜索参数 */
    type ContractModelConfigSearchParams = CommonType.RecordNullable<
      Pick<ContractModelConfigVo, 'id' | 'modelName' | 'modelKey' | 'modelType'> &
        Common.CommonSearchParams & {
          orderByColumn?: string; // 排序列
          isAsc?: 'desc' | 'asc'; // 排序方向 desc 或 asc
        }
    >;
  }
}
