class Admins::ImportItemBankService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :file, :result

  def initialize(file, sub_discipline_id)
    @sub_discipline_id = sub_discipline_id
    @file   = file
    @result = { success: 0, fail: [] }
  end

  def call
    raise Error, '文件不存在' if file.blank?

    excel = Admins::ImportItemBankExcel.new(file)
    excel.read_each(&method(:save_data))

    result
  rescue ApplicationImport::Error => ex
    raise Error, ex.message
  end

  private

  def save_data(data)
    count = 0

    unless data.item_type.to_s.strip.present?
      return 
    end
    unless data.login.to_s.strip.present?
      raise '用户名不能为空'
    end

    user = User.find_by(login: data.login.to_s.strip)
    item_bank = ItemBank.new(public: true, name: data.name, difficulty: data.difficulty || 1, user_id: user.id, sub_discipline_id: @sub_discipline_id)
    case data.item_type.to_s
    when '1'
      #单选题
      item_bank.item_type = 'SINGLE'
    when '2'
      # 多选题
      item_bank.item_type = 'MULTIPLE'
    when '3'
      # 判断题
      item_bank.item_type = 'JUDGMENT'
    end
    item_bank.save!

    answer = data.answer.to_s.strip
    if data.item_type.to_s.strip == '3'
      is_right = answer == '1' #判断题答案
      item_bank.item_choices.create!(choice_text: '正确', is_answer: is_right)
      item_bank.item_choices.create!(choice_text: '错误', is_answer: !is_right)
    else
      select_answer = answer.split("")
      if data.choice_text1.present?
        item_bank.item_choices.create!(choice_text: data.choice_text1, is_answer: select_answer.include?("A"))
      end
      if data.choice_text2.present?
        item_bank.item_choices.create!(choice_text: data.choice_text2, is_answer: select_answer.include?("B"))
      end
      if data.choice_text3.present?
        item_bank.item_choices.create!(choice_text: data.choice_text3, is_answer: select_answer.include?("C"))
      end
      if data.choice_text4.present?
        item_bank.item_choices.create!(choice_text: data.choice_text4, is_answer: select_answer.include?("D"))
      end
      if data.choice_text5.present?
        item_bank.item_choices.create!(choice_text: data.choice_text5, is_answer: select_answer.include?("E"))
      end
    end
    count += 1

    result[:success] += count
  rescue Exception => ex
    fail_data = data.as_json
    fail_data[:data] = fail_data.values.join(',')
    fail_data[:message] = ex.message

    result[:fail] << fail_data
  end
end