class Oauth::GitlinkController < Oauth::BaseController
  def bind
    begin
      login = params[:login]
      mail = params[:mail] || nil
      callback_url = params[:callback_url]
      token = params[:token]

      ::OauthEducoderForm.new({login: login, token: token, callback_url: callback_url}).validate!

      open_user= OpenUsers::Gitlink.find_by(uid: login) || OpenUsers::Gitlink.find_by(uid: mail)

      if open_user.present? && open_user.user.present? && open_user.user.email_binded?
        Rails.logger.info "######## open_user exist and open_user.user exsit and email is binded ok"
        successful_authentication(open_user.user)

        redirect_to callback_url
      else
        Rails.logger.info "######## open user not exits"
        user = User.find_by(login: login) || User.find_by(mail: mail)

        if user.is_a?(User) && !user.is_a?(AnonymousUser)
          OpenUsers::Gitlink.create!(user: user, uid: login)
          successful_authentication(user)

          redirect_to callback_url
        else
          redirect_to oauth_register_path(login: login, mail: mail, callback_url: callback_url)
        end
      end
    rescue WechatOauth::Error => ex
      render_error(ex.message)
    end
  end

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

      result = GitlinkOauth::Service.access_token(code)
      result = GitlinkOauth::Service.user_info(result[:access_token])
      login = result['login']
      mail = result['email']
      nickName = result['username']
      new_user = false
      # 存在该用户
      open_user = OpenUsers::Gitlink.find_by(uid: login)
      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::Gitlink.create!(user_id: has_user.id, uid: login, extra: result)
            successful_authentication(has_user)
          else
            new_user = true
            login = User.generate_user_login('p')
            mail = "#{login}@example.org" if mail.blank?
            reg_result = autologin_register(login, mail, "Ec#{login}2021#", 'gitlink', nil, nickName)
            Rails.logger.info("[Gitlink] [reg_result] #{reg_result} ")
            if reg_result[:message].blank?
              open_user = OpenUsers::Gitlink.create!(user_id: reg_result[:user][:id], uid: login, extra: result)
              successful_authentication(open_user.user)
            else
              tip_exception(reg_result.present? ? reg_result[:message] : "授权失败")
            end
          end
        else
          OpenUsers::Gitlink.create!(user: current_user, uid: login, extra: result)
        end
      end

      redirect_to root_path(new_user: new_user)
    rescue Exception => ex
      render_error(ex.message)
    end
  end
end
