#coding=utf-8
class CompetitionsController < ApplicationController
  before_filter :find_type, :except => [:index, :new_competition, :edit_competition, :md_content, :create_md_content,
                                        :edit_md_content, :update_md_content,
                                        :new_competition_stage, :new_stage_section, :update_competition_stage]
  before_filter :find_inform, :only => [:edit_inform, :update_inform]
  before_filter :require_login, :only => [:enroll_portal]
  skip_before_filter :verify_authenticity_token, :only => [:edit_rule]
  layout 'base_competition'

  include CompetitionsHelper
  include ApplicationHelper
  
  def home
    respond_to do |format|
      format.html { render :layout => "base_edu"}
      format.js
    end
  end

  def show
    @images = @competition.attachments
  end

  def index
    @competitions = Competition.where(:status => 1).reorder("online_time desc")
    respond_to do |format|
      format.html { render :layout => "base_edu"}
      format.js
    end
  end

  def informs
    status = params[:status] || 1
    @informs = Inform.where(:container_type => "Competition", :container_id => @competition.id, :status => status)
  end

  def md_edit

  end

  def new_inform
    @status = params[:status]
    @url = "#{create_inform_competition_path(@competition, :status => @status)}"
    @inform = Inform.new
  end

  def create_inform
    inform = Inform.new(params[:inform])
    inform.container_type = "Competition"
    inform.container_id = @competition.id
    inform.status = params[:status]
    inform.save_attachments(params[:attachments])
    inform.save
    redirect_to informs_competition_url(@competition, :status => params[:status])
  end

  def edit_inform
    @layout_header_show = false
    @url = "#{update_inform_competition_path(@competition, :inform_id => @inform, :status => params[:status])}"
  end

  def update_inform
    @inform.update_attributes(params[:inform])
    @inform.save_attachments(params[:attachments])
    @inform.save
    redirect_to informs_competition_url(@competition, :status => params[:status])
  end

  def md_content
    @md_content_header = true
    @md_content = CompetitionModuleMdContent.find params[:md_content_id]
    @competition = @md_content.competition_module.competition

  end

  def create_md_content
    md_content = CompetitionModuleMdContent.find params[:md_content_id]
    md_content.update_attributes(params[:md_content])
    md_content.save_attachments(params[:attachments])
    redirect_to md_contents_competition_url(:md_content_id => md_content.id)
  end

  def edit_md_content
    @md_content_header = true
    @md_content = CompetitionModuleMdContent.find params[:md_content_id]
    @competition = @md_content.competition_module.competition
    @url = "#{update_md_content_competitions_path(:md_content_id => @md_content.id)}"
  end

  def update_md_content
    md_content = CompetitionModuleMdContent.find params[:md_content_id]
    md_content.update_attributes(params[:md_content])
    md_content.save_attachments(params[:attachments])
    redirect_to md_content_competitions_path(:md_content_id => md_content.id)
  end

  def enroll
    @user = User.current
    if params[:schoolname] && params[:schoolname].strip != ""
      school_ids = School.where("name like '%#{params[:schoolname]}%'").pluck(:id)
      school_ids = school_ids.size == 0 ? "(-1)" : "(" + school_ids.join(",") + ")"
      @teams = @competition.competition_teams.joins("join user_extensions ue on competition_teams.user_id = ue.user_id").where("ue.school_id in #{school_ids}").order("#{CompetitionTeam.table_name}.created_at desc")
    else
      @teams = @competition.competition_teams.includes(:team_members, {user: :user_extensions}).order("#{CompetitionTeam.table_name}.created_at desc")
    end

    @team_count = @teams.count
    @search_teams_count = @teams.count
    @team_members_count = TeamMember.where(:competition_team_id => @teams.pluck(:id)).count

    @is_enroll = CompetitionTeam.where(:id => TeamMember.where(:user_id => @user, :competition_team_id => @competition.competition_teams.map(&:id)).pluck(:competition_team_id)).reorder("created_at desc")
    @show_notice = (@competition.identifier == "gcc-dev-2018" || @competition.identifier == "gcc-annotation-2018") && @competition.competition_teams.where(:user_id => User.current.id, :teacher_id => nil).count > 0
    @teams = paginateHelper @teams, 50
    respond_to do |format|
      format.js
      format.html
    end
  end

  def enroll_portal
    CompetitionList.create(:user_id => User.current.id, :competition_id => @competition)
    redirect_to enroll_competition_path
  end

  def send_message
    stage = @competition.competition_stages.where(:id => params[:stage_id]).first
    section = stage.competition_stage_sections.reorder("start_time asc").first
    if section.present? && section.start_time.present? && section.start_time > Time.now
      User.where(:id => TeamMember.where(:competition_team_id => @competition.competition_teams.pluck(:id)).pluck(:user_id).uniq).each do |user|
        name = @competition.name + "(#{stage.name})"
        begin
          if user.phone.present?
            status = Trustie::Sms.send(mobile: user.phone.to_s, code: '1', send_type:'competition_start', user_name:user.show_name, name:name, result:section.start_time.strftime('%Y-%m-%d %H:%M:%S'))
          end
        rescue => e
          Rails.logger.error "发送验证码出错: #{e}"
        end
      end
      @status = 0
    else
      @status = 1
    end
  end

  def charts
    if (@competition.competition_modules.where(:name => "排行榜").first.present? && !@competition.competition_modules.where(:name => "排行榜").first.hidden) || User.current.admin?
      @max_min_stage = max_min_stage_time @competition
      if params[:stage_id]
        @stage = @competition.competition_stages.where(:id => params[:stage_id]).first
        @type = @stage.name
      elsif @competition.competition_stages.count == 1
        @stage = @competition.competition_stages.first
        @type = "排行榜"
      else
        if @competition.end_time < Time.now
          @type = "总排行榜"
        else
          @max_min_stage.reverse.each do |section|
            if section.competition_stage.name != "模拟赛"
              if section.min_start_time < Time.now
                @stage = section.competition_stage
                @type = @stage.name
                break
              end
            end
          end
        end
      end
      if @competition.identifier == "gcc-annotation-2018"
        @rule_content = @competition.chart_rules.first
      else
        @rule_content = @competition.chart_rules.where(:competition_stage_id => @stage.try(:id)).first
      end
      @records = []
      if @competition.identifier == 'hn'
        if @type == "总排行榜"
          pre_stage = @competition.competition_stages.where(:name => "预赛").first
          final_stage = @competition.competition_stages.where(:name => "决赛").first
          @records = @competition.competition_teams.includes(:user => [:user_extensions => [:school]])
          @records.each do |team|
            # 决赛记录
            f_score = team.competition_scores.where(:competition_stage_id => final_stage.try(:id)).first
            # 预赛记录
            p_score = team.competition_scores.where(:competition_stage_id => pre_stage.try(:id)).first
            team[:s_score] = (f_score.try(:score).to_f * 0.8 + p_score.try(:score).to_f * 0.2).try(:round, 2)
            team[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
          end
        else
          @records = CompetitionTeam.find_by_sql("SELECT teams.*, cs.score AS s_score, cs.cost_time AS s_spend_time FROM competition_teams teams, competition_scores cs WHERE cs.competition_team_id = teams.`id` AND cs.competition_stage_id = '#{@stage.id}'")
        end
        @records = @records.sort do |a, b|
          [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
        end
        current_team = @competition.team_members.where(:user_id => User.current.id).first
        if current_team.present?
          @user_rank = @records.map(&:id).index(current_team.competition_team_id)
          @user_record = @records.select{|team| team.id == current_team.competition_team_id}.first if @user_rank.present?
        end
        @records = @records[0..17]
      elsif @competition.identifier == 'gcc-dev-2018'
        if @type == "预赛" || @type == "决赛"
          if @type == "预赛"
            # 'nyog9r7c','yugrij4n','48flws5g','bfgau7s6','mfv6zrj7','f398leqr','qwaffs2p','ose7482b','y5wh2ofx'
            # 预赛的实训id  第一阶段:1185,1197,1195  第二阶段:1202, 1210, 1207  第三阶段:1254,1255,1243
            shixun1_id = [1185, 1197, 1195]
            shixun2_id = [1202, 1210, 1207]
            shixun3_id = [1254, 1255, 1243]
          elsif @type == "决赛"
            # '92b7vt8x','a7fxenvc','wt2xfzny','xa4m9cng','tng6heyf','am5o73er','9fla2zry','fzp3iu4w','qlsy6xb4'
            # 预赛的实训id  第一阶段:1289,1373,1256  第二阶段:1488, 1453, 1487  第三阶段:1470, 1473, 1408
            shixun1_id = Shixun.where(:identifier => ['92b7vt8x','a7fxenvc','wt2xfzny']).pluck(:id)
            shixun2_id = Shixun.where(:identifier => ['xa4m9cng','tng6heyf','am5o73er']).pluck(:id)
            shixun3_id = Shixun.where(:identifier => ['9fla2zry','fzp3iu4w','qlsy6xb4']).pluck(:id)
          end

          if @competition.competition_scores.where(:competition_stage_id => @stage.id).count == 0
            # 三个阶段的开始时间和结束时间
            s1_time = @stage.competition_stage_sections[0].start_time
            e1_time = @stage.competition_stage_sections[0].end_time
            s2_time = @stage.competition_stage_sections[1].start_time
            e2_time = @stage.competition_stage_sections[1].end_time
            s3_time = @stage.competition_stage_sections[2].start_time
            e3_time = @stage.competition_stage_sections[2].end_time

            @records = @competition.competition_teams.includes(:user => [:user_extensions => [:school]])
            @records.each do |team|
              user_ids = team.team_members.where(:is_teacher => 0).pluck(:user_id)
              # 第一阶段的得分和耗时
              challenges_1 = Challenge.where(:shixun_id => shixun1_id)
              challenge_rate1 = 0.5
              result1 = chart_exp_score_pre user_ids, s1_time, e1_time, challenges_1, challenge_rate1
              score1 = result1[0]
              time1 = result1[1]

              # 第二阶段的得分和耗时
              challenge_rate2 = 1.0
              challenges_2 = Challenge.where(:shixun_id => shixun2_id)
              result2 = chart_exp_score_pre user_ids, s2_time, e2_time, challenges_2, challenge_rate2
              score2 = result2[0]
              time2 = result2[1]


              # 第三阶段的得分和耗时
              challenges_3 = Challenge.where(:shixun_id => shixun3_id)
              result3 = chart_exp_score_third user_ids, s3_time, e3_time, challenges_3
              score3 = result3[0]
              time3 = result3[1]

              team[:s_score] = (score1 + score2 + score3).try(:round, 2)
              team[:s_spend_time] = time1 + time2 + time3

              # 比赛已截止且未有分数纪录 则创建
              if Time.now > e3_time && team.competition_scores.where(:competition_id => @competition.id, :competition_stage_id => @stage.id).count == 0
                CompetitionScore.create(:user_id => team.user_id, :competition_team_id => team.id, :competition_id => @competition.id, :competition_stage_id => @stage.id, :score => team[:s_score], :cost_time => team[:s_spend_time])
              end
            end
          else
            @records = CompetitionTeam.find_by_sql("SELECT teams.*, cs.score AS s_score, cs.cost_time AS s_spend_time FROM competition_teams teams, competition_scores cs WHERE cs.competition_team_id = teams.`id` AND cs.competition_stage_id = '#{@stage.id}'")
          end
        elsif @type == "总排行榜"
          pre_stage = @competition.competition_stages.where(:name => "预赛").first
          final_stage = @competition.competition_stages.where(:name => "决赛").first
          @records = @competition.competition_teams.includes(:user => [:user_extensions => [:school]])
          @records.each do |team|
            # 决赛记录
            f_score = team.competition_scores.where(:competition_stage_id => final_stage.try(:id)).first
            # 预赛记录
            p_score = team.competition_scores.where(:competition_stage_id => pre_stage.try(:id)).first
            team[:s_score] = (f_score.try(:score).to_f * 0.85 + p_score.try(:score).to_f * 0.15).try(:round, 2)
            team[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
          end
        end

        @records = @records.sort do |a, b|
          [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
        end
        current_team_ids = @competition.team_members.where(:user_id => User.current.id).pluck(:competition_team_id).uniq
        @user_ranks = @records.select{|com_team| current_team_ids.include?(com_team.id)}
        @records = @records.select{|record| record[:s_score] > 0}
        @user_ranks.each do |team|
          rank = @records.map(&:id).index(team.id)
          team[:rank] = rank.present? ? (rank+1) : 0
        end
        records_length = 97
        @records = @records[0..records_length]
      elsif @competition.identifier == "gcc-annotation-2018"
        @records = @competition.competition_teams.includes(:user => [:user_extensions => [:school]])
        @records.each do |team|
          team[:s_score] = team.competition_scores.where(:competition_id => @competition.id).first.try(:score).to_f.try(:round, 3)
        end
        @records = @records.sort do |a, b|
          [b[:s_score]] <=> [a[:s_score]]
        end
        current_team_ids = @competition.team_members.where(:user_id => User.current.id).pluck(:competition_team_id).uniq
        @user_ranks = @records.select{|com_team| current_team_ids.include?(com_team.id)}
        @records = @records.select{|record| record[:s_score] > 0}
        @user_ranks.each do |team|
          rank = @records.map(&:id).index(team.id)
          team[:rank] = rank.present? ? (rank+1) : 0
        end
      end
    else
      render_403
    end
  end


  def export_chart_score
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "比赛成绩"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue

    if @competition.identifier == "hn"
      records = User.where(:id => CompetitionScore.where("competition_id = #{@competition.id} and competition_stage_id is not null").map(&:user_id)).includes(:user_extensions => [:school])
      records.each do |user|
        # 决赛记录
        f_score = user.competition_scores.where(:region => 'hn', :score_type => 'f').first
        # 预赛记录
        p_score = user.competition_scores.where(:region => 'hn', :score_type => 'p').first
        user[:p_score] = p_score.try(:score)
        user[:p_time] = p_score.try(:cost_time)
        user[:f_score] = f_score.try(:score)
        user[:f_time] = f_score.try(:cost_time)
        user[:s_score] = (f_score.try(:score).to_f * 0.8 + p_score.try(:score).to_f * 0.2).try(:round, 2)
        user[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
      end
      records = records.sort do |a, b|
        [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
      end

      sheet1.row(0).concat(["序号","姓名","学校","学号","模拟赛得分","模拟赛用时","预赛得分","预赛用时",
                            "决赛得分","决赛用时","总得分","总用时"])
      count_row = 1
      records.each_with_index do |user, index|
        sheet1[count_row,0] = index + 1
        sheet1[count_row,1] = user.show_real_name
        sheet1[count_row,2] = user.school_name
        sheet1[count_row,3] = user.user_extensions.try(:student_id)
        sheet1[count_row,4] = user.competition_scores.where(:region => 'hn', :score_type => 't').first.try(:score)
        sheet1[count_row,5] = com_spend_time user.competition_scores.where(:region => 'hn', :score_type => 't').first.try(:cost_time).to_i
        sheet1[count_row,6] = user[:p_score]
        sheet1[count_row,7] = com_spend_time user[:p_time].to_i
        sheet1[count_row,8] = user[:f_score]
        sheet1[count_row,9] = com_spend_time user[:f_time].to_i
        sheet1[count_row,10] = user[:s_score]
        sheet1[count_row,11] = com_spend_time user[:s_spend_time].to_i
        count_row += 1
      end
    elsif @competition.identifier == "gcc-dev-2018"
      records = @competition.competition_teams
      records.each do |team|
        # 决赛记录
        f_score = team.competition_scores.where(:competition_stage_id => @competition.competition_stages.where(:name => "决赛").first.try(:id)).first
        # 预赛记录
        p_score = team.competition_scores.where(:competition_stage_id => @competition.competition_stages.where(:name => "预赛").first.try(:id)).first
        team[:p_score] = p_score.try(:score)
        team[:p_time] = p_score.try(:cost_time)
        team[:f_score] = f_score.try(:score)
        team[:f_time] = f_score.try(:cost_time)
        team[:s_score] = (f_score.try(:score).to_f * 0.85 + p_score.try(:score).to_f * 0.15).try(:round, 2)
        team[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
      end
      records = records.sort do |a, b|
        [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
      end

      sheet1.row(0).concat(["序号","战队名","指导老师","队员","学校","预赛得分","预赛用时",
                            "决赛得分","决赛用时","总得分","总用时"])
      count_row = 1
      records.each_with_index do |team, index|
        user = team.user
        sheet1[count_row,0] = index + 1
        sheet1[count_row,1] = team.name
        sheet1[count_row,2] = team.teacher.try(:show_real_name)
        sheet1[count_row,3] = team.group_members
        sheet1[count_row,4] = chart_school_str team.team_members.where(:is_teacher => 0)
        sheet1[count_row,5] = team[:p_score]
        sheet1[count_row,6] = com_spend_time team[:p_time].to_i
        sheet1[count_row,7] = team[:f_score]
        sheet1[count_row,8] = com_spend_time team[:f_time].to_i
        sheet1[count_row,9] = team[:s_score]
        sheet1[count_row,10] = com_spend_time team[:s_spend_time].to_i
        count_row += 1
      end
    elsif @competition.identifier == "gcc-annotation-2018"
      records = @competition.competition_teams
      records.each do |team|
        team[:s_score] = team.competition_scores.where(:competition_id => @competition.id).first.try(:score).to_f.try(:round, 3)
      end
      records = records.sort do |a, b|
        [b[:s_score]] <=> [a[:s_score]]
      end

      sheet1.row(0).concat(["序号","战队名","指导老师","队员","学校","总得分"])
      count_row = 1
      records.each_with_index do |team, index|
        user = team.user
        sheet1[count_row,0] = index + 1
        sheet1[count_row,1] = team.name
        sheet1[count_row,2] = team.teacher.try(:show_real_name)
        sheet1[count_row,3] = team.group_members
        sheet1[count_row,4] = chart_school_str team.team_members.where(:is_teacher => 0)
        sheet1[count_row,5] = team[:s_score]
        count_row += 1
      end
    end
    book.write xls_report
    send_data(xls_report.string, :type => "text/excel;charset=utf-8; header=present",
              :filename => filename_for_content_disposition("#{@competition.name}比赛成绩.xls"))
  end

  def edit_rule
    @stage = @competition.competition_stages.where(:id => params[:stage_id]).first
    if request.get?
      @rule_content = ChartRule.where(:competition_id => @competition.id, :competition_stage_id => @stage.try(:id)).first
    else
      if params[:content]
        @rule_content = ChartRule.where(:competition_id => @competition.id, :competition_stage_id => @stage.try(:id)).first
        if @rule_content.present?
          @rule_content.update_attribute("content", params[:content])
        else
          @rule_content = ChartRule.create(:competition_id => @competition.id, :competition_stage_id => @stage.try(:id), :content => params[:content])
        end
      end
    end
  end

  def online_switch
    if @competition.present?
      if @competition.status
        @competition.update_attributes(:status => 0)
        @btn_html = "上架"
      else
        @competition.update_attributes(:status => 1, :online_time => Time.now)
        @btn_html = "下架"
      end
    end
  end

  def new_competition
    if params[:com_name] && params[:com_name].strip != ""
      visits = rand(400..1000)
      Competition.create(:name => params[:com_name], :start_time => params[:start_time], :end_time => params[:end_time], :visits => visits)
    end
    redirect_to competition_managements_path
  end

  def edit_competition
    competition = Competition.find params[:id]
    if params[:com_name] && params[:com_name].strip != ""
      competition.update_attributes(:name => params[:com_name], :start_time => params[:start_time], :end_time => params[:end_time])
    end
    redirect_to competition_managements_path
  end

  def competition_setting
    # @competition = Competition.find params[:id]
    if params[:md_name]
      md_modules = @competition.competition_modules.where(:md_edit => true)
      md_modules.destroy_all if md_modules
      params[:md_name].each_with_index do |name, index|
        hidden = params[:md_checked][index].to_i == 0 ? 1 : 0
        cm = CompetitionModule.create(:competition_id => @competition.id,:name => name, :position => params[:md_position][index], :hidden => hidden, :md_edit => true)
        # 创建md_contents
        CompetitionModuleMdContent.create(:competition_module_id => cm.id)
      end
    end

    if params[:competition_module]
      @competition.competition_modules.where(:id => params[:competition_module], :md_edit => false).update_all(:hidden => 0)
      none_modules = @competition.competition_modules.where("name != '首页' and md_edit = false").map(&:id).join(",").split(",") - params[:competition_module]
      @competition.competition_modules.where(:id => none_modules).update_all(:hidden => 1)
    end
    if params[:name]
      @competition.competition_modules.where("name not in ('首页', '报名', '通知公告', '排行榜', '资料下载') and md_edit = false").each_with_index do |mod, index|
        mod.update_attribute("name", params[:name][index])
      end
    end
    if params[:url]
      @competition.competition_modules.where("name not in ('首页', '报名', '通知公告', '排行榜') and md_edit = false").each_with_index do |mod, index|
        mod.update_attribute("url", params[:url][index])
      end
    end
    if params[:position]
      @competition.competition_modules.where(:md_edit => false).each_with_index do |mod, index|
        mod.update_attribute("position", params[:position][index])
      end
    end
    @competition.update_attributes(:identifier => params[:identifier], :min_num => params[:min_num], :max_num => params[:max_num], :enroll_end_time => params[:enroll_end_time])
    if params[:new_name]
      params[:new_name].each_with_index do |new_module, index|
        @competition.competition_modules << CompetitionModule.new(:name => new_module, :position => params[:new_position][index], :hidden => 0, :url => params[:new_url][index])
      end
    end
  end

  def competition_images
    @competition.attachments.destroy_all
    if params[:file]
      params[:file].each do |file|
        img_base64_head = 'data:image/jpeg;base64,'
        if file && file.start_with?(img_base64_head)
          file = StringIO.new(Base64.decode64(file[img_base64_head.size,file.size-img_base64_head.size]))
          attachment = Attachment.new(:file => file)
          attachment.author = User.current
          attachment.container_type = 'Competition'
          attachment.container_id = @competition.id
          attachment.filename = Redmine::Utils.random_hex(16) + ".jpg"
          attachment.save
        end
      end
    end
  end

  def new_competition_stage
    @result = ""
    @competition = Competition.find params[:id]
    if params[:name] && params[:name] != ""
      if @competition.competition_stages.where(:name => params[:name]).count > 0
        @result = "已存在同名的阶段"
      else
        @competition.competition_stages << CompetitionStage.new(:name => params[:name])
        @result = "新建成功"
      end
    end
  end

  def update_competition_stage
    @competition = Competition.find params[:id]
    @competition.competition_stages.where(:id => params[:stage_id]).update_all(:name => params[:name])
  end

  def delete_competition_stage
    @competition.competition_stages.where(:id => params[:stage_id]).destroy_all
  end

  def new_stage_section
    @competition = Competition.find params[:id]
    @result = ""
    stage = @competition.competition_stages.where(:id => params[:stage_id]).first
    if stage.present?
      new_section = CompetitionStageSection.new(:competition_id => @competition.id, :name => params[:new_section_name],
      :start_time => params[:new_start_time], :end_time => params[:new_end_time], :entry => params[:entry])
      stage.competition_stage_sections << new_section
      if params[:entry_name]
        params[:entry_name].each_with_index do |name, index|
          new_section.competition_entries << CompetitionEntry.new(:competition_stage_id => stage.id, :name => name, :url => params[:entry_url][index])
        end
      end
      new_section.entry = params[:entry_name] ? params[:entry_name].length : 0
      new_section.save
      @result = "新建成功"
    end
  end

  def update_stage_section
    section = @competition.competition_stage_sections.where(:id => params[:section_id]).first
    if section.present?
      section_entries = section.competition_entries
      if !params[:entry_name]
        section_entries.destroy_all
      else
        if params[:entry_name].length < section_entries.size
          section_entries[params[:entry_name].length, section_entries.size - 1].destroy_all
        end

        params[:entry_name].each_with_index do |name, index|
          entry = section_entries[index]
          if entry.present?
            entry.update_attributes(:name => name, :url => params[:entry_url][index])
          else
            section.competition_entries << CompetitionEntry.new(:competition_stage_id => section.competition_stage_id, :name => name, :url => params[:entry_url][index])
          end
        end
      end
      section.update_attributes(:name => params[:name], :start_time => params[:start_time], :end_time => params[:end_time], :entry => params[:entry_name] ? params[:entry_name].length : 0)
    end
  end

  def delete_stage_section
    @competition.competition_stage_sections.where(:id => params[:section_id]).destroy_all
  end

  private

  def chart_exp_score_mo myshixuns, s_time, e_time
    score1 = 0
    time1 = 0
    myshixuns.each do |myshixun|
      t_games = myshixun.games.select{|game| game.status == 2 && game.open_time >= s_time && game.end_time <= e_time }
      myshixun_score = t_games.map(&:final_score).sum
      myshixun_time = 0
      t_games.each do |game|
        myshixun_time += (game.end_time.to_i - game.open_time.to_i) > 0 ? (game.end_time.to_i - game.open_time.to_i) : 0
      end
      # myshixun_time = t_games.map(&:cost_time).sum
      time1 = myshixun_score > score1 ? myshixun_time : time1
      score1 = myshixun_score > score1 ? myshixun_score : score1
    end
    return [score1, time1]
  end

  def chart_exp_score myshixuns, s_time, e_time
    score1 = 0
    time1 = 0
    myshixuns.each do |myshixun|
      t_games = myshixun.games.select{|game| game.status == 2 && game.open_time >= s_time && game.end_time <= e_time }
      myshixun_score = t_games.map(&:final_score).sum
      end_time = t_games.map(&:end_time).max
      myshixun_time = (end_time.to_i - s_time.to_i) > 0 ? (end_time.to_i - s_time.to_i) : 0
      # myshixun_time = t_games.map(&:cost_time).sum
      time1 = myshixun_score > score1 ? myshixun_time : time1
      score1 = myshixun_score > score1 ? myshixun_score : score1
    end
    return [score1, time1]
  end

  # 预赛第一阶段
  # challenges 每阶段三个实训的所有关卡
  # s_time 阶段开始时间  e_time 阶段结束时间
  # rate 关卡经验值与分数的比值
  # 对三个实训的所有关卡循环: 找到在比赛时间内通关的最低耗时
  def chart_exp_score_pre user_ids, s_time, e_time, challenges, rate
    total_score = 0
    total_time = 0
    length = challenges.size / 3   #每个实训的关卡数
    for i in 1..length
      score = 0
      time = 0
      challenges.where(:position => i).each do |challenge|
        Game.where(:challenge_id => challenge.id, :user_id => user_ids, :status => 2).select{|game| game.open_time >= s_time && game.end_time <= e_time }.each do |game|
          game_score = challenge.score * rate
          cost_time = (game.end_time.to_i - s_time.to_i) > 0 ? (game.end_time.to_i -  s_time.to_i) : 0
          if score < game_score
            score = game_score
            time = cost_time
          elsif score == game_score
            time = cost_time > time ? time : cost_time
          end
        end
      end
      total_score += score
      total_time += time
=begin
      if team_id == 744
        Rails.logger.warn("#########challenge---#{i}:#{score}")
      end
=end
    end
    return [total_score, total_time]
  end

  def chart_exp_score_third user_ids, s_time, e_time, challenges
    # 第三阶段的得分和耗时
    score3 = 0
    time3 = 0

    challenges.each do |challenge|
      Game.where(:challenge_id => challenge.id, :user_id => user_ids, :status => 2).select{|game| game.open_time >= s_time && game.end_time <= e_time }.each do |game|
        outputs = game.outputs.select{|output| !output.text_scor.nil? }
        if outputs.present?
          outputs = outputs.sort { |a, b| b[:text_scor].to_f <=> a[:text_scor].to_f }
          myshixun_score = outputs.first.text_scor.to_f
          myshixun_time = outputs.first.created_at.to_i - s_time.to_i
          if score3 < myshixun_score
            score3 = myshixun_score
            time3 = myshixun_time
          elsif score3 == myshixun_score
            time3 = myshixun_time > time3 ? time3 : myshixun_time
          end
        end
      end
    end
    return [score3, time3]
  end

  def find_inform
    if params[:inform_id].present?
      @inform = Inform.find params[:inform_id]
    end
  end

  def find_type
    # competition = ["hn", "db"]
    # @competition = params[:competition_id] ? params[:competition_id] : params[:id]
    # if competition.include?(@competition.try(:strip))
    #   @competition
    # else
    #   render_404
    # end

    if Competition.where(:identifier => params[:id]).blank?
      @competition = Competition.find(params[:id])
    else
      @competition = Competition.where(:identifier => params[:id]).first
    end
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end