# == Schema Information
#
# Table name: competition_infos
#
#  id                :integer          not null, primary key
#  identifier        :string(255)
#  title             :string(255)
#  content           :text(4294967295)
#  video_url         :string(255)
#  manager_ids       :string(255)
#  zones             :string(255)
#  sub_competitions  :string(255)
#  is_local          :boolean          default("0")
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  enroll_date       :datetime
#  upload_date       :datetime
#  zones_local       :string(255)
#  guide             :text(65535)
#  about_us          :text(65535)
#  banner_url        :string(255)
#  enroll_template   :string(255)
#  admin_data        :text(65535)
#  enroll_columns    :text(65535)
#  status            :boolean          default("0")
#  applet_banner_url :string(255)
#  watchers_count    :integer          default("0")
#  start_at          :datetime
#  visits            :integer
#  sort_no           :integer          default("0")
#
# Indexes
#
#  index_competition_infos_on_identifier  (identifier) UNIQUE
#

class CompetitionInfo < ApplicationRecord
  has_many :competition_users
  has_many :watchers, as: :watchable, dependent: :destroy
  has_many :competition_notices, dependent: :destroy
  has_many :journals, as: :journalized, dependent: :destroy

  validates_uniqueness_of :identifier, message: " %{value} 竞赛标识已被使用"

  serialize :admin_data, JSON

  def competition_zones
    self.is_local? ? self.zones_local.to_s.split(",") : self.zones.to_s.split(",")
  end

  def competition_users_count
    self.identifier == "tzb2025" ? self.competition_users.where("competition_users.enroll_template_id is not null").count : self['competition_users_count']
  end

  def competition_subs
    self.sub_competitions.to_s.split(",")
  end

  # 管理员配置方式：id:赛区名称,id:赛区名称
  def manager_zones(user)
    return nil if self.zones.blank?
    return self.competition_zones if user.admin?
    return [] if self.manager_ids.blank? && self.admin_data.blank?
    zones = []
    if self.admin_data.present? && self.admin_data.is_a?(Array)
      # self.admin_data = JSON.parse(self.admin_data)  if self.admin_data.is_a?(String)
      self.admin_data.each do |data|
        zones = zones + data["data"] if data["user_id"].to_s == user.id.to_s
      end
    else
      managers = self.manager_ids.split(",")
      managers.each do |u|
        zones.push(u.split(":")[1]) if u.split(":")[0].to_s == user.id.to_s
      end
    end
    zones
  rescue => err
    Rails.logger.info("admin_data is not json,error:#{err}")
    []
  end

  # 管理员配置方式：id:赛区名称,id:赛区名称
  def is_manager?(user)
    return true if user.admin?
    return false if self.manager_ids.blank? && self.admin_data.blank?
    if self.admin_data.present? && self.admin_data.is_a?(Array)
      # self.admin_data = JSON.parse(self.admin_data) if self.admin_data.is_a?(String)
      self.admin_data.select { |data| data["user_id"].to_s == user.id.to_s }.size > 0
    else
      managers = manager_ids.split(",")
      managers.select { |u| u.split(":")[0].to_s == user.id.to_s }.size > 0
    end
  rescue => err
    Rails.logger.info("admin_data is not json,error:#{err}")
    false
  end

  def enroll_fields
    hash={}
    hash.merge!({ "ID" => "id" })
    hash.merge!({ "用户名" => "user_login" })
    hash.merge!({ "队长姓名" => "leader" })
    hash.merge!({ "队长单位" => "org_name" })
    hash.merge!({ "队长职称" => "org_job" })
    hash.merge!({ "军衔" => "org_rank" }) if self.is_local?
    hash.merge!({ "队长电话" => "phone" })
    hash.merge!({ "赛区" => "zone" })
    hash.merge!({ "赛项" => "sub_competition" })
    hash.merge!({ "课题来源" => "subject_source_from" })
    hash.merge!({ "子赛道" => "sub_item" })
    # hash.merge!({ "参赛作品名称" => "works_name" })
    # hash.merge!({ "参赛作品链接" => "works_url" })
    hash.merge!({ "成员" => "members_to_string" })
    hash.merge!({ "指导老师姓名" => "teacher_name" })
    hash.merge!({ "指导老师单位" => "teacher_dept" })
    hash.merge!({ "指导老师邮箱" => "teacher_email" })
    hash.merge!({ "指导老师电话" => "teacher_phone" })
    hash.merge!({ "指导老师职称" => "teacher_professional" })

    self.enroll_columns.present? && self.enroll_columns.is_a?(String) ? JSON.parse(self.enroll_columns) : hash
  rescue => err
    Rails.logger.info("enroll_columns is not json,error:#{err}")
    hash
  end

end
