class Oauth2Controller < ActionController::Base
  layout 'doorkeeper/application'
  include LoginHelper

  def show
    client_id = params[:call_url].split("client_id=")[1].split("&redirect_uri")[0]
    @call_url = request.fullpath.split('call_url=').last
    @app = Doorkeeper::Application.find_by(uid: client_id)
  end

  def create
    if params[:login].blank?
      @error = {msg: '邮箱地址或用户名不能为空', id: 'login'}
    elsif params[:password].blank?
      @error = {msg: '请输入密码', id: 'password'}
    else
      @user = User.try_to_login(params[:login], params[:password])

      return @error = {msg: '账号或密码错误', id: 'login'} if @user.blank?
      return @error = {msg: '违反平台使用规范，账号已被锁定', id: 'login'} if @user.locked?

      login_control = LimitForbidControl::UserLogin.new(@user)
      return  @error = {msg: "登录密码出错已达上限，账号已被锁定，请#{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'} if login_control.forbid?

      password_ok = @user.check_password?(params[:password].to_s)
      unless password_ok
        if login_control.remain_times-1 == 0
           @error = {msg: "登录密码出错已达上限，账号已被锁定，请#{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'}
        else
           @error = {msg: "你已经输错密码#{login_control.error_times+1}次，还剩余#{login_control.remain_times-1}次机会", id: 'account'}
        end
        login_control.increment!
        return
      end
      login_control.clear
      redirect_to params[:call_url] + "&auth=" + @user.login
    end
  end
end
