class SyncCompetitionTzbUserJob < ApplicationJob
  queue_as :default

  def perform(code=nil)
    url = EduSetting.get("SyncCompetitionTzbUserUrl") || "https://2025.tiaozhanbei.net/api/v1/ai_contest/3579510184/project_list/"
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.hostname, uri.port)
    if uri.scheme == 'https'
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    response = http.send_request('GET', uri.path, nil, {'Content-Type' => 'application/json','Authorization' => 'Bearer sk-CQ5oe9UI14nlwYnMtsNV4MBMDLwQ67bQXIa2fDy5m0bSQ5Ts'})
    # Rails.logger.info("SyncCompetitionTzbUserJob body===#{response.body}")
    result = JSON.parse(response.body)
#     data = '{"Code":"Ok","Message":"成功","Data":[{"corp_id":123456,"match_id":666,"user_uid":"uid_y0gqNR3EesqZVgA",
# "project_pid":"pid_123001","activation_code":"V2nyoEYzl2zRaVySpldc","project_status":"not_finished",
# "project_status_text":"未提交","status_level":"school","status_level_text":"校级","school_code":"10003",
# "school_name":"清华大学","province_name":"北京"},{"corp_id":123456,"match_id":666,"user_uid":"uid_JHnTBdt8GA3tziq","project_pid":"pid_123002","activation_code":"nde8u5HNQ7qqXjkBIQG0","project_status":"submit_to","project_status_text":"已提交","status_level":"school","status_level_text":"校级","school_code":"10003","school_name":"清华大学","province_name":"北京"},{"corp_id":123456,"match_id":666,"user_uid":"uid_2tCNcoKX8T8oHvk","project_pid":"pid_123003","activation_code":"iZQCh3mfuJ8ESrUPwGRo","project_status":"pass_by","project_status_text":"审核通过","status_level":"school","status_level_text":"校级","school_code":"10001","school_name":"北京大学","province_name":"北京"},{"corp_id":123456,"match_id":666,"user_uid":"uid_DziaXaNTkyS1M05","project_pid":"pid_123004","activation_code":"c42BKyehYWAxeAqjLdc8","project_status":"not_pass_by","project_status_text":"审核未通过","status_level":"province","status_level_text":"省级","school_code":"10001","school_name":"北京大学","province_name":"北京"}]}'
#     result = JSON.parse(data)
    Rails.logger.info("SyncCompetitionTzbUserJob size===#{result["Data"].size}")
    result["Data"].each  do |row|
      tzb_user = CompetitionTzbUser.find_by(user_uid: row["user_uid"])
      if tzb_user.blank?
        tzb_user = CompetitionTzbUser.new
        tzb_user.user_uid = row["user_uid"]
        tzb_user.user_email = row["user_email"]
        tzb_user.activation_code = row["activation_code"]
        tzb_user.info_json = row.to_json
        tzb_user.save
      end
      if tzb_user.present? && tzb_user.user_id.blank?
        password = generate_user_login('')
        user_id = register_user(tzb_user, password)
        tzb_user.update_attributes!(user_id: user_id, pwd: password)
      end
    end
  end


  def register_user(tzb_user, pwd)
    user = User.find_by(mail: tzb_user.user_email)
    return user.id if user.present?
    username = generate_user_login('p')
    email = tzb_user.user_email
    email = "#{username}@example.org" if email.blank?
    company_name = tzb_user.user_info("school_name")
    user_type = company_name.present? && company_name.include?("大学") ? 4 : 6
    password = pwd
    user = User.new(login: username, mail: email, password: password, type: 'User', company_name: company_name)
    interactor = Gitea::RegisterInteractor.call({ username: username, email: email, password: password })
    gitea_user = interactor.result
    result = Gitea::User::GenerateTokenService.call(username, password)
    user.gitea_token = result['sha1']
    user.gitea_uid = gitea_user[:body]['id']
    user.user_type = user_type
    user.save!
    UserExtension.create!(user_id: user.id)
    user.id
  end


  # 生成邀请码
  def generate_user_login type
    code = %W(0 1 2 3 4 5 6 7 8 9).sample(8).join
    code = type + code.to_s
    return generate_user_login(type) if User.where(login: code).present?
    code
  end
end