class CompetitionInfosController < ApplicationController
  include ApplicationHelper
  before_action :find_competition, only: [:show, :edit, :update, :update_zone_or_sub, :enroll, :upload, :enroll_status,
                                          :statistics, :import, :import_template, :enroll_list, :ranking_list, :enroll_update, :enroll_status_update, :apply_status_update,
                                          :upload_enroll_template, :upload_apply_template, :enroll_template, :apply_template, :online_switch, :destroy, :update_expert_audit]
  before_action :require_admin, only: [:new, :edit, :create, :destroy]
  before_action :check_competition_manager, only: [:update, :enroll_status_update, :online_switch, :enroll_template]
  before_action :check_competition_manager_and_expert, only: [:enroll_list]
  before_action :require_login, only: [:enroll, :enroll_update, :enroll_status_update, :upload, :upload_enroll_template, :update_expert_audit]

  skip_before_action :verify_authenticity_token, :only => [:update_expert_audit]


  def index
    competition_infos = CompetitionInfo.order(sort_no: :desc)
    competition_infos = competition_infos.where("competition_infos.title like ?", "%#{params[:name]}%") if params[:name].present?
    competition_infos = competition_infos.joins(:watchers).where(watchers: { user_id: current_user.id }) if params[:category].to_s == "watched"
    competition_infos = competition_infos.joins(:competition_users).where(competition_users: { user_id: current_user.id }).or(competition_infos.joins(:competition_users).merge(CompetitionUser.with_member_phone(current_user.phone))) if params[:category].to_s == "joined"
    competition_infos = competition_infos.where(status: ActiveModel::Type::Boolean.new.cast(params[:status])) if ActiveModel::Type::Boolean.new.cast(params[:status]).present?
    if params[:is_expert_audit].present?
      competition_infos = competition_infos.where(:is_expert_audit => params[:is_expert_audit].to_s == "true")
    end
    @competition_infos = paginate(competition_infos)
    respond_to do |format|
      format.html
      format.json { render_ok(data: @competition_infos.as_json, count: competition_infos.count) }
    end
  end

  def list
    @competition_infos = CompetitionInfo.order(sort_no: :desc)
    @competition_infos = @competition_infos.where(id: params[:ids].to_s.split(",")) if params[:ids].present?
  end

  def recommend
    sort_direction = ["asc", "desc"].include?(params[:sort_direction].to_s) ? params[:sort_direction] : "desc"
    sort_by = params[:sort_by] || "created_at"
    competition_infos = CompetitionInfo.where(status: true)
    competition_infos = competition_infos.where("title like ?", "%#{params[:name]}%") if params[:name].present?
    @total_count = competition_infos.count
    if sort_by.to_s == "hot"
      competition_infos = competition_infos.select("competition_infos.*, (SELECT count(1) from competition_users where competition_users.competition_info_id = competition_infos.id ) as count").order("count #{sort_direction}")
    elsif sort_by.to_s == "new"
      sort_by = "created_at"
      competition_infos = competition_infos.order("#{sort_by} #{params[:sort_direction]}")
    else
      competition_infos = competition_infos.order("#{sort_by} #{params[:sort_direction]}")
    end
    @competition_infos = paginate(competition_infos)
    render_ok(data: @competition_infos.as_json, count: @total_count)
  end

  def update_expert_audit
    @competition_info.update_attributes(:is_expert_audit => params[:is_expert_audit].to_s == "true")
    render_ok
  end

  # GET /competition_infos/new
  def new
    @competition_info = CompetitionInfo.new
  end

  # GET /competition_infos/1/edit
  def edit
    respond_to do |format|
      format.html
      format.json { render_ok(data: @competition_info.as_json) }
    end
  end

  # POST /competition_infos.json
  def create
    @competition_info = CompetitionInfo.new(competition_info_params)
    @competition_info.admin_data = params[:admin_data] if params[:admin_data].present?

    respond_to do |format|
      if @competition_info.save
        format.html { redirect_to competition_infos_path, notice: '创建成功.' }
        format.json { render_ok(data: @competition_info.as_json) }
      else
        format.html { render :new }
        format.json { render json: @competition_info.errors, status: -1 }
      end
    end
  end

  # PATCH/PUT /competition_infos/1.json
  def update
    # @competition_info = CompetitionInfo.find params[:id]
    respond_to do |format|
      @competition_info.admin_data = params[:admin_data] if params[:admin_data].present?
      if @competition_info.update!(competition_info_params)
        format.html { redirect_to competition_infos_path, notice: '更新成功.' }
        format.json { render_ok(data: @competition_info.as_json) }
      else
        format.html { render :edit }
        format.json { render json: @competition_info.errors, status: -1 }
      end
    end
  end

  def online_switch
    if @competition_info.status
      @competition_info.update_attributes!(status: false)
    else
      @competition_info.update_attributes!(status: true)
    end
    render_ok
  end

  def update_zone_or_sub
    tip_exception "参数错误" if params[:new].blank? || params[:old].blank? || params[:type].blank?
    if params[:type].to_s == "zone"
      competition_users = CompetitionUser.where(competition_info: @competition_info.id).where(zone: params[:old].to_s)
      competition_users.update_all(zone: params[:new].to_s)
    elsif params[:type].to_s == "sub"
      competition_users = CompetitionUser.where(competition_info: @competition_info.id).where(sub_competition: params[:old].to_s)
      competition_users.update_all(sub_competition: params[:new].to_s)
    end
    render_ok
  end

  def import 
    return render_error('请上传正确的文件') if params[:file].blank? || !params[:file].is_a?(ActionDispatch::Http::UploadedFile)
    ActiveRecord::Base.transaction do 
      doc = SimpleXlsxReader.open(params[:file].tempfile)
      enroll_fields = @competition_info.enroll_fields.stringify_keys.except("ID")
      # 获取第一张工作表的第一行作为列名
      sheet = doc.sheets.first
      column_names = sheet.rows.first

      success_count = 0
      failed_count = 0
      sheet.rows[1..-1].each do |row|
        send_data = {}
        enroll_fields.each do |key, value|
          target_index = column_names.index(key)
          next if target_index.nil?
          send_data[value] = row[target_index] 
        end
        members_keys = column_names - enroll_fields.keys - ["*用户标识"]
        if EduSetting.get("is_local") == "true"
          members_keys = members_keys.each_slice(3).to_a
        else 
          members_keys = members_keys.each_slice(5).to_a
        end
        member_array = []
        members_keys.each do |ma|
          member = {}
          ma.each_with_index do |i, index|
            if index == 0 
              key_name = "key"
              member[key_name] = index   
            else
              key_name = "real_name" if i.end_with?("姓名")
              key_name = "org_name" if i.end_with?("单位")
              key_name = "phone" if i.end_with?("手机号")
              key_name = "zw" if i.end_with?("职务")
              key_name = "jx"  if i.end_with?("jx")
              member[key_name] = row[column_names.index(i)]
            end
          end
          member_array << member
        end
        send_data["members"] = member_array
        login_index = column_names.index("*用户标识")
        user = User.find_by(login:row[login_index]) || User.find_by(phone: send_data['phone'])
        if user.present?
          begin
            cu = @competition_info.competition_users.new(user_id: user.id)
            cu.attributes = send_data
            cu.save!
            success_count += 1
          rescue => e
            failed_count += 1
          end
        else
          failed_count += 1
        end
      end
      render_ok({success_count: success_count, failed_count: failed_count})
    end
  rescue => e
    render_error("读取Excel文件失败: #{e.message}")
  end

  def import_template 
   
    respond_to do |format|
      format.json
      format.xlsx {
          set_export_cookies
          enroll_fields = @competition_info.enroll_fields.except("ID")
          @table_columns = ["*用户标识"] | enroll_fields.keys
          if EduSetting.get("is_local") == "true"
            @table_columns = @table_columns + ["*成员姓名", "*成员单位", "*成员手机号"]  
          else
            @table_columns = @table_columns + ["*成员姓名", "*成员单位", "*成员手机号", "*职务", "*jx"]
          end
          render xlsx: "竞赛报名导入模板", template: "competition_infos/import_template.xlsx.axlsx", locals: { table_columns: @table_columns }
      }
    end
  end

  def enroll_list
    @stage = params[:stage] || params[:ext5]
    # 后续统一按默认1阶段开赛，先过渡兼容以前竞赛
    if @competition_info.identifier.to_s == "zstp2025" && @stage.blank?
      @stage = 1
    elsif @competition_info.identifier.to_s == "2025nlts" && @stage.blank?
      @stage = 1
    end
    competition_users = CompetitionUser.where(competition_info: @competition_info.id).order("updated_at desc")
    zones = @competition_info.manager_zones(current_user)
    if params[:zone].present?
      competition_users = zones.include?(params[:zone].to_s) ? competition_users.where(zone: params[:zone].to_s) : competition_users.where(zone: [])
    else
      competition_users = current_user.admin? ? competition_users : competition_users.where(zone: zones)
    end
    competition_users = competition_users.where(sub_competition: params[:sub_competition].to_s) if params[:sub_competition].present?
    if params[:keyword].present?
      if ["tzb2025"].include?(@competition_info.identifier)
        if params[:apply_status].present?
          competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.phone LIKE :keyword", keyword: "%#{params[:keyword].to_s}%")
        else
          competition_users = competition_users.where("competition_users.ext4 LIKE :keyword OR competition_users.ext5 LIKE :keyword ", keyword: "%#{params[:keyword].to_s}%")
        end
      else
        competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.phone LIKE :keyword", keyword: "%#{params[:keyword].to_s}%")
      end
    end
    if params[:status].present?
      competition_users = competition_users.where(status: params[:status].to_s.split(","))
    end
    if params[:apply_status].present?
      competition_users = competition_users.where(ext3: params[:apply_status].to_s.split(","))
    else
      if ["yys2025", "tzb2025"].include?(@competition_info.identifier)
        if params[:type]=="un_file"
          competition_users = competition_users.where("leader is not null and phone is not null and org_name is not null")
        else
          competition_users = competition_users.where("competition_users.enroll_template_id is not null")
        end
      end
    end
    if params[:upload].to_s == "true"
      # competition_users = competition_users.joins("join attachments on attachments.container_type='CompetitionUser' and attachments.container_id = competition_users.id")
      competition_users = competition_users.where(status: 3)
    end
    if params[:sub_item].present?
      competition_users = competition_users.where(sub_item: params[:sub_item])
    end
    competition_users = competition_users.where(id: params[:included_ids].to_s.split(",")) if params[:included_ids].present?
    competition_users = competition_users.where.not(id: params[:excluded_ids].to_s.split(",")) if params[:excluded_ids].present?

    @competition_users_count = competition_users.count
    competition_users = competition_users.select("DISTINCT competition_users.*")
    if params[:sort_by].present? && params[:sort_direction].present?
      sort_by = CompetitionUser.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'updated_at'
      sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
      competition_users = competition_users.reorder("#{sort_by} #{sort_direction}")
    end
    @competition_users = paginate(competition_users)
    respond_to do |format|
      format.json
      # 导出功能
      format.xlsx {
        set_export_cookies
        competition_users = params[:upload].to_s == "true" ? competition_users.where(status: [2, 3]) : competition_users.where(status: [1, 2, 3])
        enroll_fields = @competition_info.enroll_fields
        enroll_fields = enroll_fields.delete_if { |key, value| ["sub_item", "works_name", "works_url"].include?(value) } if params[:upload].to_s != "true"
        @table_columns = ["序号"] | enroll_fields.keys
        # @table_columns = @table_columns + %w(参赛报名表下载链接)
        @table_columns = @table_columns + %w(作品下载链接) if params[:upload].to_s == "true" && !enroll_fields.values.include?("works_url")
        @table_columns = @table_columns + %w(申请表下载链接) if params[:apply_status].present?
        @table_columns = @table_columns + %w(bm审查下载链接) if @competition_info.identifier == "KXSYSJ-2024" && params[:upload].to_s == "true"
        # 重排成员放最后
        enroll_fields_values = enroll_fields.values - ["members_to_string"] + ["members_to_string"]
        @export_infos = []
        @export_infos_new = []
        @only_files = []
        max_members = []
        file_count=0
        competition_users.each_with_index do |u, index|
          info_array = []
          info_array.push(index + 1)
          file_array = []
          # file = Attachment.where_id_or_uuid(u.enroll_template_id).first
          # file_array = file_array + [file.blank? ? "" : "#{EduSetting.get('host_name')}/#{download_url(file)}"]
          if params[:upload].to_s == "true" && !enroll_fields.values.include?("works_url")
            # file_array = file_array + [u.attachments.blank? ? "" : "#{EduSetting.get('host_name')}/#{download_url(u.attachments.first)}"]
            file_array = file_array + [u.attachment_files]
          end
          if params[:only_files].to_s == "true"
            u.attachments.each do |attach|
              file_count += 1
              @only_files.push(["作品#{file_count}", attach.filename])
            end
          end
          if params[:apply_status].present?
            file = Attachment.where_id_or_uuid(u.ext2).first
            file_array = file_array + [file.blank? ? "" : "#{EduSetting.get('host_name')}/#{download_url(file)}"]
          end
          if @competition_info.identifier == "KXSYSJ-2024" && params[:upload].to_s == "true"
            file = Attachment.where_id_or_uuid(u.bm_file_id).first
            file_array = file_array + [file.blank? ? "" : "#{EduSetting.get('host_name')}/#{download_url(file)}"]
          end
          enroll_fields_values.each do |val|
            if "members_to_string" == val.to_s
              members = u.send("#{val}")
              max_members.push(members.size)
              info_array = info_array + file_array + members
            else
              info_array.push("#{u.send("#{val}")}")
            end
          end
          @export_infos.push(info_array)
        end
        Rails.logger.info("######_______________1111########@export_infos: #{@export_infos}")
        if max_members.present? && max_members.max > 1
          max_members.max.times do |n|
            @table_columns = @table_columns - ["成员"]
            @table_columns.push("成员#{n + 1}")
          end
          total_col = enroll_fields.values.size + max_members.max.to_i
          @export_infos.each do |info|
            blank_str = []
            (total_col - 1 - info.size).times do
              blank_str.push("")
            end
            @export_infos_new.push(info + blank_str)
          end
        else
          @table_columns =  @table_columns - ["成员"] + ["成员"]
          @export_infos_new = @export_infos
        end
        export_name = "竞赛报名列表_#{Time.now.strftime('%Y%m%d_%H%M%S')}"
        export_name = "竞赛作品列表_#{Time.now.strftime('%Y%m%d_%H%M%S')}" if params[:upload].to_s == "true"
        Rails.logger.info("######_______________########export_infos_new: #{@export_infos_new}")
        if params[:only_files].to_s == "true"
          render xlsx: "作品清单_#{Time.now.strftime('%Y%m%d_%H%M%S')}", template: "competition_infos/enroll_list.xlsx.axlsx", locals: { table_columns: ["序号","作品名称"], export_infos: @only_files }
        else
          render xlsx: "#{export_name.strip}", template: "competition_infos/enroll_list.xlsx.axlsx", locals: { table_columns: @table_columns, export_infos: @export_infos_new }
        end
      }
      format.zip {
        competition_users = params[:upload].to_s == "true" ? competition_users.where(status: [2, 3]) : competition_users.where(status: [1, 2, 3])
        Rails.logger.info("######_______________########competition_users.size: #{competition_users.size}")
        service = Competition::ZipWorkFileService.new(competition_users, "files", params[:file_index])
        send_file service.zip, filename: service.filename, type: 'application/zip'
      }
    end
  end

  def enroll_template
    file_attr_name = params[:file].to_s == "bm_file_id" ? params[:file].to_s : "enroll_template_id"
    competition_users = CompetitionUser.where(competition_info: @competition_info.id).order("updated_at desc")
    competition_users = competition_users.where(status: [1, 2, 3])
    competition_users = competition_users.where("competition_users.enroll_template_id is not null") if file_attr_name.to_s == "enroll_template_id"
    competition_users = competition_users.where("competition_users.bm_file_id is not null") if file_attr_name.to_s == "bm_file_id"
    zones = @competition_info.manager_zones(current_user)
    if params[:zone].present?
      competition_users = zones.include?(params[:zone].to_s) ? competition_users.where(zone: params[:zone].to_s) : competition_users.where(zone: [])
    else
      competition_users = current_user.admin? ? competition_users : competition_users.where(zone: zones)
    end
    if params[:sub_competition].present?
      competition_users = competition_users.where(sub_competition: params[:sub_competition].to_s)
    end
    if params[:keyword].present?
      competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.phone LIKE :keyword", keyword: "%#{params[:keyword].to_s}%")
    end
    respond_to do |format|
      format.json
      format.zip {
        Rails.logger.info("######_______________########competition_users.size: #{competition_users.size}")
        service = Competition::ZipEnrollTemplateService.new(competition_users, "files", file_attr_name)
        send_file service.zip, filename: service.filename, type: 'application/zip'
      }
    end
  end

  def apply_template
    competition_users = CompetitionUser.where(competition_info: @competition_info.id).order("updated_at desc")
    competition_users = competition_users.where(status: [1, 2, 3]).where("competition_users.ext2 is not null")
    zones = @competition_info.manager_zones(current_user)
    if params[:zone].present?
      competition_users = zones.include?(params[:zone].to_s) ? competition_users.where(zone: params[:zone].to_s) : competition_users.where(zone: [])
    else
      competition_users = current_user.admin? ? competition_users : competition_users.where(zone: zones)
    end
    if params[:sub_competition].present?
      competition_users = competition_users.where(sub_competition: params[:sub_competition].to_s)
    end
    if params[:keyword].present?
      competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.phone LIKE :keyword", keyword: "%#{params[:keyword].to_s}%")
    end
    respond_to do |format|
      format.json
      format.zip {
        Rails.logger.info("######_______________########competition_users.size: #{competition_users.size}")
        service = Competition::ZipApplyTemplateService.new(competition_users, "files")
        send_file service.zip, filename: service.filename, type: 'application/zip'
      }
    end
  end

  def show
    @competition_info.increment!(:visits)
  end

  def enroll_status_update
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: params[:user_id])
    tip_exception "未找到该报名用户" if competition_user.blank?
    tip_exception "状态参数错误" unless ['0', '1', '2'].include?(params[:status].to_s)
    old_status = competition_user.status
    stage = competition_user.ext5
    # 作品驳回时得分清0
    if old_status.to_i == 3 && params[:status].to_i ==2
      competition_user.competition_user_scores.where(stage: stage.to_i).update_all(score: 0, last_score: 0)
      competition_user.update_attributes!(score: 0)
      cache_key = "limit_forbid_control:#{@competition_info.identifier}:competition_api_score:#{competition_user.id}-#{stage}"
      Rails.cache.delete(cache_key)
      api_score_control = LimitForbidControl::CompetitionApiScoreNew.new(competition_user.id)
      api_score_control.clear
    end
    competition_user.update_attributes!(status: params[:status].to_i)
    render_ok
  end

  def apply_status_update
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: params[:user_id])
    tip_exception "未找到该报名用户" if competition_user.blank?
    tip_exception "状态参数错误" unless ['0', '1', '2'].include?(params[:status].to_s)
    competition_user.update_attributes!(ext3: params[:status].to_i)
    render_ok
  end

  def enroll
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    tip_exception "您已经报名!" if competition_user.present?
    competition_user = CompetitionUser.new(enroll_params)
    competition_user.competition_info = @competition_info
    competition_user.user = current_user
    competition_user.members = params[:members]
    competition_user.status = 1 if competition_user.status.to_i == 0
    competition_user.status = 2 if @competition_info.identifier.include?("qz202")
    # competition_user.status = 2 if @competition_info.identifier.include?("tzb2025")
    if @competition_info.identifier.to_s.downcase.include?("kxsysj-2024-2")
      if CompetitionUser.where(competition_info: @competition_info.id).where(ext1: competition_user.ext1).present?
        tip_exception "一个作品复赛序号只能一个队伍使用，如有作品复赛序号被冒用，咨询大赛组委会进行删除或其他操作。"
      end
      competition_user.status = 2
    end
    if @competition_info.identifier.to_s.downcase.include?("tzb2025")
      if CompetitionUser.where(competition_info: @competition_info.id).where(status: [1, 2, 3])
                        .where(ext4: competition_user.ext4).where(ext5: competition_user.ext5).present?
        tip_exception "该参赛团队报名表已提交，无法再次提交。"
      end
    end
    competition_user.save
    render_ok
  end

  def enroll_update
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    tip_exception "未报名，请先报名" if competition_user.blank?
    competition_user.update_attributes!(enroll_params)
    competition_user.members = params[:members]
    competition_user.status = 1 if competition_user.status.to_i == 0
    competition_user.status = 2 if @competition_info.identifier.include?("qz202")
    # competition_user.status = 2 if @competition_info.identifier.include?("tzb2025")
    if @competition_info.identifier.to_s.downcase.include?("kxsysj-2024-2")
      if CompetitionUser.where(competition_info: @competition_info.id).where(ext1: competition_user.ext1)
                        .where(status: [2,3]).where.not(id: competition_user.id).present?
        tip_exception "一个作品复赛序号只能一个队伍使用，如有作品复赛序号被冒用，咨询大赛组委会进行删除或其他操作。"
      end
      competition_user.status = 2
    end
    if @competition_info.identifier.to_s.downcase.include?("tzb2025")
      if CompetitionUser.where(competition_info: @competition_info.id)
                        .where(ext4: competition_user.ext4).where(ext5: competition_user.ext5)
                        .where(status: [1, 2, 3]).where.not(id: competition_user.id).present?
        tip_exception "该参赛团队报名表已提交，无法再次提交。"
      end
    end
    competition_user.save
    render_ok
  end

  def upload_enroll_template
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    tip_exception "未报名，请先报名" if competition_user.blank?
    tip_exception "附件参数enroll_template_id不能为空" if params[:enroll_template_id].blank?
    competition_user.update_attributes!(enroll_template_id: params[:enroll_template_id])
    render_ok
  end

  def upload_apply_template
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    # tip_exception "未报名，请先报名" if competition_user.blank?
    if competition_user.blank? && ["yys2025", "tzb2025"].include?(@competition_info.identifier)
      competition_user = CompetitionUser.new
      competition_user.competition_info = @competition_info
      competition_user.user = current_user
      competition_user.status = 2
      competition_user.save
    else
      tip_exception "未报名，请先报名" unless competition_user.present?
    end
    tip_exception "附件参数apply_template_id不能为空" if params[:apply_template_id].blank?
    competition_user.update_attributes!(ext2: params[:apply_template_id], ext3: 1)
    render_ok
  end

  def enroll_status
    @stage = params[:stage] || params[:ext5]
    # 后续统一按默认1阶段开赛，先过渡兼容以前竞赛
    if @competition_info.identifier.to_s == "zstp2025" && @stage.blank?
      @stage = 1
    elsif @competition_info.identifier.to_s == "2025nlts" && @stage.blank?
      @stage = 1
    end
    @competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    # first_round_ids = CompetitionUser.where(competition_info_id: @competition_info.id).where("score > 26").pluck(:id)
    # 第一轮赛合格人员
    first_round_ids = [541, 543, 544, 545, 546, 548, 550, 551, 552, 554, 555, 556, 558, 560, 563, 565, 567, 576, 579, 581]
    @second_round = first_round_ids.include?(@competition_user&.id)
    if  @competition_info.identifier.to_s == "dmsc" || @competition_info.identifier.to_s == "zswd"
      cache_key = "limit_forbid_control:#{@competition_info.identifier}:competition_api_score:#{@competition_user&.id}-#{@stage}"
      @count_control = Rails.cache.read(cache_key)
    else
      api_score_control = LimitForbidControl::CompetitionApiScoreNew.new(@competition_user&.id)
      @count_control = api_score_control.forbid?
    end
  end

  def upload
    @stage = params[:stage] || params[:ext5]
    # 后续统一按默认1阶段开赛，先过渡兼容以前竞赛
    if @competition_info.identifier.to_s == "zstp2025" && @stage.blank?
      @stage = 1
    elsif @competition_info.identifier.to_s == "2025nlts" && @stage.blank?
      @stage = 1
    end
    competition_user = CompetitionUser.find_by(competition_info: @competition_info.id, user_id: current_user.id)
    tip_exception "未报名，请先报名" if competition_user.blank?
    # tip_exception "附件参数attachment_ids不能为空" if params[:attachment_ids].blank?
    # 第一轮赛合格人员
    # first_round_ids = CompetitionUser.where(competition_info_id: @competition_info.id).where("score > 26").pluck(:id)
    first_round_ids = [541, 543, 544, 545, 546, 548, 550, 551, 552, 554, 555, 556, 558, 560, 563, 565, 567, 576, 579, 581]
    tip_exception "您不在复赛名单中，不能参加复赛！" if @competition_info.identifier == "zstp2022" && !first_round_ids.include?(competition_user&.id)
    if  @competition_info.identifier.to_s == "dmsc" || @competition_info.identifier.to_s == "zswd"
      cache_key = "limit_forbid_control:#{@competition_info.identifier}:competition_api_score:#{competition_user.id}-#{@stage}"
      allow_count = 1
      count_control = Rails.cache.read(cache_key)
      if count_control.present? && count_control.to_i >= allow_count
        return normal_status(-1, "打分受限，当前竞赛仅支持3天打一次榜")
      else
        Rails.cache.write(cache_key, count_control.to_i + 1, expires_in: 5.minutes)
      end
    elsif @competition_info.identifier.to_s == "zstp2025"
      return normal_status(-1, "打分已达上限5次") if competition_user.competition_user_scores.where("competition_user_scores.score > 0").count >= 5
    elsif @competition_info.identifier.to_s == "2025nlts"
      api_score_control = LimitForbidControl::CompetitionApiScoreNew.new(competition_user.id, 1, 1)
      return normal_status(-1, "今日打分已达上限，请明日再试") if api_score_control.forbid?
      api_score_control.increment!
    else
      api_score_control = LimitForbidControl::CompetitionApiScore.new(competition_user.id)
      return normal_status(-1, "今日打分已达上限，请明日再试") if api_score_control.forbid?
      api_score_control.increment!
    end
    competition_user.bm_file_id = params[:bm_file_id] if params[:bm_file_id].present?
    # tip_exception "您已经提交作品!" if competition_user.present? && competition_user.attachments.present?
    if params[:attachment_ids].present?
      competition_user.attachments.update_all(container_id: nil, container_type: nil)
      params[:attachment_ids].each do |id|
        attachment = Attachment.where_id_or_uuid(id).first
        unless attachment.blank?
          attachment.container = competition_user
          attachment.author_id = current_user.id
          attachment.description = ""
          attachment.save
        end
        forge_url = Rails.application.config_for(:configuration)['platform_url'] || EduSetting.get("main_site")
        filePath = "#{forge_url}/api/attachments/#{attachment.id}"
        if EduSetting.get("competition_ccks_ids").to_s.split(",").include?(@competition_info.identifier.to_s)
          api_url = "/script/ccks"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath)
        elsif EduSetting.get("competition_zstp2023_ids").to_s.split(",").include?(@competition_info.identifier.to_s)
          api_url = "/script/ccks2023"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath)
        elsif @competition_info.identifier.to_s == "dmsc"
          api_url = "/script/qyCode"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath, @stage)
        elsif @competition_info.identifier.to_s == "zswd"
          api_url = "/script/qyMilitary"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath, @stage)
        elsif @competition_info.identifier.to_s == "mmlss"
          api_url = "/script/mmlssEval"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath, @stage)
        elsif @competition_info.identifier.to_s == "zstp2025"
          api_url = "/script/ccks2025"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath, @stage)
        elsif @competition_info.identifier.to_s == "2025nlts"
          api_url = "/script/cxds2025"
          CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath, @stage)
        end
      end
    end
    competition_user.sub_item = params[:sub_item] if params[:sub_item].present?
    competition_user.works_name = params[:works_name] if params[:works_name].present?
    competition_user.works_url = params[:works_url] if params[:works_url].present?
    if @stage.present?
      competition_user.update_attributes!(api_status: 1, status: 3, ext5: @stage)
    else
      competition_user.update_attributes!(api_status: 1, status: 3)
    end
    render_ok
  end

  # 自动打分接口
  def auto_score
    filePath = params[:filePath].to_s
    team_id = params[:team_id].to_s
    api_url = params[:api_url].to_s
    tip_exception("参数错误") if filePath.blank? || team_id.blank? || api_url.blank?
    competition_team = CompetitionTeam.find team_id
    competition_team.update_attributes!(api_status: 1)
    api_score_control = LimitForbidControl::CompetitionApiScoreNew.new(team_id)
    return normal_status(-1, "今日打分已达上限，请明日再试") if api_score_control.forbid?
    api_score_control.increment!
    CompetitionAutoScoreJob.perform_later(team_id, api_url, filePath)
    render_ok
  end

  # 赛事风采
  def statistics
    @competition_users = @competition_info.competition_users.where(status: [1, 2, 3])
    @upload_count = @competition_users.joins("join attachments on attachments.container_type='CompetitionUser' and attachments.container_id = competition_users.id").count
  end

  # 排名
  def ranking_list
    @stage = params[:stage] || params[:ext5]
    # 后续统一按默认1阶段开赛，先过渡兼容以前竞赛
    if @competition_info.identifier.to_s == "zstp2025" && @stage.blank?
      @stage = 1
    elsif @competition_info.identifier.to_s == "2025nlts" && @stage.blank?
      @stage = 1
    end
    if @stage.present?
      competition_users = @competition_info.competition_users
      if params[:keyword].present?
        competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.ext4 LIKE :keyword ", keyword: "%#{params[:keyword].to_s}%")
      end
      competition_users = competition_users.select("distinct competition_users.*").joins(:competition_user_scores)
                                           .where("competition_users.status = 3")
                                           .where("competition_user_scores.stage = ? ", @stage.to_i)
                                           .where("competition_user_scores.score > 0")
                                           .group("competition_users.id")
                                           .order("max(competition_user_scores.score) desc, competition_user_scores.created_at asc")
      @rank_num = competition_users.pluck("distinct competition_users.id")
      @competition_users_count = @rank_num.size
      @competition_users = paginate(competition_users)
    else
      competition_users = @competition_info.competition_users.where("competition_users.status = 3").where("score > 0").order("score desc, created_at asc")
      @rank_num = competition_users.pluck(:id)
      if params[:keyword].present?
        competition_users = competition_users.where("competition_users.org_name LIKE :keyword OR competition_users.leader LIKE :keyword OR competition_users.ext4 LIKE :keyword ", keyword: "%#{params[:keyword].to_s}%")
      end
      @competition_users_count = competition_users.count
      @competition_users = paginate(competition_users)
    end
  end

  def tzb_actived
    tip_exception "请输入激活码" if params[:code].blank?
    SyncCompetitionTzbUserJob.perform_later("code")
    tzb_user = CompetitionTzbUser.find_by(activation_code: params[:code])
    tip_exception "激活码正在同步确认中，请稍后再试" if tzb_user.blank?
    tip_exception "激活码正在同步确认中，请稍后再试" if tzb_user.user_id.blank?
    user = User.find_by(id: tzb_user.user_id)
    successful_authentication(user)
    tzb_user.update_attributes!(actived: true)
    render_ok({ user: { login: user.login, mail: user.mail, password: tzb_user.pwd } })
  end

  def destroy
    if @competition_info.destroy!
      flash[:success] = '删除成功'
    else
      flash[:danger] = '删除失败'
    end
    redirect_to "api/competition_infos"
  end

  private

  def enroll_params
    params.permit(:org_name, :org_job, :org_rank, :leader, :zone, :sub_competition, :phone,
                  :subject_source_type, :subject_source_name, :enroll_template_id, :mail, :ext1, :ext2, :ext3, :ext4, :ext5,
                  :bm_file_id, :teacher_name, :teacher_dept, :teacher_email, :teacher_phone, :teacher_professional)
  end

  def competition_info_params
    params.require(:competition_info).permit(:title, :zones, :zones_local, :sub_competitions, :identifier, :content, :description, :org_name,
                                             :video_url, :is_local, :manager_ids, :upload_date, :enroll_date, :guide, :about_us,
                                             :banner_url, :enroll_template, :enroll_columns, :applet_banner_url, :start_at,:start_upload_date, :sort_no,
                                             :ext1, :ext2, :ext3, :ext4, :ext5, :ext6, :ext7, :ext8, :is_expert_audit)
  end

  def find_competition
    if CompetitionInfo.where(:identifier => params[:id]).exists?
      @competition_info = CompetitionInfo.where(:identifier => params[:id]).first
    else
      @competition_info = CompetitionInfo.find(params[:id])
    end
  end

  def manager_competition_zones
    if current_user.admin?
      @competition_info.competition_zones
    else
      @competition_info.manager_zones(current_user)
    end
  end

  def check_competition_manager
    unless @competition_info.is_manager?(current_user)
      tip_exception(403, "你没有权限操作!")
    end
  end

  def check_competition_manager_and_expert
    unless @competition_info.is_manager?(current_user) || current_user.is_expert?
      tip_exception(403, "你没有权限操作!")
    end
  end
end
