class PollQuestionsController < ApplicationController
  before_action :require_login, :check_auth
  before_action :get_poll, only: [:new, :create]
  before_action :get_poll_question, except: [:new, :create]
  before_action :is_course_teacher
  before_action :get_poll_questions_count, only: [:create]
  before_action :get_poll_question_answers, only: [:edit, :update]
  before_action :check_poll_status, only: [:new, :create, :delete_answer, :destroy]
  before_action :validates_params, only: [:create, :update]
  before_action :validates_update_params, only: [:update]


  def new
    ActiveRecord::Base.transaction do
      begin
        @poll_question = @poll.poll_questions.new
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("页面调用失败!")
        raise ActiveRecord::Rollback
      end
    end
  end

  # 创建题目和选择的答案
  def create
    ActiveRecord::Base.transaction do
      poll_options = {
        :question_title => params[:question_title],
        :question_type => params[:question_type],
        :is_necessary => params[:is_necessary].to_i,
        :question_number => @poll_ques_count + 1,
        :max_choices => params[:max_choices] || nil,
        :min_choices => params[:min_choices] || nil
      }
      @poll_question = @poll.poll_questions.new(poll_options)

      if params[:insert_id].present? #插入问题时,那么从插入的这个id以后的question_num都将要+1
        insert_poll = @poll.poll_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.poll_questions.insert_question(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 = {
              :answer_position => i,
              :answer_text => answer
            }
            poll_answers = @poll_question.poll_answers.new question_option
            poll_answers.save!
          end
          # 新增答案的其他选项
          if p_other_answer
            question_option = {
              :answer_position => p_answer.count + 1,
              :answer_text => ''
            }
            poll_answers = @poll_question.poll_answers.new question_option
            poll_answers.save!
          end
        end
      end
    end
  end

  def show
    ActiveRecord::Base.transaction do
      begin
        @poll_answers = @poll_question.poll_answers
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("页面调用失败!")
        raise ActiveRecord::Rollback
      end
    end
  end

  def edit
    ActiveRecord::Base.transaction do
      begin
        @poll_answers = @poll_question.poll_answers
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("页面调用失败!")
        raise ActiveRecord::Rollback
      end
    end
  end

  def update
    ActiveRecord::Base.transaction do
      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_question.poll_answers.each do |an|
          if (p_answer_count < @poll_current_answers) && (p_answer_count..@poll_current_answers).to_a.include?(an.answer_position)
            an.destroy
          end
        end
        (1..p_answer_count).each do |i|
          answer = @poll_question.poll_answers.find_answer_by_custom("answer_position", i).first
          if answer # 判断该位置的answer是否存在,存在则更新.不存在则跳到下一步
            answer.answer_text = p_answer[i - 1]
            answer.answer_position = i
            answer.save!
          else
            answer_options = {
              :answer_position => i,
              :answer_text => p_answer[i - 1]
            }
            @poll_question.poll_answers.new answer_options
          end
        end
        if p_other_answer #判断答案的其他选项是否存在
          other_answer = @poll_question.poll_answers.find_answer_by_custom("answer_text", "").first
          if other_answer.blank?
            question_option = {
              :answer_position => p_answer_count + 1,
              :answer_text => ''
            }
            @poll_question.poll_answers.new question_option
          else
            other_answer.answer_position = p_answer_count + 1
            other_answer.save!
          end
        end
      end

      @poll_question.update!(poll_questions_params)
    end
  end

  def delete_answer
    ActiveRecord::Base.transaction do
      begin
        answer_d_id = params[:answer_no].to_i # 答案的当前位置
        poll_answers = @poll_question.poll_answers
        delete_answer = poll_answers.find_by(answer_position: answer_d_id)
        left_answers = poll_answers.where("answer_position > ?", answer_d_id)
        left_answers.update_all("answer_position = answer_position - 1") if left_answers

        if delete_answer.destroy
          normal_status(0, "答案删除成功!")
        else
          normal_status(-1, "答案删除失败!")
        end
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("答案删除失败!")
      end
    end
  end

  def destroy
    ActiveRecord::Base.transaction do
      begin
        question_d_id = @poll_question.question_number.to_i #问题的当前位置
        poll_questions = @poll.poll_questions
        left_questions = poll_questions.insert_question(question_d_id)
        left_questions.update_all("question_number = question_number - 1") if left_questions
        @poll_question.destroy!
        normal_status("删除成功")
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("问题删除失败!")
      end
    end
  end

  def up_down
    ActiveRecord::Base.transaction do
      begin
        opr = params[:opr]
        current_q_p = @poll_question.question_number.to_i #问题的当前位置
        if @poll.polls_status.to_i == 1
          if opr.present?
            if opr.to_s == "up"
              last_q_p = @poll.poll_questions.find_by(question_number: (current_q_p - 1)) #当前问题的前一个问题
              if last_q_p.present?
                @poll_question.update!(question_number: (current_q_p - 1))
                last_q_p.update!(question_number: current_q_p) # 重新获取当前问题的位置
                normal_status(0, "问题上移成功!")
              else
                normal_status(-1, "移动失败,已经是第一个问题了!")
              end
            elsif opr.to_s == "down"
              next_q_p = @poll.poll_questions.find_by(question_number: (current_q_p + 1)) #当前问题的后一个问题
              if next_q_p.present?
                @poll_question.update!(question_number: (current_q_p + 1))
                next_q_p.update!(question_number: current_q_p)

                normal_status(0, "问题下移成功!")
              else
                normal_status(-1, "移动失败,已经是最后一个问题了!")
              end
            end
          else
            normal_status(-1, "移动失败,请输入参数")
          end
        else
          normal_status(-1, "已发布的不能移动问题")
        end
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("问题移动失败!")
      end
    end
  end

  private

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

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

  def validates_update_params
    question_a_count = params[:question_answers].present? ? params[:question_answers].count : 0
    question_o_count = params[:question_other_answer].present? ? params[:question_other_answer].count : 0
    normal_status(-1, "已发布的问卷不允许增删答案!") if (((question_a_count + question_o_count) != @poll_current_answers) && (@poll.polls_status.to_i != 1))
  end

  def get_poll
    @poll = Poll.find_by(id: params[:poll_id])
    if @poll.blank?
      tip_exception(404)
    end
  end

  def get_poll_questions_count
    if @poll.poll_questions.count > 0
      @poll_ques_count = @poll.poll_questions.count
    else
      @poll_ques_count = 0
    end
  end

  def get_poll_question
    @poll_question = PollQuestion.find_by(id: params[:id])
    if @poll_question.present?
      @poll = Poll.find_by(id: @poll_question.poll_id)
    else
      tip_exception(404)
    end
  end

  #获取问题的答案数量
  def get_poll_question_answers
    @poll_current_answers = @poll_question.poll_answers.count
  end

  # 已发布的问卷不能新增题目
  def check_poll_status
    normal_status(-1, "问卷已发布,不能更改问卷题目") if @poll.polls_status.to_i != 1
  end

  def is_course_teacher
    @course = @poll.course
    if @course.blank?
      tip_exception(404)
    else
      @identity = current_user.course_identity(@course)
      normal_status(-1, "权限不够") unless (@course.present? && @identity < Course::STUDENT) #课堂存在,且当前用户为教师/管理员
    end
  end
end