class QuestionBanksController < ApplicationController
  before_action :require_login, :check_auth
  before_action :params_filter, except: [:my_courses]

  # 题库选用列表
  # object_type: #  normal 普通作业题库； group 分组作业题库； poll问卷题库； exercise试卷题库; gtask 毕设选题题库；gtopic 毕设任务
  # filter: 过滤条件 public公共题库， myself我的题库
  # search: 搜索条件
  def bank_list
    page = params[:page] || 1
    limit = params[:limit] || 15
    @certification_teacher = current_user.is_certification_teacher || current_user.admin?
    @objects = @object_type.classify.constantize.where(@object_filter)
    @objects =
        if params[:search]
          if params[:filter] == 'public'
            # 已认证才能获取题库
            if @certification_teacher
              sql = %Q{
              #{@objects.table_name}.is_public = 1 and concat(#{@objects.table_name}.name, course_lists.name) like
                    '%#{params[:search]}%'
                  }
              @objects.joins(:course_list).where(sql)
            else
              @objects.none
            end
          else
            sql = %Q{
            #{@objects.table_name}.user_id = #{current_user.id} and concat(#{@objects.table_name}.name, course_lists.name) like
                    '%#{params[:search]}%'
                  }
            @objects.joins(:course_list).where(sql)
          end
        else
          if params[:filter] == 'public'
            if @certification_teacher # 只用平台已认证的老师才能获取题库
              @objects.is_public
            else
              @objects.none
            end
          else
            @objects.myself(current_user.id)
          end
        end
    @objects = @objects.page(page).per(limit)
  end

  # 保存题库
  def save_banks
    tip_exception("bank_id不能为空") if params[:bank_id].blank?
    tip_exception("一次最多只能选用15份题库") if params[:bank_id].count > 15
    tip_exception("course_id不能为空") if params[:course_id].blank?
    begin
      objects = @object_type.classify.constantize.where(id: params[:bank_id])
      course = Course.find params[:course_id]
      new_object_ids = []
      objects.each do |object|
        case @object_type
        when 'HomeworkBank' # 作业
          new_object = quote_homework_bank object,course
        when 'ExerciseBank'
          if object.container_type == 'Exercise' # 试卷
            new_object = quote_exercise_bank object, course
          else # 问卷
            new_object = quote_poll_bank object, course
          end
        when 'GtaskBank'
          new_object = quote_gtask_bank object, course
        when 'GtopicBank'
          new_object = quote_gtopic_bank object, course
        end
        new_object_ids << new_object.id
      end
      render json: {status: 0, message: "选题成功", object_ids: new_object_ids}
    rescue Exception => e
      uid_logger_error(e.message)
      tip_exception("题库选用失败")
      raise ActiveRecord::Rollback
    end
  end

  def my_courses
    @courses = current_user.manage_courses.where(is_delete: 0, is_end: 0)
  end

  def send_to_course
    bank = current_bank
    course = current_user.manage_courses.find_by(id: params[:course_id])
    case @object_type
    when 'HomeworkBank' # 作业
      quote_homework_bank bank, course
    when 'ExerciseBank'
      if bank.container_type == 'Exercise' # 试卷
        quote_exercise_bank bank, course
      else # 问卷
        quote_poll_bank bank, course
      end
    when 'GtaskBank'
      quote_gtask_bank bank, course
    when 'GtopicBank'
      quote_gtopic_bank bank, course
    end
    normal_status("发送成功")
  end

  def destroy
    bank = current_bank

    unless user.admin? || bank.user_id == user.id
      render_forbidden
      return
    end

    bank.destroy!

    render_ok
  end

  def public
    current_bank.update!(is_public: true)
    render_ok
  end

  private

  def current_bank
    @_current_bank ||= @object_type.classify.constantize.where(@object_filter).find(params[:id])
  end
  def params_filter
    type = ["normal", "group", "poll", "exercise", "gtask", "gtopic"]
    tip_exception("object_type类型不正确") unless type.include?(params[:object_type])
    # HomeworkBank 普通、分组作业题库；ExerciseBank试卷、问卷题库；GtaskBank毕设选题题库；GtopicBank毕设任务题库；
    case params[:object_type]
    when 'normal'
      @object_type = "HomeworkBank"
      @object_filter = "homework_type = 1" # 普通作业
    when 'group'
      @object_type = "HomeworkBank"
      @object_filter = "homework_type = 3" # 分组作业
    when 'poll'
      @object_type = "ExerciseBank"
      @object_filter = "container_type = 'Poll'" # 问卷
    when 'exercise'
      @object_type = "ExerciseBank"
      @object_filter = "container_type = 'Exercise'" # 试卷
    when 'gtask'
      @object_type = "GtaskBank"
      @object_filter = nil
    when 'gtopic'
      @object_type = "GtopicBank"
      @object_filter = nil
    end
  end

  def quote_homework_bank homework, course
    ActiveRecord::Base.transaction do
      # 复制作业的基本信息
      new_homework = HomeworkCommon.new(name: homework.name, user_id: current_user.id, description: homework.description,
                                        homework_type: homework.homework_type, course_id: course.id, homework_bank_id: homework.id,
                                        reference_answer: homework.reference_answer)

      # 作业的基本设置复制
      new_homework.homework_detail_manual = HomeworkDetailManual.new
      new_homework_detail_manual = new_homework.homework_detail_manual

      if new_homework.homework_type == "group"
        # 分组作业表的复制
        new_homework.homework_detail_group = HomeworkDetailGroup.new
        new_homework.homework_detail_group.min_num = homework.min_num
        new_homework.homework_detail_group.max_num = homework.max_num
        new_homework.homework_detail_group.base_on_project = homework.base_on_project
      end
      # 附件
      logger.info("######attachments: #{homework.attachments.count}")
      if new_homework.save!
        homework.attachments.try(:each) do |attachment|
          att = attachment.copy
          att.container_id = nil
          att.container_type = nil
          att.author_id = homework.user_id
          att.attachtype = attachment.attachtype || 1
          # att.attachtype = 1
          att.copy_from = attachment.id
          att.save!
          new_homework.attachments << att
        end
        logger.info("######new_homework.attachments: #{new_homework.attachments.count}")
        new_homework_detail_manual.save if new_homework_detail_manual
        new_homework.homework_detail_group.save if new_homework.homework_detail_group
        HomeworksService.new.create_works_list(new_homework, course)
        homework.update_column(:quotes, homework.quotes + 1)
      end
      new_homework
    end
  end

  def quote_exercise_bank exercise, course
    ActiveRecord::Base.transaction do
      new_exercise = Exercise.new(:exercise_name => exercise.name, :exercise_description => exercise.description,
                                  :user_id => current_user.id, :course_id => course.id, :exercise_bank_id => exercise.id)
      # 复制试卷基本信息
      exercise.exercise_bank_questions.each do |q|
        option = {
            :question_title => q.question_title,
            :question_type => q.question_type || 1,
            :question_number => q.question_number,
            :question_score => q.question_score,
            :shixun_name => q.shixun_name,
            :shixun_id => q.shixun_id
        }
        exercise_question = new_exercise.exercise_questions.new option
        # question_type：5实训题；其他是非实训题
        if q.question_type != 5
          # 复制选择题题目选项
          q.exercise_bank_choices.try(:each_with_index) do |choice, index|
            exercise_question.exercise_choices.new({choice_position: index+1, choice_text: choice.choice_text})
          end

          # 复制标准答案(填空题和问答题)  多空填空题的话，应该是原标准答案的exercise_choice_id，即为题空的位置。
          q.exercise_bank_standard_answers.try(:each) do |answer|
            exercise_question.exercise_standard_answers.new({exercise_choice_id: answer.exercise_bank_choice_id, answer_text: answer.answer_text})
          end
        else
          # 复制实训题
          q.exercise_bank_shixun_challenges.try(:each_with_index) do |sc, index|
            exercise_question.exercise_shixun_challenges.new({position: index+1, challenge_id: sc.challenge_id,
                                                              shixun_id: sc.shixun_id, question_score: sc.question_score})
          end
        end
      end
      # 添加学生
      # if new_exercise.save
      #   new_exercise.create_exercise_list
      #   exercise.update_column(:quotes, exercise.quotes+1)
      # end
      new_exercise if new_exercise.save!
    end
  end

  def quote_poll_bank poll, course
    ActiveRecord::Base.transaction do
      new_poll = Poll.new(:polls_name => poll.name, :polls_description => poll.description, :user_id => current_user.id,
                          :polls_type => 'Course', :course_id => course.id, :exercise_bank_id => poll.id)

      poll.exercise_bank_questions.try(:each) do |q|
        option = {
            :question_title => q.question_title,
            :question_type => q.question_type || 1,
            :is_necessary => q.is_necessary,
            :question_number => q.question_number,
            :max_choices => q.max_choices,
            :min_choices => q.min_choices
        }
        poll_question = new_poll.poll_questions.new option
        q.exercise_bank_choices.try(:each_with_index) do |choice, index|
          poll_question.poll_answers.new({answer_position: index+1, answer_text: choice.choice_text})
        end
      end
      # if new_poll.save
      #   new_poll.create_polls_list
      #   poll.update_column(:quotes, poll.quotes+1)
      # end
      new_poll if new_poll.save!
    end
  end

  def quote_gtask_bank task, course
    ActiveRecord::Base.transaction do
      new_task = GraduationTask.new
      new_task.attributes = task.attributes.dup.except("id", "course_id", "user_id", "quotes", "graduation_task_id",
                                                       "course_list_id", "gtask_bank_id", "created_at", "updated_at")
      new_task.course_id = course.id
      new_task.gtask_bank_id = task.id
      new_task.user_id = current_user.id
      if new_task.save!
        new_task.create_work_list
      end
      # 复制附件内容
      task.attachments.try(:each) do |attachment|
        att = attachment.copy
        att.container_id = nil
        att.container_type = nil
        att.author_id = task.user_id
        att.copy_from = attachment.id
        att.save
        new_task.attachments << att
      end
      task.update_column(:quotes, task.quotes+1)
      new_task
    end
  end

  def quote_gtopic_bank topic, course
    ActiveRecord::Base.transaction do
      new_topic = GraduationTopic.new
      new_topic.attributes = topic.attributes.dup.except("id", "course_id", "user_id", "graduation_topic_id", "quotes",
                                                         "course_list_id", "gtopic_bank_id", "created_at", "updated_at")
      new_topic.course_id = course.id
      new_topic.gtopic_bank_id = topic.id
      new_topic.user_id = current_user.id
      new_topic.tea_id = current_user.id
      new_topic.save

      topic.attachments.each.try(:each) do |attachment|
        att = attachment.copy
        att.container_id = nil
        att.container_type = nil
        att.author_id = topic.user_id
        att.copy_from = attachment.id
        att.save
        new_topic.attachments << att
      end
      topic.update_column(:quotes, topic.quotes+1)
      new_topic
    end
  end


end
