class Oauth::AcgeController < Oauth::BaseController
  include RegisterHelper

  def refer 
    uid = params['uid'].to_s.strip
    tip_exception("uid不能为空") if uid.blank?

    open_user = OpenUsers::Acge.find_by(uid: uid)
    if open_user.present? && open_user.user.present? 
      render :json => {login: open_user.user.login}
    else 
      render_not_found
    end
  end

  def create 
    begin
      uid = params['uid'].to_s.strip
      tip_exception("uid不能为空") if uid.blank?
      redirect_uri = params['redirect_uri'].to_s.strip
      tip_exception("redirect_uri不能为空") if redirect_uri.blank?
      email = params['email'].to_s.strip 
      tip_exception("email不能为空") if email.blank?
      phone = params['phone'].to_s.strip 
      tip_exception("phone不能为空") if phone.blank?
      name = params['name'].to_s.strip 
      tip_exception("name不能为空") if name.blank?

      open_user = OpenUsers::Acge.find_by(uid: uid)
      if open_user.present? && open_user.user.present?
        successful_authentication(open_user.user)
        redirect_to redirect_uri
        return
      else
        if current_user.blank? || !current_user.logged?
          session[:unionid] = uid 
          user = User.find_by(mail: email) || User.find_by(phone: phone)
          if user.present? 
            OpenUsers::Acge.create!(user: user, uid: uid)
            successful_authentication(user)
            redirect_to redirect_uri

            return
          else
            username = uid
            password = SecureRandom.hex(4)
            reg_result = autologin_register(username, email, password, 'acge', phone, name)
            existing_rows = CSV.read("public/操作系统大赛用户信息.csv")
            new_row = [username, email, password, phone, name]
            existing_rows << new_row
            CSV.open("public/操作系统大赛用户信息.csv", 'wb') do |csv| 
              existing_rows.each { |row| csv << row }
            end
            if reg_result[:message].blank?
              open_user = OpenUsers::Acge.create!(user_id: reg_result[:user][:id], uid: uid)
              successful_authentication(open_user.user)
              redirect_to redirect_uri

              return
            else 
              render_error(reg_result[:message])
            end
          end
        else
          OpenUsers::Acge.create!(user: current_user, uid: uid)
          successful_authentication(current_user)
          redirect_to redirect_uri

          return
        end
      end

      Rails.logger.info("[OAuth2] session[:unionid] -> #{session[:unionid]}")
      # redirect_to "/bindlogin/acge?redirect_uri=#{redirect_uri}"
    rescue Exception => ex
      render_error(ex.message)
    end
  end
end