$(document).on("turbolinks:load", function() {
  if ($("body.admins-hack-imports-index-page").length > 0) {
    // 导入题库
    var $import_hack_import = $(".modal.admin-import-hack-modal");
    var $importForm = $import_hack_import.find(
      "form.admin-import-hack-form"
    );

    $import_hack_import.on("show.bs.modal", function() {
      resetFileInputFunc($import_hack_import.find(".upload-file-input"));
      $import_hack_import.find(".file-names").html("选择文件");
      $import_hack_import.find(".upload-file-input").trigger("click");
    });
    $import_hack_import.on("change", ".upload-file-input", function(e) {
      var file = $(this)[0].files[0];
      $import_hack_import
        .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_hack_import.on("click", ".submit-btn", function() {
      $importForm.find(".error").html("");

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

        $.ajax({
          method: "POST",
          dataType: "json",
          url: "/admins/hack_imports",
          data: new FormData($importForm[0]),
          processData: false,
          contentType: false,
          success: function(data) {
            $("body").mLoading("destroy");
            $import_hack_import.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);
          },
        });
      }
    });
  }
});