class Oauth::CallbacksController < Oauth::BaseController
  def create
    process_callback_new
  rescue Exception => e
    Rails.logger.info "授权失败:#{e}"
    tip_exception("授权失败")
  end

  private

  def config_providers
    config = Rails.application.config_for(:configuration)
    config.dig("oauth").keys
  end

  # QQ: {"ret":0,"msg":"","is_lost":0,"nickname":"颜值不算太高","gender":"男","gender_type":1,"province":"","city":"","year":"2013","constellation":"","figureurl":"http://qzapp.qlogo.cn/qzapp/101508858/0F860F4B329768F47B22341C5FD9089C/30","figureurl_1":"http://qzapp.qlogo.cn/qzapp/101508858/0F860F4B329768F47B22341C5FD9089C/50","figureurl_2":"http://qzapp.qlogo.cn/qzapp/101508858/0F860F4B329768F47B22341C5FD9089C/100","figureurl_qq_1":"http://thirdqq.qlogo.cn/g?b=oidb\u0026k=My3segFVHFqVmauibJQUltw\u0026s=40\u0026t=1568887757","figureurl_qq_2":"http://thirdqq.qlogo.cn/g?b=oidb\u0026k=My3segFVHFqVmauibJQUltw\u0026s=100\u0026t=1568887757","figureurl_qq":"http://thirdqq.qlogo.cn/g?b=oidb\u0026k=My3segFVHFqVmauibJQUltw\u0026s=140\u0026t=1568887757","figureurl_type":"1","is_yellow_vip":"0","vip":"0","yellow_vip_level":"0","level":"0","is_yellow_year_vip":"0"}
  def process_callback
    Rails.logger.info("[OAuth2] omniauth.auth -> #{request.env['omniauth.auth'].inspect}")
    if auth_hash.blank?
      redirect_to("/login") && return
    end

    new_user = false
    platform = auth_hash[:provider]
    uid = auth_hash[:uid]
    mail = auth_hash.info.email || nil
    nickname = ["gitee", "github"].include?(platform) ? auth_hash.info.name : auth_hash.info.nickname

    open_user = "OpenUsers::#{platform.to_s.capitalize}".constantize.find_by(uid: uid)
    if open_user.present? && open_user.user.present?
      successful_authentication(open_user.user)
    else
      if current_user.blank? || !current_user.logged?
        has_user = User.find_by(mail: mail)
        if has_user.present?
          "OpenUsers::#{platform.to_s.capitalize}".constantize.create!(user_id: has_user.id, uid: uid, extra: auth_hash.extra)
          successful_authentication(has_user)
        else
          new_user = true
          login = build_login_name(platform, auth_hash.info.nickname)
          mail = "#{login}@example.org" if mail.blank?
          code = %W(0 1 2 3 4 5 6 7 8 9)
          rand_password = code.sample(10).join
          reg_result = autologin_register(login, mail, rand_password, platform, nil, nickname)
          Rails.logger.info("[OAuth2] omniauth.auth [reg_result] #{reg_result} ")
          if reg_result[:message].blank?
            open_user = "OpenUsers::#{platform.to_s.capitalize}".constantize.create!(user_id: reg_result[:user][:id], uid: uid, extra: auth_hash.extra)
            successful_authentication(open_user.user)
          else
            tip_exception(reg_result.present? ? reg_result[:message] : "授权失败")
          end
        end
      else
        "OpenUsers::#{platform.to_s.capitalize}".constantize.create!(user: current_user, uid: login, extra: auth_hash.extra)
      end
    end
    redirect_to root_path(new_user: new_user)
  end

  def process_callback_new
    Rails.logger.info("[OAuth2] omniauth.auth -> #{request.env['omniauth.auth'].inspect}")
    if auth_hash.blank?
      redirect_to("/login") && return
    end
    platform = auth_hash[:provider]
    uid = auth_hash[:uid]
    uid = auth_hash.info.unionid if platform == "wechat"

    open_user = "OpenUsers::#{platform.to_s.capitalize}".constantize.find_by(uid: uid)
    if open_user.present? && open_user.user.present?
      successful_authentication(open_user.user)
      redirect_to root_path(new_user: false)
      return
    else
      if current_user.blank? || !current_user.logged?
        session[:unionid] = uid
      else
        "OpenUsers::#{platform.to_s.capitalize}".constantize.create!(user: current_user, uid: uid)
      end
    end
    Rails.logger.info("[OAuth2] session[:unionid] -> #{session[:unionid]}")
    redirect_to "/bindlogin/#{platform}"
  end

  # gitee,github nickname=login,如果系统未占用保留原用户名
  def build_login_name(provider, nickname)
    if ["gitee", "github"].include?(provider) && User.find_by(login: nickname).blank?
      nickname
    else
      User.generate_user_login('p')
    end
  end
end