class Oauth::Ci4sController < Oauth::BaseController
  include RegisterHelper


  def oauth_url
    redirect_to Ci4s::Service.oauth_url
  end

  # 需要educoder那边设置回调地址
  def create
    begin
      code = params['code'].to_s.strip
      tip_exception("code不能为空") if code.blank?

      new_user = false
      token = Ci4s::Service.access_token(code)
      Rails.logger.info("[OAuth2] result -> #{token}")
      result = Ci4s::Service.user_info(token[:access_token])
      tip_exception("请求用户信息错误") if result['code'].to_i != 200
      user_info = result['data']
      # 存在该用户
      open_user = OpenUsers::Ci4s.find_by(uid: user_info['username'])
      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?
          new_user = true
          session[:unionid] = user_info['username']
          # login = User.generate_login('E')
          login = user_info['username']
          email = user_info['email']
          email = "#{login}@forge.com" if email.blank?
          reg_result = autologin_register(login, email, "Ec#{login}2021#", 'educoder', user_info['mobile'])
          Rails.logger.info("[OAuth2] reg_result -> #{reg_result}")
          if reg_result[:message].blank?
            open_user = OpenUsers::Ci4s.create!(user_id: reg_result[:user][:id], uid: login, extra: user_info)
            successful_authentication(open_user.user)
          else
            tip_exception(reg_result[:message])
          end
        else
          OpenUsers::Ci4s.create!(user: current_user, uid: user_info['username'], extra: user_info)
        end
      end
      Rails.logger.info("[OAuth2] session[:unionid] -> #{session[:unionid]}")
      redirect_to root_path(new_user: new_user)
    rescue Exception => ex
      render_error(ex.message)
    end
  end
end
