$(document).on('turbolinks:load', function () {
  if ($('body.admins-item-banks-index-page').length > 0) {
    // 导入题库
    var $import_item_bank = $('.modal.admin-import-item_bank-modal');
    var $importForm = $import_item_bank.find('form.admin-import-item_bank-form');

    $import_item_bank.on('show.bs.modal', function () {
      resetFileInputFunc($import_item_bank.find('.upload-file-input'));
      $import_item_bank.find('.file-names').html('选择文件');
      $import_item_bank.find('.upload-file-input').trigger('click');
    })
    $import_item_bank.on('change', '.upload-file-input', function (e) {
      var file = $(this)[0].files[0];
      $import_item_bank.find('.file-names').html(file ? file.name : '请选择文件');
    })

    var importFormValid = function () {
      if ($importForm.find('input[name="file"]').val() == undefined || $importForm.find('input[name="file"]').val().length == 0) {
        $importForm.find('.error').html('请选择文件');
        return false;
      }

      return true;
    }

    var buildResultMessage = function (data) {
      var messageHtml = "<div>导入结果：成功" + data.success + "条，失败" + data.fail.length + "条</div>";

      return messageHtml;
    }

    $import_item_bank.on('click', '.submit-btn', function () {
      $importForm.find('.error').html('');

      if (importFormValid()) {
        $('body').mLoading({
          text: '正在导入...'
        });

        $.ajax({
          method: 'POST',
          dataType: 'json',
          url: '/admins/item_banks',
          data: new FormData($importForm[0]),
          processData: false,
          contentType: false,
          success: function (data) {
            $('body').mLoading('destroy');
            $import_item_bank.modal('hide');

            showMessageModal(buildResultMessage(data), function () {
              window.location.reload();
            })
          },
          error: function (res) {
            $('body').mLoading('destroy');
            var data = res.responseJSON;
            $importForm.find('.error').html(data.message);
          }
        })
      }
    })
  }
})