var angular = require('angular');
require('ngIonic');
require('../modules');
var module = angular.module('linker.directives');

module.directive('viewLinkerDetail', function($rootScope, $ionicModal) {
  var $newScope, createdLinkerModal = false;

  function createScope() {
    var $newScope = $rootScope.$new(true);

    $newScope.goBack = function() {
      $newScope.linkerModal.remove();
      $newScope.linkerModal = null;
      createdLinkerModal = false;
    };

    return $newScope;
  }

  function createLinkerModal() {
    $ionicModal.fromTemplateUrl('views/linker/modal/linkerdetail.modal.tpl.html', function(modal) {
      $newScope.linkerModal = modal;
      $newScope.linkerModal.show();
    }, {
      scope: $newScope,
      animation: 'slide-in-up'
    });
  }

  return {
    restrict: 'A',
    link: function($scope, element, attr) {
      element.on('click', function() {
        if (!$newScope) {
          $newScope = createScope();
        }
        //兼容之前的，没有user时，再给userId
        $newScope.linkerUser = $scope.$eval(attr.viewLinkerDetailUser);
        // 传递当前的部门id进来，用于判断应该显示什么职务
        $newScope.linkerDeptId = $scope.$eval(attr.viewLinkerDetailDeptid); 

        if(!$newScope.linkerUser || !$newScope.linkerUser.userName) {
          $newScope.userId = attr.viewLinkerDetail;
        } else {
          $newScope.userId = null;
        }

        createLinkerModal();//每次打开新的

        // if (!createdLinkerModal) {
        //   createdLinkerModal = true;
        //   createLinkerModal();
        // }

        // if ($newScope.linkerModal) {
        //   $newScope.linkerModal.show();
        // }
      });
    }
  };
});
