var angular = require('angular');
require('jsUtil');
require('../modules');
require('../services/LinkerService');

var module = angular.module('linker.directives.idtoname');

module.directive('idToName', function(LinkerService) {
  return {
    template: '<span>{{userOrDept.name}}</span>',
    restict: 'A',
    replace: true,
    scope: {
      id: '=id',
      type: '@type',
      showMe: '@showMe',
      showColon: '@showColon',
      showWholeName: '@showWholeName'
    },
    link: function(scope) {
      scope.userOrDept = {};
      /**
       * 显示人员名称。
       * 如果showMe为true，且id为当前登录人id，则显示'我'；否则显示名称。
       */
      function showUser() {
        if (scope.showMe && scope.showMe === 'true') {
          queryUserAndDisplay(LinkerService.currentUserId);
        } else {
          queryUserAndDisplay();
        }
      }

      function queryUserAndDisplay(userId) {
        LinkerService.queryUserById(scope.id).then(function(user) {
          scope.name = userId && userId === user.userId ? '我' : user.userName;
          if (scope.showColon && scope.showColon === 'true') {
            scope.name = scope.name + ':';
          }
          scope.userOrDept.name = scope.name;
        });
      }

      function showDept() {
        LinkerService.queryDeptById(scope.id).then(function(dept) {
          dept = jsUtil.isArray(dept) ? dept[0] : dept;
          if (scope.showWholeName === 'true') {
            scope.name = dept.title.slice(1);
          } else {
            scope.name = dept.text;
          }
          scope.userOrDept.name = scope.name;
        });
      }

      function displayUserOrDept() {
        if (!scope.id) {
          scope.name = '';
          return;
        }
        if (scope.type === 'user') {
          showUser();
        } else if (scope.type === 'dept') {
          showDept();
        }
      }

      scope.$watch('id', function() {
        displayUserOrDept();
      });

      displayUserOrDept();
    }
  };
});
