class Api::V1::GitlinkCompetitionAppliesController < Api::V1::BaseController 

  def create 
    return render_error("请输入正确的竞赛ID") unless params[:competition_id].present? 
    return render_error("请输入正确的队伍ID") unless params[:team_id].present? 
    return render_error("请输入正确的队伍成员信息") unless params[:team_members].is_a?(Array)
    params[:team_members].each do |member| 
      apply = GitlinkCompetitionApply.find_or_create_by(competition_id: params[:competition_id], team_id: params[:team_id], educoder_login: member[:login])
      apply.competition_identifier = params[:competition_identifier]
      apply.team_name = params[:team_name]
      apply.school_name = member[:school_name]
      apply.nickname = member[:nickname]
      apply.identity = member[:identity]
      apply.role = member[:role]
      apply.email = member[:email]
      user_info = get_user_info_by_educoder_login(member[:login])
      apply.phone = user_info["phone"]
      apply.save
    end
    render_ok
  end

  def get_user_info_by_educoder_login(edu_login)
    req_params = { "login" => "#{edu_login}", "private_token" => "hriEn3UwXfJs3PmyXnqQ" }
    api_url=  "https://data.educoder.net"
    client = Faraday.new(url: api_url)
    response = client.public_send("get", "/api/sources/get_user_info_by_login", req_params)
    result = JSON.parse(response.body)

    return nil if result["status"].to_s != "0"

    # login 邮箱 手机号 姓名 学校/单位
    user_info = result["data"]

    return user_info
  end
end