$(document).on('turbolinks:load', function () {
  if ($('body.admins-job-classifies-index-page').length > 0) {
    var table = $("#admin_job_classify_table");
    table.treetable({
      expandable: true,
      sortable: {
        axis: 'y'
      },
      onNodeCollapse: function () {
        var node = this;
        table.treetable("unloadBranch", node);
      },
      onNodeExpand: function () {
        var node = this;
        $.ajax({
          async: false,
          url: "/admins/job_classifies/" + node.id + "/children"
        }).done(function (html) {
          if (html === "") {
            $.notify({
              message: '暂无分类'
            });
          } else {
            var rows = $(html).filter("tr");
            table.treetable("loadBranch", node, rows);
          }
        });
      }
    });

    Sortable.create($("#admin_job_classify_table tbody").get(0), {
      onEnd: function (evt) {
        var $item = $(evt.item)
        var node_id = $item.data("tt-id");
        $.ajax({
          data: {
            parent_id: $item.hasClass('root-node') ? "" : $item.prev().data("parent-id"), // 拖放父级结点不需要更新parent
            // 如果拖放到第一位，确保position最小值为 1
            position: $item.prev().hasClass('root-node') && $item.hasClass('root-node') == false || $item.prev().data("position") === undefined ? 1 : parseInt($item.prev().data("position")) + 1
          },
          type: "PUT",
          url: "/admins/job_classifies/" + $item.data("tt-id") + "/change",
          success: function () {
            $.notify({
              message: '操作成功'
            });
            window.location.reload()
          }
        })
      }
    });

     // ============== 新建 ===============
     var $modal = $('.modal.admin-create-job_classifies-modal');
     var $form = $modal.find('form.admin-create-job_classifies-form');
     var $nameInput = $form.find('input[name="name"]');

     $form.validate({
       errorElement: 'span',
       errorClass: 'danger text-danger',
       rules: {
         name: {
           required: true
         }
       }
     });

     // modal ready fire
     $modal.on('show.bs.modal', function () {
       $nameInput.val('');
     });

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

       if ($form.valid()) {
         var url = $form.data('url');

         $.ajax({
           method: 'POST',
           dataType: 'json',
           url: url,
           data: $form.serialize(),
           success: function () {
             $.notify({
               message: '创建成功'
             });
             $modal.modal('hide');

             setTimeout(function () {
               window.location.reload();
             }, 500);
           },
           error: function (res) {
             var data = res.responseJSON;
             $form.find('.error').html(data.message);
           }
         });
       }
     });
    //  编辑

     $('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-job_classifies-modal', function () {
       var $modal = $('.modal.admin-edit-job_classifies-modal');
       var $form = $modal.find('form.admin-edit-job_classifies-form');

       $form.validate({
         errorElement: 'span',
         errorClass: 'danger text-danger',
         rules: {
           'job_classify[name]': {
             required: true,
             maxlength: 20
           }
         }
       });

       $modal.on('click', '.submit-btn', submit_edit_form);

       $form.find("#job_classify_name").keydown(function (e) {
         var ev = e || event;
         var keycode = ev.which || ev.keyCode;
         if (keycode == 13) {
           submit_edit_form();
           return false;
         }
       });

       function submit_edit_form() {
         $form.find('.error').html('');
         var url = $form.attr('action');
         console.log(url)

         if ($form.valid()) {
           $.ajax({
             method: 'PATCH',
             dataType: 'script',
             url: url,
             data: $form.serialize()
           });
         }
       }
     });
  }
})