class CompetitionInfosController < ApplicationController
  include ApplicationHelper
  before_action :find_competition, only: [:show, :edit, :update, :update_zone_or_sub, :enroll, :upload, :enroll_status,
                                          :statistics, :enroll_list, :ranking_list, :enroll_update, :enroll_status_update,
                                          :upload_enroll_template, :enroll_template, :online_switch]
  before_action :require_admin, only: [:new, :edit, :create]
  before_action :check_competition_manager, only: [:update, :enroll_status_update]

  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 = 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 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

  # 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]

    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 @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 enroll_list
    competition_users = CompetitionUser.where(competition_info: @competition_info.id).order("updated_at desc")
    zones = @competition_info.manager_zones(current_user)
    if @competition_info.identifier == "qz2022"
      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
    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
    if params[:status].present?
      competition_users = competition_users.where(status: params[:status])
    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")
    end
    @competition_users_count = competition_users.count
    competition_users = competition_users.select("DISTINCT competition_users.*")
    @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])
        @table_columns = @competition_info.enroll_fields.keys
        @table_columns = @table_columns + %w(作品下载链接) if params[:upload].to_s == "true"
        @export_infos = []
        @export_infos_new = []
        max_members = []
        competition_users.each do |u|
          info_array = []
          @competition_info.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 + members
            else
              info_array.push("#{u.send("#{val}")}")
            end
          end
          if params[:upload].to_s == "true"
            info_array = info_array + [u.attachments.blank? ? "" : "#{EduSetting.get('host_name')}/#{download_url(u.attachments.first)}"]
          end
          @export_infos.push(info_array)
        end
        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 = @competition_info.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
        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"
        render xlsx: "#{export_name.strip}", template: "competition_infos/enroll_list.xlsx.axlsx", locals: { table_columns: @table_columns, export_infos: @export_infos_new }
      }
      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")
        send_file service.zip, filename: service.filename, type: 'application/zip'
      }
    end
  end

  def enroll_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.enroll_template_id 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::ZipEnrollTemplateService.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)
    competition_user.update_attributes!(status: 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
    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
    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 enroll_status
    @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)
  end

  def upload
    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)
    api_score_control = LimitForbidControl::CompetitionApiScore.new(competition_user.id)
    return normal_status(-1, "今日打分已达上限，请明日再试") if api_score_control.forbid?
    api_score_control.increment!
    # tip_exception "您已经提交作品!" if competition_user.present? && competition_user.attachments.present?
    competition_user.attachments.update_all(container_id: nil, container_type: nil)
    params[:attachment_ids].each do |id|
      attachment = Attachment.find_by_id(id)
      unless attachment.blank?
        attachment.container = competition_user
        attachment.author_id = current_user.id
        attachment.description = ""
        attachment.save
      end
      api_url = "/script/ccks"
      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)
        CompetitionAutoScoreNewJob.perform_later(competition_user.id, api_url, filePath)
      end
    end
    competition_user.update_attributes!(status: 3)
    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::CompetitionApiScore.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
    competition_users = @competition_info.competition_users.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 ", keyword: "%#{params[:keyword].to_s}%")
    end
    @competition_users_count = competition_users.count
    @competition_users = paginate(competition_users)
  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)
  end

  def competition_info_params
    params.require(:competition_info).permit(:title, :zones, :zones_local, :sub_competitions, :identifier, :content,
                                             :video_url, :is_local, :manager_ids, :upload_date, :enroll_date, :guide, :about_us,
                                             :banner_url, :enroll_template, :enroll_columns, :applet_banner_url,:start_at, :sort_no)
  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
end
