class ExaminationBanksController < ApplicationController
  include PaginateHelper
  before_action :require_login
  before_action :find_exam, except: [:index, :create]
  before_action :edit_auth, only: [:update, :destroy, :set_public]

  def index
    exams = ExaminationBankQuery.call(params)
    @exams_count = exams.size
    @exams = paginate exams.includes(:user, :examination_items)
  end

  def show
    @items = @exam.examination_items
    @single_questions = @items.where(item_type: "SINGLE")
    @multiple_questions = @items.where(item_type: "MULTIPLE")
    @judgement_questions = @items.where(item_type: "JUDGMENT")
    @program_questions = @items.where(item_type: "PROGRAM")
  end

  def create
    ActiveRecord::Base.transaction do
      exam = ExaminationBank.new(user: current_user)
      # 保存试卷基础信息
      exam = ExaminationBanks::SaveExaminationBankService.call(exam, form_params)

      # 将试题篮中的试题发送到试卷，试卷的题目与试题独立
      current_user.item_baskets.includes(:item_bank).each do |basket|
        item = basket.item_bank
        if item.present?
          new_item = ExaminationItem.new(examination_bank: exam, item_bank: item, name: item.name, item_type: item.item_type,
                                         difficulty: item.difficulty, score: basket.score, position: basket.position)
          new_item.save!
          item.increment!(:quotes)

          if item.item_type == "PROGRAM"
            new_hack = item.container.fork
            new_item.update_attributes!(container: new_hack)
          else
            new_item.examination_item_analysis.create!(analysis: item.analysis)
            item.item_choices.each do |choice|
              new_item.examination_item_choices << ExaminationItemChoice.new(choice_text: choice.choice_text, is_answer: choice.is_answer)
            end
          end
        end
      end

      current_user.item_baskets.destroy_all
    end
    render_ok
  end

  def edit

  end

  def update

  end

  def destroy
    @exam.destroy!
    render_ok
  end

  def set_public
    tip_exception(-1, "该试卷已公开") if @exam.public?
    @exam.update_attributes!(public: 1)
    render_ok
  end

  private

  def form_params
    params.permit(:discipline_id, :sub_discipline_id, :difficulty, :name, :duration, tag_discipline_id: [])
  end

  def find_exam
    @exam = ExaminationBank.find_by!(id: params[:id])
  end

  def edit_auth
    current_user.admin_or_business? || @exam.user == current_user
  end
end