# == 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
  belongs_to :user

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

  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
  #
  def members_to_string
    return [] if members.blank?
    str = []
    members.each do |m|
      str.push("#{m["real_name"]} #{m["org_name"]} #{m["org_job"]} #{m["org_rank"]}")
    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"] : "系统打分错误，信息不详"
  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
end
