var angular = require('angular');
require('jsUtil');
require('../modules');
require('../../../commons/directives/$toast');
require('../services/userList');
require('../services/LinkerRemoteService');
require('../services/FavoriteLinkerService');

var module = angular.module('linker.controllers');

module.controller('LinkerDetailCtrl', function(
  $scope, $ionicActionSheet, $ionicPopup, $state, $toast,
  userList, FavoriteLinkerService, LinkerRemoteService, ConfigApp) {

  $scope.showPhone = ConfigApp.appTypeName === 'gjjoa' ? true : false;

  $scope.canAddToContact = !!navigator.contacts;
  $scope.barTheme = 'dark';

  $scope.$watch('linkerUser', function(user) {
    if(user && user.userName) {//要保证传过来的user是正确的user
      $scope.user = user;
      $scope.favorited = FavoriteLinkerService.isFavorite(user.userId);
    }
  });

  //$scope.userId 表示打开的联系人
  $scope.$watch('userId', function(userId) {
    if(!userId) {return;}
    if(!$scope.user || $scope.user.userId != userId) {
      $scope.loading = true;
      getUser(userId);

      $scope.favorited = FavoriteLinkerService.isFavorite(userId);
      $scope.loading = false;
    }
  });

  function getUser(userId) {
    var promise = userList.get(userId);

    promise.then(function(user) {
      $scope.user = user;
      $scope.loading = false;
    });
  }

  $scope.getRole = function() {
    return '办公室主任';
  };
  /**
   * 收藏联系人
   */
  $scope.favorite = function() {
    var linkman= [];
    linkman.push($scope.user.userId);
    return FavoriteLinkerService.add(linkman).then(function() {
      $scope.favorited = true;
      $toast.showLongCenter('联系人已收藏。');
    }, function() {
      $toast.showLongCenter('收藏联系人失败，请检查网络连接。');
    });

  };
  /**
   * 取消收藏联系人。
   */
  $scope.cancelFavorite = function() {
    return FavoriteLinkerService.remove($scope.user.userId).then(function() {
      $scope.favorited = false;
      $toast.showLongCenter('联系人已取消收藏。');
    }, function() {
      $toast.showLongCenter('取消收藏联系人失败，请检查网络连接。');
    });

  };

  /**
   * 添加到通讯录
   */
  $scope.addToContacts = function() {
    if (navigator.contacts) {
      var phoneNumbers = [];
      if ($scope.user.phone) {
        /*global ContactField*/
        phoneNumbers.push(new ContactField('mobile', $scope.user.phone, false));
      }
      var concat = navigator.contacts.create({
        displayName: $scope.user.userName,
        nickName: $scope.user.userName,
        phoneNumbers: phoneNumbers
      });

      concat.save(function() {
        $toast.showLongCenter('联系人已添加到通讯录中。');
      }, function() {
        $toast.showLongCenter('添加联系人到通讯录失败，请检查app是否有权限添加联系人到手机通讯录。');
      });
    }
  };

  $scope.getUserDuty = function(user) {
    // 如果有部门ID则显示oneMorePostDuty中的值
    // 如果没有部门id则显示原来的userDuty主职务
    if($scope.linkerDeptId && user.oneMorePostDuty) {
      return user.oneMorePostDuty[$scope.linkerDeptId];
    }
    return user.userDuty;
  };
});
