require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';
  $(function() {
    /**
     * Save the new user status.
     */
    var changeUserStatus = function (action) {
      var notification = new XWiki.widgets.Notification("\u4FDD\u5B58...", 'inprogress');
      var url = new XWiki.Document(XWiki.Model.resolve('XWiki.Notifications.Code.NotificationPreferenceService', XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
      $.post(url, {
        'action': action,
        'csrf': xm.form_token,
        'user': XWiki.Model.serialize(xm.documentReference),
        'target': 'user'
      }).then(() => {
        notification.hide();
        new XWiki.widgets.Notification("\u5B8C\u6210", 'done');
        if (action == 'watchUser') {
          $('.notificationWatchUserNotFollowing').addClass('hidden');
          $('.notificationWatchUserFollowing').removeClass('hidden')
        } else {
          $('.notificationWatchUserFollowing').addClass('hidden');
          $('.notificationWatchUserNotFollowing').removeClass('hidden');
        }
      }).catch(() => {
        notification.hide();
        new XWiki.widgets.Notification("\u4FDD\u5B58\u901A\u77E5\u8BBE\u7F6E\u65F6\u51FA\u9519", 'error');
      });
    };

    var setUserDisableStatus = function(action) {
      var notification = new XWiki.widgets.Notification("\u4FDD\u5B58...", 'inprogress');
      var url = new XWiki.Document(XWiki.Model.resolve('XWiki.XWikiUserProfileSheet', XWiki.EntityType.DOCUMENT)).getURL('get', 'outputSyntax=plain');
      $.post(url, {
        'action': action,
        'csrf': xm.form_token,
        'userId': XWiki.Model.serialize(xm.documentReference)
      }).then(data => {
        notification.hide();
        if (data.success) {
          new XWiki.widgets.Notification("\u5B8C\u6210", 'done');
          if (action == 'disable') {
            $('#disable').addClass('hidden');
            $('#enable').removeClass('hidden');
          } else {
            $('#disable').removeClass('hidden');
            $('#enable').addClass('hidden');
          }
        } else {
          new XWiki.widgets.Notification("\u4FDD\u5B58\u7528\u6237\u72B6\u6001\u65F6\u51FA\u9519", 'error');
        }
      }).catch(() => {
        notification.hide();
        new XWiki.widgets.Notification("\u4FDD\u5B58\u7528\u6237\u72B6\u6001\u65F6\u51FA\u9519", 'error');
      });
    };

    $('#disable').on('click', function(event) {
      setUserDisableStatus('disable');
    });

    $('#enable').on('click', function(event) {
      setUserDisableStatus('enable');
    });

    /**
     * DOM events
     */
    $('.notificationWatchUserAdd').on('click', function(event) {
      changeUserStatus('watchUser');
    });
    $('.notificationWatchUserRemove').on('click', function(event) {
      changeUserStatus('unwatchUser');
    });
  });
});
