require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';

  /**
   * Handle the notification email interval.
   */
  $(document).off('change.notificationEmailInterval');
  $(document).on('change.notificationEmailInterval', '.notificationEmailInterval', function() {
    var intervalSelect = $(this);
    var notification = new XWiki.widgets.Notification("您的设置正在保存中......", 'inprogress');
    var serviceURL = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService',
      XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
    var target = $('.notifEmailPreferences').attr('data-target');
    var targetUser = target === 'user' ? $('.notifEmailPreferences').attr('data-user') : '';
    $.post(serviceURL, {
      'action': 'setInterval',
      'interval': intervalSelect.val(),
      'target': target,
      'user': targetUser,
      'csrf': xm.form_token
    }).then(data => {
      notification.replace(new XWiki.widgets.Notification("已保存！", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("保存您的设置失败", 'error'));
    });
  });

  /**
   * Handle the include diff in email setting
   */
  $(document).off('change.notificationEmailDiffType');
  $(document).on('change.notificationEmailDiffType', '.notificationEmailDiffType', function() {
    var diffTypeSelect = $(this);
    var notification = new XWiki.widgets.Notification("您的设置正在保存中......", 'inprogress');
    var serviceURL = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService',
      XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
    var target = $('.notifEmailPreferences').attr('data-target');
    var targetUser = target === 'user' ? $('.notifEmailPreferences').attr('data-user') : '';
    $.post(serviceURL, {
      'action': 'setDiffType',
      'diffType': diffTypeSelect.val(),
      'target': target,
      'user': targetUser,
      'csrf': xm.form_token
    }).then(data => {
      notification.replace(new XWiki.widgets.Notification("已保存！", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("保存您的设置失败", 'error'));
    });
  });
});
