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

  def create  #每一次答案的点击，请求一次，实训题不在这里回答
    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.in?([Exercise::SINGLE, Exercise::JUDGMENT, Exercise::COMPLETION]) && 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  #选择题（单选）/判断题
        if ea.exists?
          ea.first.update!(exercise_choice_id: choice_id )
        else
          answer_option = {
            :user_id => current_user.id,
            :exercise_question_id => @exercise_question.id,
            :exercise_choice_id => choice_id,
            :answer_text => ""
          }
          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] : []
        question_choice_ids = @exercise_question.exercise_choices.pluck(:id)

        ea_ids = ea.pluck(:exercise_choice_id)
        common_answer_ids = choice_ids & ea_ids   #已经存在的试卷选项id
        new_ids = (choice_ids - common_answer_ids).uniq   # 新增的id
        old_ids = (ea_ids - common_answer_ids).uniq  #没有选择的，则删掉
        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 => "",
                :choice_index => question_choice_ids.index(e).to_i + 1   # choice的序号
            }
            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,
            :choice_index => choice_id
        }
        ea_answer = ea.search_answer_users("exercise_choice_id",choice_id)
        if ea.present? && ea_answer.present?
          # 答案为空而且之前有过回答的话则将回答删除
          if answer_text.strip.blank?
            ea_answer.destroy_all
          else
            ea_answer.first.update!(answer_option)
          end
        else
          if answer_text.strip.present?
            ex_new = ExerciseAnswer.new(answer_option)
            ex_new.save!
          end
        end
      elsif q_type == Exercise::SUBJECTIVE  #简答题
        answer_option = {
            :user_id => current_user.id,
            :exercise_question_id => @exercise_question.id
        }
        if ea.present? #已经回答了的，
          if answer_text.strip.blank?
            ea.destroy_all
          else
            ea.first.update!(answer_text: answer_text)
          end
        else
          if answer_text.strip.present?
            answer_option.merge!(answer_text:answer_text)
            ex_a = ExerciseAnswer.new(answer_option)
            ex_a.save!
          end
        end
      end
      normal_status(0,"回答成功")
    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.commited?
      normal_status(-1,"已提交/已结束的试卷不允许修改！")
    else
      if (@exercise_user_status == Exercise::DEADLINE && @exercise_user.none_commit?) || (@exercise.time > 0 && @exercise_user.start_at.present? && ((@exercise_user.start_at + @exercise.time.to_i.minutes) < Time.now))
        commit_exercise_user @exercise, @exercise_user
        normal_status(-1,"试卷提交时间已截止！")
      end
    end

  end

end
