'use strict';

const Controller = require('egg').Controller;
const uuidv4 = require('uuid/v4');
class UserController extends Controller {
  // 手机登录
  async loginByPhone() {
    const { ctx, service } = this;
    const params = ctx.request.body;

    if (ctx.isEmpty(params.phone) || isNaN(params.phone) || params.phone.length !== 11) {
      ctx.failed('手机号错误');
    }
    if (ctx.isEmpty(params.code)) {
      ctx.failed('验证码错误');
    }

    const ret = await service.course.v5.user.loginByPhone(params);
    ctx.success(ret);
  }

  // 发送验证码
  async sendVerificationCode() {
    const { ctx, service } = this;
    const queryParams = ctx.request.body;

    if (ctx.isEmpty(queryParams.phone) || isNaN(queryParams.phone) || queryParams.phone.length !== 11) {
      ctx.failed('手机号错误');
    }

    const ret = await service.course.v5.user.sendVerificationCode(queryParams);
    ctx.success(ret);
  }

  // 微信登录
  async loginByWX() {
    const { ctx, service } = this;
    const params = ctx.request.body;

    if (ctx.isEmpty(params.code)) {
      ctx.failed('code is empty');
    }

    const ret = await service.course.v5.user.loginByWX(params);
    ctx.success(ret);
  }

  // 授权后注册用户信息
  async registerUserInfo() {
    const { ctx, service } = this;
    const input_params = ctx.request.body;
    const { avatar, nickname, province, country, sex, city } = input_params;
    const encryptedData = input_params.encryptedData || '';
    const iv = input_params.iv || '';
    const params = { avatar, nickname, province, country, sex, city, encryptedData, iv };

    const ret = await service.course.v5.user.registerUserInfo(params);
    ctx.success(ret);
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx, service } = this;

    const ret = await service.course.v5.user.getUserInfo();

    ctx.success(ret);
  }
}

module.exports = UserController;
