import { Context } from '@midwayjs/koa';
import { ApiResponse, ApiTags } from '@midwayjs/swagger';
import { JwtService } from '@midwayjs/jwt';
import get = require('lodash/get');
import { RoleService } from '../service/system/role.service';
import { Controller, Get, Inject, MidwayWebRouterService, Post } from '@midwayjs/core';
import { ErrorCode, ServiceError } from '../error/service.error';
@ApiTags(['工具'])
@Controller('/token')
export class TokenController {
  @Inject()
  jwtService: JwtService;

  @Inject()
  roleService: RoleService;
  @Inject()
  webRouterService: MidwayWebRouterService;

  @Inject()
  ctx: Context;

  @Get('/tokenView')
  @ApiResponse({})
  async tokenView() {
    const token = get(this.ctx, 'request.header.token');
    if (!token) throw new ServiceError(ErrorCode.NOT_LOGIN);
    const result: any = await this.jwtService.decode(token);
    const userMenusResult = await this.roleService.getUserMenus();
    const menus = get(userMenusResult, 'menus');
    const role_code = get(userMenusResult, 'role_code');
    result.menus = menus;
    result.role_code = role_code;
    return result;
  }

  /**
   * 获取用户编码
   * @returns 用户编码列表
   */
  @Post('/getUserApiCodes')
  async getUserApiCodes() {
    const codes = await this.roleService.getUserApiCodes();
    return codes;
  }
  /**
   * 查询要访问的路由编码,query没有 .query
   * @returns {string} 路由编码
   */
  @Post('/gerRouterInfo')
  async getRouterInfo() {
    const body: any = this.ctx.request.body;
    const route = await this.webRouterService.getMatchedRouterInfo(get(body, 'uri'), get(body, 'method'));
    const col = new route.controllerClz();
    const codes = [];
    const controllerCode = col.controllerCode;
    codes.push(controllerCode);
    if (route.method !== 'query') codes.push(route.method);
    const code = codes.join('.');
    return code;
  }
  // @Get('/app')
  // async appLogin(fiiter) {
  //   const { config, js_code } = fiiter.query;
  //   const result: any = await this.service.appLogin(config, js_code);
  //   return result;
  // }
}
