class PollBankQuestionsController < ApplicationController
  before_action :require_login, :check_auth  #用户需登陆
  before_action :get_poll, only:[:create]  #获取试卷
  before_action :get_poll_question, except: [:create]  #获取试卷的问题及试卷
  before_action :bank_admin  #是否为老师
  before_action :validates_params, only: [:create, :update]  #传入参数的验证

  def create
    ActiveRecord::Base.transaction do
      begin
        poll_options = {
          :question_title => params[:question_title],
          :question_type => params[:question_type],
          :is_necessary => params[:is_necessary].to_i,
          :question_number => @poll.exercise_bank_questions.count + 1,
          :max_choices => params[:max_choices] || nil,
          :min_choices => params[:min_choices] || nil
        }
        @poll_question = @poll.exercise_bank_questions.new(poll_options)

        if params[:insert_id].present? #插入问题时，那么从插入的这个id以后的question_num都将要+1
          insert_poll = @poll.exercise_bank_questions.find_by(id: params[:insert_id])
          if insert_poll.present?  #如果该问题存在的话，意思是如果是第一题，那么就不存在插入
            ques_num = insert_poll.question_number.to_i
            @poll_question.question_number = ques_num + 1  #更新了问题的位置
            @poll.exercise_bank_questions.insert_question_ex(ques_num).update_all("question_number = question_number + 1")
          end
        end
        if @poll_question.save!
          if params[:question_type] != 3
            p_answer = params[:question_answers]
            p_other_answer = params[:question_other_answer]
            # 新增选择题答案选择的选项
            (1..p_answer.count).each do |i|
              answer = p_answer[i-1] # 传入的答案的内容
              question_option = {
                :choice_position => i,
                :choice_text => answer
              }
              poll_answers = @poll_question.exercise_bank_choices.new question_option
              poll_answers.save
            end
            # 新增答案的其他选项
            if p_other_answer
              question_option = {
                :choice_position => p_answer.count + 1,
                :choice_text => ''
              }
              poll_answers = @poll_question.exercise_bank_choices.new question_option
              poll_answers.save
            end
          end
        end
        normal_status("创建成功")
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception(e.message)
        raise ActiveRecord::Rollback
      end
    end
  end

  def update
    ActiveRecord::Base.transaction do
      begin
        if @poll_question.question_type < 3  #当为单选题或多选题时
          p_answer = params[:question_answers]
          p_other_answer = params[:question_other_answer]
          p_answer_count = p_answer.count
          @poll_current_answers = @poll_question.exercise_bank_choices.count
          @poll_question.exercise_bank_choices.each do |an|
            if (p_answer_count < @poll_current_answers) && (p_answer_count..@poll_current_answers).to_a.include?(an.choice_position)
              an.destroy
            end
          end
          (1..p_answer_count).each do |i|
            answer = @poll_question.exercise_bank_choices.find_choice_custom("choice_position",i).first
            if answer  # 判断该位置的answer是否存在，存在则更新.不存在则跳到下一步
              answer.choice_text = p_answer[i-1]
              answer.choice_position = i
              answer.save
            else
              answer_options = {
                :choice_position => i,
                :choice_text => p_answer[i-1]
              }
              @poll_question.exercise_bank_choices.new answer_options
            end
          end
          if p_other_answer  #判断答案的其他选项是否存在
            other_answer = @poll_question.exercise_bank_choices.find_choice_custom("choice_text","").first
            if other_answer.blank?
              question_option = {
                :choice_position => p_answer_count + 1,
                :choice_text => ''
              }
              @poll_question.exercise_bank_choices.new question_option
            else
              other_answer.choice_position = p_answer_count + 1
              other_answer.save
            end
          end
        end
        @poll_question.update_attributes(poll_questions_params)
        normal_status("问卷更新成功")
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception(e.message)
        raise ActiveRecord::Rollback
      end
    end
  end

  private

  def bank_admin
    tip_exception(403, "无权限") unless @poll.user_id == current_user.id || current_user.admin_or_business?
  end

  def get_poll
    @poll = ExerciseBank.find_by!(id: params[:exercise_bank_id])
  end

  def get_poll_question
    @poll_question = ExerciseBankQuestion.find_by!(id: params[:id])
    @poll = @poll_question.exercise_bank
  end

  def poll_questions_params
    params.permit(:question_title,:question_type,:is_necessary,:question_number,:max_choices,:min_choices)
  end

  def validates_params
    tip_exception(-1, "问题标题不能为空！") if params[:question_title].blank?
    tip_exception(-1, "是否要求必答的值不能为空！") if params[:is_necessary].blank?
    tip_exception(-1, "问题类型不能为空！") if params[:question_type].blank?
    if params[:min_choices].present? && params[:max_choices].present? && (params[:min_choices].to_i > params[:max_choices].to_i)
      tip_exception(-1, "最小可选不能大于最大可选！")
    elsif params[:question_answers].present? && (params[:max_choices].to_i > params[:question_answers].count)
      tip_exception(-1, "选择题的最大可选项不能大于答案数！")
    elsif [1,3].include?(params[:question_type]) && (params[:max_choices].to_i > 0 || params[:min_choices].to_i > 0)
      tip_exception(-1, "单选题或主观题不能有最大或最小选择数！")
    elsif params[:question_type] == 3 && (params[:question_answers] || params[:question_other_answer])
      tip_exception(-1, "主观问题不需要可选答案！")
    elsif params[:question_type] != 3
      if params[:question_answers].present? && params[:question_answers].include?("")
        tip_exception(-1, "选择题不能有空值！")
      elsif params[:question_other_answer].present? && params[:question_other_answer].length > 0
        tip_exception(-1, "其他选项不能有值！")
      elsif params[:question_type] == 1 && params[:question_answers].count < 2
        tip_exception(-1, "单选题选项不能小于2！")
      elsif params[:question_type] == 2 && params[:question_answers].count < 3
        tip_exception(-1, "多选题选项不能小于3！")
      end
    end
  end

end
