const Controller = require('./base')
const Param = require('../util/param')
const Rule = require('../util/rule')
const Response = require('../util/response')
const { LoginService } = require('../service/index')

class LoginController extends Controller {
  async getCode (ctx) {
    let { phone } = ctx.request.query
    let response = new Response(ctx)

    let rules = {
      phone: [phone, 'require', Rule.Reg_Phone]
    }

    let param = new Param(ctx, rules)

    if (!param.checkParams()) return

    try {
      let data = await LoginService.findCode(phone)

      if (!data) {
        data = await LoginService.getCode(phone)
      }

      response.success(data)
    } catch (error) {
      response.error({
        code: CODE_UNKNOW_ERROT,
        msg: error
      })
    }
  }

  async checkCode (ctx) {
    let { phone, code } = ctx.request.query

    let response = new Response(ctx)

    let rules = {
      phone: [phone, 'require', Rule.Reg_Phone],
      code: [code, 'require', Rule.Reg_Code]
    }

    let param = new Param(ctx, rules)

    if (!param.checkParams()) return

    try {
      let res = await LoginService.checkCode(phone, code)

      if (res === null) {
        response.error({
          code: CODE_NORMAL_ERROR,
          msg: '请先获取验证码'
        })
      } else {
        let data = {
          res
        }
        if (res === true) {
          let token = await LoginService.createToken(phone)
          data.token = token
          response.success(data)
        } else {
          response.error({
            code: CODE_NORMAL_ERROR,
            msg: '验证码错误'
          })
        }
      }
    } catch (error) {
      response.error({
        code: CODE_UNKNOW_ERROT,
        msg: error
      })
    }
  }

  async authUser (ctx) {
    let { phone, token } = ctx.request.query

    let response = new Response(ctx)

    let rules = {
      phone: [phone, 'require', Rule.Reg_Phone],
      token: [token, 'require']
    }

    let param = new Param(ctx, rules)

    try {
      if (!param.checkParams()) return
      let data = await LoginService.authUser(phone, token)
      response.success(data)
    } catch (error) {
      response.error({
        code: CODE_UNKNOW_ERROT,
        msg: error
      })
    }
  }
}

module.exports = LoginController
