class MainController < ApplicationController
  protect_from_forgery except: :index
  skip_before_action :check_sign
  skip_before_action :user_setup
  skip_before_action :setup_laboratory

  #before_action :sso_login, only: [:index]

  def first_stamp
    render :json => { status: 0, message: Time.now.to_i, online: UserOnline.count }
  end

  def test_404
    status_code = 404
    status = status_code.to_s
    fname = %w[404 403 422 500].include?(status) ? status : "unknown"

    respond_to do |format|
      format.html { render template: "/shared/#{fname}", handler: [:erb], status: status }
      format.xml { render :xml => Laboratory.limit(1).to_xml, status: status }
      format.all { render body: nil, status: status }
    end
  end

  def index
    domain_session = params[:_educoder_session]
    if domain_session
      uid_logger("main start  domain_session is #{domain_session}")
      if cookies[:_educoder_session] != domain_session
        cookies[:_educoder_session] = nil
        cookies[:_educoder_session] = domain_session
      end


      uid_logger("main start is #{cookies[:_educoder_session]}")
    end

    # TODO: 这块之后需要整合，者架构重新变化，统一跳转到index后再路由分发
    if params[:path] && params[:path]&.include?("h5educoderbuild") && params[:path].split("/").first == "h5educoderbuild"
      render file: 'public/h5educoderbuild/index.html', :layout => false, :content_type=> 'text/html'
    elsif params[:path].to_s.include?("test_404")
      test_404
    else
      render file: 'public/react/build/index.html', :layout => false, :content_type=> 'text/html'
    end

  end

  def sso_login
    return if current_user.logged?
    return unless EduSetting.get("509_SSO_LOGIN_OPEN").to_s == "true"
    user_token = params['access_token']
    Rails.logger.info "=== params.access_token user_token ====#{user_token}"

    app_domain = EduSetting.get("509_APP_DOMAIN")
    access_token = get_509_sso_token
    if access_token.present?
      api_user_url ="#{app_domain}/api/sso/user?access_token=#{user_token}"
      user_params = url_http_post(api_user_url, {})
      if user_params['rsltcode'].to_s == "0"
        login = user_params['account']
        login = login[0..20] if login.size > 29
        phone = user_params['mobile']
        mail = user_params['useremail']
        mail = "#{login}@example.org" if mail.blank?
        nickname = user_params['fullname']
        orgName = user_params['orgName']
        user = phone.present? ? User.find_by(phone: phone) : nil
        user = User.where("login = ?  or phone = ? or mail = ? ", login.presence, phone.presence, mail.presence).first if user.nil?
        if user.blank?
          Rails.logger.info "=== 创建新用户 ===="
          user = User.new(type: "User")
          user.login = login
          user.phone = phone
          user.mail = mail
          user.nickname = nickname if nickname.present?
          user.company_name = orgName if orgName.present?
          user.user_type = "6"
          user.professional_field = "12"
          password = "a12345678"
          user.password = password

          # gitea用户注册, email, username, password
          interactor = Gitea::RegisterInteractor.call({username: user.login, email: user.mail, password: password})
          if interactor.success?
            gitea_user = interactor.result
            result = Gitea::User::GenerateTokenService.call(user.login, password)
            user.gitea_token = result['sha1']
            user.gitea_uid = gitea_user[:body]['id']
            if user.save!
              UserExtension.create!(user_id: user.id)
            end
          else
            tip_exception(-1, interactor.result[:message])
          end
        else
          user.update!(phone: phone) if user.phone.blank? && phone.present? && User.find_by(phone: phone).blank?
          user.update!(nickname: nickname) if user.nickname.blank? && nickname.present?
        end
        successful_authentication(user)
      else
        Rails.logger.error("#############api_url:#{api_user_url},code: #{user_params['rsltcode']}, msg: #{user_params['rsltcode']}")
      end
    end
  end

  def get_509_sso_token
    app_id = EduSetting.get("509_APP_ID")
    app_secret = EduSetting.get("509_APP_SECRET")
    app_domain = EduSetting.get("509_APP_DOMAIN")
    api_token_url ="#{app_domain}/api/uaa/oauth/token?client_id=#{app_id}&client_secret=#{app_secret}&grant_type=client_credentials"
    # api_token_url ="#{app_domain}/oauth/token?client_id=#{app_id}&client_secret=#{app_secret}&grant_type=client_credentials"
    access_token = Rails.cache.read("509_APP/access_token")
    if access_token.present?
      api_check_token_url = "#{app_domain}/api/sso/valtoken/#{access_token}"
      # api_check_token_url = "#{app_domain}/api/sso/user?access_token=#{access_token}"
      result = url_http_post(api_check_token_url, {})
      if result['rsltcode'].to_s != "0"
        data = url_http_post(api_token_url, {})
        access_token = data['access_token']
        Rails.cache.write("509_APP/access_token", access_token, expires_in: 5.days)
      end
    else
      data = url_http_post(api_token_url, {})
      access_token = data['access_token']
      Rails.cache.write("509_APP/access_token", access_token, expires_in: 5.days)
    end
    access_token
  end

  def url_http_post(api_url,params)
    Rails.logger.info "api_url==#{api_url}"
    uri = URI.parse(api_url)
    http = Net::HTTP.new uri.host, uri.port
    http.open_timeout = 60
    http.read_timeout = 60
    if uri.scheme == 'https'
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    begin
      request = Net::HTTP::Post.new(uri)
      request.set_form_data(params) if params.present?
      request['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
      response = http.start { |http| http.request(request) }
      Rails.logger.info "api response.body==#{response.body}"
      JSON.parse response.body
    rescue =>err
      Rails.logger.error("#############api_url:#{api_url},error:#{err.message.size}")
      # Rails.logger.error("#############api_url:#{api_url},error:#{err.message}")
      return {}
    end
  end
end
