$(document).on('turbolinks:load', function() {
  if ($('body.admins-upgrade-notices-index-page').length > 0) {
    window.upgradeNoticeForm = function(clazz) {
      var $modal = $('.modal.admin-' + clazz + '-upgrade-notice-modal');
      var $form = $modal.find('form.admin-' + clazz + '-upgrade-notice-form');

      $form.validate({
        errorElement: 'span',
        errorClass: 'danger text-danger',
        rules: {
          'upgrade_notice[title]': {
            required: true
          },
          'upgrade_notice[content]': {
            required: true
          },
          'upgrade_notice[start_at]': {
            required: true
          },
          'upgrade_notice[end_at]': {
            required: true
          }
        }
      });

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

        if ($form.valid()) {
          var url = $form.attr('action');
          var newDate = new Date();
          var begin_time = Date.parse($('.' + clazz +'_start_at').val());
          var end_time = Date.parse($('.' + clazz +'_end_at').val());
          if (begin_time < newDate) {
            $('.' + clazz +'_end_at').addClass('danger text-danger');
            $form.find('.error').html('开始时间应大于当前时间');
            return false
          } else if (end_time < newDate) {
            $form.find('.error').html('结束时间应大于当前时间');
            $('.' + clazz +'_end_at').addClass('danger text-danger');
            return false
          } else if (end_time < begin_time) {
            $form.find('.error').html('结束时间应大于开始时间');
            $('.' + clazz +'_end_at').addClass('danger text-danger');
            return false
          }

          $.ajax({
            method: clazz == 'create' ? 'POST' : 'PUT',
            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);
            }
          });
        }
      });
    }

    var timeOptions = {
      autoclose: 1,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii',
      minuteStep: 10
    };

    $(".create_start_at").datetimepicker(timeOptions)
    $(".create_end_at").datetimepicker(timeOptions)
    upgradeNoticeForm("create");
  }
});