module StudentWorksHelper
  # 学生作业是否迟交
  def student_work_is_delay? homework_common, game
    (Time.now > homework_common.end_time && game.end_time.blank?) || (game.end_time.present? && game.end_time > homework_common.end_time)
  end

  # 关卡的完成状态：提交截止(不允许补交)后或补交截止后通关的是无效状态，允许补交且在补交阶段内通关的是延时状态，提交截止前完成的是正常状态
  # 0：未通关  1：正常  2：延时  3：无效
  def game_status game, homework
    if game.status == 2
      homework_setting = homework.homework_group_setting game.user_id
      status = homework_setting.end_time >= game.end_time ? 1 :
                   (homework.allow_late && homework.late_time > game.end_time) ? 2 : 3
    else
      status = 0
    end
    status
  end

  # 作业的开启时间
  def myshixun_open_time game
    game&.open_time ? (format_time game.open_time) : "--"
  end

  # 作业完成时间
  def finished_time end_time
    end_time ? (format_time end_time) : "--"
  end

  # 作业耗时
  def time_consuming game
    game&.end_time.blank? ? "--" : (game_spend_time game.cost_time)
  end

  # 用户个人实训总得分：user_total_score；
  # consume_time通关的关卡总耗时间；
  # all_tine实训的总耗时
  # evaluate_count: 每次总评测次数；
  # eff_score：用户得分/总评测次数；
  # round_size：log(所有课堂实训最大评测次数/当前实训评测次数）

  def student_efficiency(homework_common, work)
    myshixun_ids = homework_common.student_works.pluck(:myshixun_id)
    myshixuns = Myshixun.where(id: myshixun_ids).includes(:games)
    #student_works_user_id = homework_common.student_works.pluck(:user_id).uniq
    #shixun = homework_common.shixuns.first
    #logger.info("#########shixun_id: ###{shixun.id}")
    #myshixuns = shixun.myshixuns.where(:user_id => student_works_user_id).includes(games: [:outputs])

    # 最大评测次数
    max_evaluate_count = 0

    # 数据库操作改成对hash数组的操作
    objects =
        myshixuns.map do |myshixun|
          # 评测次数
          evaluate_count = myshixun.games.pluck(:evaluate_count).sum
          # 获取最大评测次数
          max_evaluate_count = (evaluate_count > max_evaluate_count ? evaluate_count : max_evaluate_count)
          # 通关耗时
          pass_consume_time = (myshixun.total_cost_time / 60.0)
          # 总耗时
          all_time = (myshixun.games.pluck(:cost_time).sum / 60.0)
          # 通关得分
          user_total_score = myshixun.total_score.to_i
          # 耗时,保留2位小数，
          consume_time = all_time <= 1 ? 1 : Math.log(all_time).to_f
          consume_time = format("%.2f", consume_time).to_f
          # 效率
          efficiency = (pass_consume_time == 0 ? 0 : Math.log((user_total_score / pass_consume_time.to_f) + 1.0))
          efficiency = format("%.2f", efficiency).to_f

          {consume_time: consume_time, evaluate_count: evaluate_count, user_id: myshixun.user_id,
           user_total_score: user_total_score, efficiency: efficiency}
        end

    # 我的效率
    myself_eff = []
    myself_object = []
    # 最小效率值
    min_efficiency = objects.map {|o| o[:efficiency]}.min
    # 最大效率值
    # max_efficiency = objects.map{|o| o[:efficiency]}.max
    results =
        objects.each_with_index.map do |object, index|
          y_score = (object[:evaluate_count] == 0 ? 0 : (object[:user_total_score] / object[:evaluate_count].to_f))
          eff_score = format("%.2f", y_score).to_f
          # 效率值
          efficiency = object[:efficiency] < 0 ?
                           format("%.2f", object[:efficiency] - min_efficiency) : object[:efficiency]

          # 圆圈的大小
          round_size = (object[:evaluate_count] == 0 ? 0 : Math.log(max_evaluate_count / object[:evaluate_count].to_f)) * 3.14
          # 作品本人的数据
          if object[:user_id] == work.user.id
            myself_eff = [index + 1, efficiency]
            myself_object = [object[:consume_time], eff_score, round_size]
          end
          {:eff_score => eff_score, :user_id => object[:user_id], :consume_time => object[:consume_time],
           :efficiency => efficiency, :round_size => round_size}
        end

    # 对结果进行排序
    efficiency_list =
        results.sort {|x, y| x[:efficiency] <=> y[:efficiency]}.each_with_index.map do |result, index|
          if result[:user_id] == work.user.id
            myself_eff = [index+1, result[:efficiency]]
            myself_object = [result[:consume_time], result[:eff_score], result[:round_size]]
          end
          [index + 1, result[:efficiency], result[:user_id]]
        end

    consume_list =
        results.sort {|x, y| x[:consume_time] <=> y[:consume_time]}.map do |result|
          [result[:consume_time], result[:eff_score], result[:round_size], result[:user_id]]
        end

    return {myself_eff: myself_eff, myself_object: myself_object, efficiency_list: efficiency_list, consume_list: consume_list}
  end

  # tpi详情信息
  def output_detail game, output
    if game.challenge.st == 0
      output.try(:out_put).delete("详情如下：")
    else
      if game.status == 2
        "评测通过"
      else
        "共有#{game.challenge.challenge_chooses.count}组测试集，其中有#{game.challenge.challenge_chooses.count-game.choose_correct_num(output.query_index)}组测试结果不匹配"
      end
    end
  end

  def allow_score homework, identity, user_id, work
    (identity < Course::STUDENT && !work.ultimate_score) ||
        (identity == Course::STUDENT && homework.anonymous_comment &&
            [3, 4].include?(homework.homework_detail_manual.comment_status) &&
            StudentWorksEvaluationDistribution.where(user_id: user_id, student_work_id: work.id).count > 0)
  end

  def message_user_name(message_user, score, work_user, current_user, identity)
    user_name = ""
    user_login = "--"
    image_url = "--"
    if score.reviewer_role == 3 && score.user == message_user && message_user != current_user && identity >= Course::STUDENT
      user_name =  "匿评人"
    elsif score.reviewer_role == 3 && work_user == message_user && message_user != current_user && identity >= Course::STUDENT
      user_name = "被匿评人"
    else
      user_name = message_user.real_name
      user_login = message_user.login
      image_url = url_to_avatar(message_user)
    end
    {user_name: user_name, user_login: user_login, user_image_url: image_url}
  end

  def appeal_info work_appeal, user_identity, current_user
    if user_identity < Course::STUDENT || work_appeal.user == current_user
      user_name = work_appeal.user.try(:real_name)
      user_login = work_appeal.user.try(:login)
      image_url = url_to_avatar(work_appeal.user)
    else
      user_name = "匿名"
      user_login = "--"
      image_url = "--"
    end
    {id: work_appeal.id, user_name: user_name, user_login: user_login, user_image_url: image_url, time: work_appeal.created_at, content: work_appeal.comment}
  end
end
