require(['jquery', 'xwiki-meta'], function ($, xm) {
  // Make sure the change listener is not added twice.
  $(document).off('change.notificationAutoWatchMode');
  $(document).on('change.notificationAutoWatchMode', '.notificationAutoWatchMode', function() {
    var input = $(this);
    var target = input.data('target') === 'wiki' ? 'wiki' : 'user';
    var notification = new XWiki.widgets.Notification("您的设置正在保存中......", 'inprogress');
    var url = new XWiki.Document('NotificationPreferenceService', 'XWiki.Notifications.Code').getURL('get',
      'outputSyntax=plain');
    $.post(url, {
      action: 'setAutoWatchMode',
      mode: input.val(),
      target: target,
      user: input.data('user'),
      csrf: xm.form_token
    }).then(() => {
      notification.replace(new XWiki.widgets.Notification("已保存！", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("保存您的设置失败", 'error'));
    });
  });
});
