import { Body, Config, Controller, Inject, Param, Post, Get } from '@midwayjs/core';
import { ApiTags } from '@midwayjs/swagger';
import { LoginDTO, LoginType, LoginVO, UPwdDTO } from '../interface/login.interface';
import { LoginService } from '../service/login.service';
import { JwtService } from '@midwayjs/jwt';
import { Context } from '@midwayjs/koa';
const assert = require('assert');
import get = require('lodash/get');
import { UtilService } from '../service/util.service';

@ApiTags(['登录服务'])
@Controller('/login')
export class LoginController {
  @Inject()
  loginService: LoginService;
  @Inject()
  jwtService: JwtService;
  @Inject()
  utilService: UtilService;
  @Config('jwt.secret')
  jwtSecret;
  @Config('jwt.expiresIn')
  jwtExpiresIn;
  @Inject()
  ctx: Context;
  /**
   * 账密登录
   * @param data 用户名和密码
   * @param type 用户类型
   */
  @Post('/:type', { routerName: '登录' })
  async toLogin(@Body() data: LoginDTO, @Param('type') type: string) {
    const user = await this.loginService.loginByAccount(data, LoginType[type]);
    // 超级管理员不需要设置角色,部门,直接给
    if (type === 'Admin' && user.is_super === '0') user.role = [type];
    let vo = new LoginVO(user);
    vo = JSON.parse(JSON.stringify(vo));
    vo.login_code = await this.loginService.onePointLogin(vo);
    const token = await this.jwtService.sign(vo, this.jwtSecret);
    return token;
  }

  /**
   * TODO:微信小程序登录
   * @param type 用户类型
   */
  @Post('/wxapp/:type')
  async wxAppLogin(@Body('openid') openid: string, @Param('type') type: string) {
    if (!openid) assert(openid, '缺少微信唯一标识信息');
    const user = await this.loginService.wxAppLogin(openid, LoginType[type]);
    let vo = new LoginVO(user);
    vo = JSON.parse(JSON.stringify(vo));
    vo.login_code = await this.loginService.onePointLogin(vo);
    const token = await this.jwtService.sign(vo, this.jwtSecret);
    return token;
  }
  /**
   * 修改密码
   * @param data 修改密码所需数据
   * @param type 账户类型
   */
  @Post('/updatePwd/:type', { routerName: '修改密码' })
  async updatePwd(@Body() data: UPwdDTO, @Param('type') type: string) {
    await this.loginService.updatePwd(data, LoginType[type]);
    return 'ok';
  }

  @Post('/resetPwd/:type', { routerName: '重置密码' })
  async resetPwd(@Body('id') id: number, @Param('type') type: string) {
    // 随机密码
    const data = new UPwdDTO();
    data.id = id;
    data.password = this.utilService.randomStr();
    await this.loginService.updatePwd(data, LoginType[type]);
    return data.password;
  }

  @Get('/analysis')
  async analysisToken() {
    const token = get(this.ctx, 'request.header.token');
    assert(token, '缺少token信息');
    const result = await this.jwtService.decodeSync(token);
    return result;
  }
}
