# == Schema Information
#
# Table name: competition_users
#
#  id                  :integer          not null, primary key
#  competition_info_id :integer
#  user_id             :integer
#  leader              :string(255)
#  org_name            :string(255)
#  org_job             :string(255)
#  org_rank            :string(255)
#  zone                :string(255)
#  sub_competition     :string(255)
#  subject_source_type :integer
#  subject_source_name :string(255)
#  phone               :string(255)
#  members             :text(65535)
#  created_at          :datetime         not null
#  updated_at          :datetime         not null
#  status              :integer          default("0")
#  enroll_template_id  :integer
#  mail                :string(255)
#  ext1                :string(255)
#  ext2                :string(255)
#  ext3                :string(255)
#  api_status          :integer          default("0")
#  api_result          :text(65535)
#  score               :float(24)        default("0")
#
# Indexes
#
#  index_competition_users_on_competition_info_id  (competition_info_id)
#  index_competition_users_on_user_id              (user_id)
#

class CompetitionUser < ApplicationRecord
  belongs_to :competition_info, counter_cache: true
  belongs_to :user

  has_many :attachments, as: :container, dependent: :destroy
  has_many :competition_user_scores, dependent: :destroy

  validates :user_id, uniqueness: { scope: :competition_info_id}

  # 报名扩展字段应用记录
  # ext5:竞赛阶段
  # ext1:指导老师
  # ext2:申请模板文件
  # ext3:申请模板状态
  # ext4:参赛队伍名称

  serialize :members, JSON

  # %i[real_name org_name org_job org_rank].each do |method_name|
  #   define_method method_name do
  #     members&.[](method_name.to_s)
  #   end
  #
  #   define_method "#{method_name}=" do |value|
  #     self.config ||= {}
  #     members.[]=(method_name.to_s, value)
  #   end
  # end
  #

  scope :with_member_phone, -> (phone) {
    where("members LIKE ?", "%\"phone\":\"#{phone}\"%")
  }

  def members_to_string
    return [] if members.blank?
    str = []
    if members.is_a?(Array)
      members.each do |m|
        str.push("#{m["real_name"]} #{m["org_name"]} #{m["org_job"]} #{m["org_rank"]} #{m["phone"]}")
      end
    else
      m = members
      str.push("#{m["real_name"]} #{m["org_name"]} #{m["org_job"]} #{m["org_rank"]} #{m["phone"]}")
    end
    str
  end

  def subject_source_from
    self.subject_source_type == 0 ? "自主提报" : self.subject_source_name
  end

  def api_result_text
    "" if self.api_status != 3 || self.api_result.blank?
    data = JSON.parse self.api_result
    data["msg"].present? ? data["msg"] : data["errorOutput"].present? ? data["errorOutput"] : "系统打分错误，信息不详"
  rescue =>err
    return nil
  end

  def api_result_data
    {} if self.api_status != 3 || self.api_result.blank?
    data = JSON.parse self.api_result
    data
  rescue =>err
    return {}
  end

  def apply_template_id
    self.ext2
  end

  def apply_status
    self.ext3.to_i
  end

  def last_score
    self.api_status == 2 ? format("%.4f", (self.api_result_data["pass@1"] || self.api_result_data["accuracy"]).to_f).to_f : 0.to_f
  end

  def stage_score(stage)
    competition_user_scores = self.competition_user_scores.where(stage: stage.to_i).order(score: :desc)
    competition_user_scores.blank? ? 0 : competition_user_scores.first.score.to_f
  end

  def stage_last_score(stage)
    competition_user_scores = self.competition_user_scores.where(stage: stage.to_i).order(created_at: :desc)
    competition_user_scores.blank? ? 0 : competition_user_scores.first.score.to_f
  end

  def max_score_json
    competition_user_scores = self.competition_user_scores.where(stage: stage.to_i).order(score: :desc)
    competition_user_scores.blank? ? 0 : competition_user_scores.first.score.to_f
  end

  def stage_api_status(stage)
    competition_user_scores = self.competition_user_scores.where(stage: stage.to_i).order(created_at: :desc)
    competition_user_scores.blank? ? 0 : competition_user_scores.first.api_status
  end

  def stage_api_result_text(stage)
    {} if stage_api_status(stage) != 3
    api_result =  self.competition_user_scores.where(stage: stage.to_i).order(created_at: :desc).first&.api_result
    {} if api_result.blank?
    data = JSON.parse api_result
    data["msg"].present? ? data["msg"] : data["errorOutput"].present? ? data["errorOutput"] : "系统打分错误，信息不详"
  rescue =>err
    return {}
  end

  def stage_max_score_data(stage)
    api_result =  self.competition_user_scores.where(stage: stage.to_i).order(score: :desc).first&.api_result
    {} if api_result.blank?
    api_result["data"]
  rescue =>err
    return {}
  end

  def user_login
    self.user&.login.to_s
  end

  def attachment_names
    names  = []
    self.attachments.each do |att|
      names.push att.filename
    end
    names.join("\r\n")
  end

  def attachment_files
    names  = []
    self.attachments.each do |att|
      names.push "#{EduSetting.get('host_name')}/#{download_url(att)}"
    end
    names.join("\r\n")
  end

  def download_url(attachment)
    attachment&.uuid.present? ? "api/attachments/#{attachment.uuid}" : "api/attachments/#{attachment.id}"
  end

  def works_name
    if self['works_name'].present?
      self['works_name']
    else
      self.attachment_names
    end
  end

  def works_url
    if self['works_url'].present?
      self['works_url']
    else
      self.attachment_files
    end
  end

end
