class ExerciseAnswersController < ApplicationController
  before_action :require_login, :check_auth
  before_action :get_exercise_question
  include ExercisesHelper

  def create  #每一次答案的点击，请求一次，实训题不在这里回答
    ActiveRecord::Base.transaction do
      begin
        q_type = @exercise_question.question_type  #试卷的类型
        choice_id = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : ""
        answer_text = params[:answer_text].present? ? params[:answer_text].strip : ""  #为字符串
        if q_type < Exercise::SUBJECTIVE && (q_type != Exercise::MULTIPLE) && choice_id.blank?
          normal_status(-1,"请选择序号")
        else
          ea = @exercise_question.exercise_answers.search_answer_users("user_id",current_user.id)  #试卷的当前用户的答案
          if q_type == Exercise::SINGLE || q_type == Exercise::JUDGMENT  #选择题（单选）/判断题
            ea_choice = ea.search_exercise_answer("exercise_choice_id",choice_id).first
            answer_option = {
                :user_id => current_user.id,
                :exercise_question_id => @exercise_question.id,
                :exercise_choice_id => choice_id,
                :answer_text => ""
            }
            if ea_choice.present? #如果当前用户的答案存在，再次点击，即为删除
              ea_choice.destroy
            else
              if @exercise_question.exercise_standard_answers.count <= 1  #单选题的时候
                ea.first.destroy if ea.present?
              end
              ex_a = ExerciseAnswer.new(answer_option)
              ex_a.save!
            end
          elsif q_type == Exercise::MULTIPLE   #多选题的
            choice_ids = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : []

            ea_ids = ea.pluck(:exercise_choice_id)
            common_answer_ids = choice_ids & ea_ids   #已经存在的试卷选项id
            new_ids = choice_ids - common_answer_ids   # 新增的id
            old_ids = ea_ids - common_answer_ids  #没有选择的，则删掉
            if new_ids.size > 0
              new_ids.each do |e|
                answer_option = {
                    :user_id => current_user.id,
                    :exercise_question_id => @exercise_question.id,
                    :exercise_choice_id => e,
                    :answer_text => ""
                }
                ex_a = ExerciseAnswer.new(answer_option)
                ex_a.save!
              end
            end
            if old_ids.size > 0
              ea_answer = ea.search_answer_users("exercise_choice_id",old_ids)
              ea_answer.destroy_all
            end
          elsif q_type == Exercise::COMPLETION  #填空题
            answer_option = {
                :user_id => current_user.id,
                :exercise_question_id => @exercise_question.id,
                :exercise_choice_id => choice_id,
                :answer_text => answer_text
            }
            ea_answer = ea.search_answer_users("exercise_choice_id",choice_id)
            if ea.present? && ea_answer.present?
              ea_answer.update(answer_option)
            else
              ex_new = ExerciseAnswer.new(answer_option)
              ex_new.save!
            end
          elsif q_type == Exercise::SUBJECTIVE  #简答题
            answer_option = {
                :user_id => current_user.id,
                :exercise_question_id => @exercise_question.id
            }
            if ea.present? #已经回答了的，
              ea.first.update_attribute("answer_text",answer_text)
            else
              answer_option.merge!(answer_text:answer_text)
              ex_a = ExerciseAnswer.new(answer_option)
              ex_a.save!
            end
          end
          normal_status(0,"回答成功")
        end
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("页面调用失败！")
        raise ActiveRecord::Rollback
      end
    end
  end

  private

  def get_exercise_question
    @exercise_question = ExerciseQuestion.find_by_id(params[:exercise_question_id])
    @exercise = @exercise_question&.exercise
    @course = @exercise&.course
    @exercise_user = @exercise&.exercise_users.find_by(user_id: current_user.id) #当前用户
    @exercise_user_status = @exercise.get_exercise_status(current_user)

    if @exercise_question.blank?
      normal_status(-1,"试卷问题不存在！")
    elsif @exercise.blank?
      normal_status(-1,"试卷不存在！")
    elsif @course.blank?
      normal_status(-1,"该课堂不存在！")
    elsif @exercise_user.blank?
      normal_status(-1,"试卷用户不存在！")
    elsif @exercise_user.commit_status == 1
      normal_status(-1,"已提交/已结束的试卷不允许修改！")
    else
      if (@exercise_user_status == Exercise::DEADLINE && @exercise_user.commit_status == 0) || (@exercise.time > 0 && @exercise_user.start_at.present? && ((@exercise_user.start_at + (@exercise.time.to_i + 1).minutes) < Time.now))
        objective_score = calculate_student_score(@exercise,current_user)[:total_score]
        subjective_score = @exercise_user.subjective_score < 0.0 ? 0.0 : @exercise_user.subjective_score
        total_score = objective_score + subjective_score
        commit_option = {
            :status => 1,
            :commit_status => 1,
            :end_at => Time.now,
            :objective_score => objective_score,
            :score => total_score,
            :subjective_score => subjective_score
        }
        @exercise_user.update_attributes(commit_option)
        normal_status(-1,"试卷提交时间已截止！")
      end
    end

  end

end
