(function (app) {
  app
    .controller('CrearStakeholderController', function ($scope, $http, $rootScope, SweetAlert, spsservice, $uibModal, $location, $timeout, $interval, $route) {

      $scope.bloqueo = false;
      $scope.funcionarioPublico = false;

      // $scope.stakeholder.Operacion = [];


      //   $scope.obtenerComunasUsuario = function (zona) {
      //     debugger;
      //     $rootScope.comunasUsuarioData = $rootScope.comunasUsuario.filter(x => x.Zona == zona.zona || x.Zona == "");
      // }





      //Inicializar variable para asignar zona por defecto al tener solo 1
      $scope.stakeholder = new Object();
      if ($rootScope.zonasUsuario.length == 1) {
        $scope.stakeholder.Operacion = $rootScope.zonasUsuario[0].zona;
      }


      // $scope.stakeholder = [];
      $scope.crearStakeholder = function () {
        $rootScope.bloqueopantalla = true;
        $rootScope.refreshToken();


        SweetAlert.swal({
            title: "¿Está seguro(a) de crear el Stakeholder?",
            text: "No debe actualizar la página hasta que el proceso haya finalizado.",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#16AB39",
            confirmButtonText: "Si, agregar Stakeholder!",
            cancelButtonText: "Cancelar",
            closeOnConfirm: true
          },
          function (isConfirm) {
            if (isConfirm) {

              var url = "lists/getbytitle('Stakeholder')/items";
              var data = {
                '__metadata': {
                  'type': 'SP.Data.StakeholderListItem'
                },
                'Title': $scope.stakeholder.Title,
                'Telefono': $scope.stakeholder.Telefono,
                'Email': $scope.stakeholder.Email,
                'Rol': $scope.stakeholder.Rol,
                'DireccionUrl': $scope.stakeholder.DireccionUrl,
                'Tipoo': $scope.stakeholder.Tipoo.Valor,
                'Descripcion': $scope.stakeholder.Descripcion,
                'Organizacion': $scope.person.selected == null ? "" : $scope.person.selected.Title,
                'Operacion': $scope.stakeholder.Operacion.zona == null ? $scope.stakeholder.Operacion : $scope.stakeholder.Operacion.zona,
                'Comuna': $scope.stakeholder.Comuna.Comuna,
                'OtraComuna': $scope.stakeholder.ComunaOtra,
                'Categoria': $scope.stakeholder.Categoria == null ? "" : $scope.stakeholder.Categoria.Valor,
                'Relevancia': $scope.stakeholder.Relevancia
              };

              spsservice.post_data(url, data).then(function (grabaStakeholder) {
                if (grabaStakeholder.d != null) {
                  $route.reload();
                  $rootScope.ObtenerStackeholders();
                  SweetAlert.swal("Stakeholder creado.", "", "success");
                  $rootScope.bloqueopantalla = false;
                  $scope.bloqueo = true;
                }
              });
            } else {
              $rootScope.bloqueopantalla = false;
            }
          })
      }

      $scope.obtenerCategorias = function (tipoo) {
        debugger;
        $scope.categoriaStakeholderFilter = $rootScope.parametros.filter(x => x.Title == 'CategoriaStakeholder' && x.RelacionadoId == tipoo.ID);

        if (tipoo.Valor == "Otros") {
          $scope.stakeholder.Categoria = "sin categoria";
        }



      }







      debugger

      $scope.disabled = undefined;
      $scope.searchEnabled = undefined;

      $scope.setInputFocus = function () {
        $scope.$broadcast('UiSelectDemo1');
      };

      $scope.enable = function () {
        $scope.disabled = false;
      };

      $scope.disable = function () {
        $scope.disabled = true;
      };

      $scope.enableSearch = function () {
        $scope.searchEnabled = true;
      };

      $scope.disableSearch = function () {
        $scope.searchEnabled = false;
      };

      $scope.clear = function () {
        $scope.person.selected = undefined;
        $scope.address.selected = undefined;
        $scope.country.selected = undefined;
      };

      $scope.someGroupFn = function (item) {

        if (item.name[0] >= 'A' && item.name[0] <= 'M')
          return 'From A - M';

        if (item.name[0] >= 'N' && item.name[0] <= 'Z')
          return 'From N - Z';

      };

      $scope.firstLetterGroupFn = function (item) {
        return item.name[0];
      };

      $scope.reverseOrderFilterFn = function (groups) {
        return groups.reverse();
      };

      $scope.personAsync = {
        selected: "wladimir@email.com"
      };
      $scope.peopleAsync = [];

      $timeout(function () {
        $scope.peopleAsync = [{
            name: 'Adam',
            email: 'adam@email.com',
            age: 12,
            country: 'United States'
          },
          {
            name: 'Amalie',
            email: 'amalie@email.com',
            age: 12,
            country: 'Argentina'
          },
          {
            name: 'Estefanía',
            email: 'estefania@email.com',
            age: 21,
            country: 'Argentina'
          },
          {
            name: 'Adrian',
            email: 'adrian@email.com',
            age: 21,
            country: 'Ecuador'
          },
          {
            name: 'Wladimir',
            email: 'wladimir@email.com',
            age: 30,
            country: 'Ecuador'
          },
          {
            name: 'Samantha',
            email: 'samantha@email.com',
            age: 30,
            country: 'United States'
          },
          {
            name: 'Nicole',
            email: 'nicole@email.com',
            age: 43,
            country: 'Colombia'
          },
          {
            name: 'Natasha',
            email: 'natasha@email.com',
            age: 54,
            country: 'Ecuador'
          },
          {
            name: 'Michael',
            email: 'michael@email.com',
            age: 15,
            country: 'Colombia'
          },
          {
            name: 'Nicolás',
            email: 'nicole@email.com',
            age: 43,
            country: 'Colombia'
          }
        ];
      }, 3000);

      $scope.counter = 0;
      $scope.onSelectCallback = function (item, model) {
        $scope.counter++;
        $scope.eventResult = {
          item: item,
          model: model
        };
      };

      $scope.removed = function (item, model) {
        $scope.lastRemoved = {
          item: item,
          model: model
        };
      };

      $scope.tagTransform = function (newTag) {
        var item = {
          name: newTag,
          email: newTag.toLowerCase() + '@email.com',
          age: 'unknown',
          country: 'unknown'
        };

        return item;
      };

      $scope.peopleObj = {
        '1': {
          name: 'Adam',
          email: 'adam@email.com',
          age: 12,
          country: 'United States'
        },
        '2': {
          name: 'Amalie',
          email: 'amalie@email.com',
          age: 12,
          country: 'Argentina'
        },
        '3': {
          name: 'Estefanía',
          email: 'estefania@email.com',
          age: 21,
          country: 'Argentina'
        },
        '4': {
          name: 'Adrian',
          email: 'adrian@email.com',
          age: 21,
          country: 'Ecuador'
        },
        '5': {
          name: 'Wladimir',
          email: 'wladimir@email.com',
          age: 30,
          country: 'Ecuador'
        },
        '6': {
          name: 'Samantha',
          email: 'samantha@email.com',
          age: 30,
          country: 'United States'
        },
        '7': {
          name: 'Nicole',
          email: 'nicole@email.com',
          age: 43,
          country: 'Colombia'
        },
        '8': {
          name: 'Natasha',
          email: 'natasha@email.com',
          age: 54,
          country: 'Ecuador'
        },
        '9': {
          name: 'Michael',
          email: 'michael@email.com',
          age: 15,
          country: 'Colombia'
        },
        '10': {
          name: 'Nicolás',
          email: 'nicolas@email.com',
          age: 43,
          country: 'Colombia'
        }
      };

      $scope.person = {};

      $scope.person.selectedValue = $scope.peopleObj[3];
      $scope.person.selectedSingle = 'Samantha';
      $scope.person.selectedSingleKey = '5';
      // To run the demos with a preselected person object, uncomment the line below.
      //$scope.person.selected = $scope.person.selectedValue;

      //   $scope.people = [
      //     { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
      //     { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
      //     { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
      //     { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
      //     { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
      //     { name: 'Samantha',  email: 'samantha@email.com',  age: 30, country: 'United States' },
      //     { name: 'Nicole',    email: 'nicole@email.com',    age: 43, country: 'Colombia' },
      //     { name: 'Natasha',   email: 'natasha@email.com',   age: 54, country: 'Ecuador' },
      //     { name: 'Michael',   email: 'michael@email.com',   age: 15, country: 'Colombia' },
      //     { name: 'Nicolás',   email: 'nicolas@email.com',    age: 43, country: 'Colombia' }
      //   ];



      //Obtener Organizaciones            
      spsservice.get_type('lists/getbytitle', 'Organizaciones', "/Items?$select=ID,Title,Nacionalidad,Categoria&$top=5000").then(function (rOrganizaciones) {
        if (rOrganizaciones.d.results.length > 0) {

          $rootScope.organizacionesData = rOrganizaciones.d.results;

          $scope.people = $rootScope.organizacionesData;

          $scope.availableColors = ['Red', 'Green', 'Blue', 'Yellow', 'Magenta', 'Maroon', 'Umbra', 'Turquoise'];

          $scope.singleDemo = {};
          $scope.singleDemo.color = '';
          $scope.multipleDemo = {};
          $scope.multipleDemo.colors = ['Blue', 'Red'];
          $scope.multipleDemo.colors2 = ['Blue', 'Red'];
          $scope.multipleDemo.selectedPeople = [$scope.people[5], $scope.people[4]];
          $scope.multipleDemo.selectedPeople2 = $scope.multipleDemo.selectedPeople;
          $scope.multipleDemo.selectedPeopleWithGroupBy = [$scope.people[8], $scope.people[6]];
          $scope.multipleDemo.selectedPeopleSimple = ['samantha@email.com', 'wladimir@email.com'];
          $scope.multipleDemo.removeSelectIsFalse = [$scope.people[2], $scope.people[0]];

        }
      });
      //Fin obtener Organizaciones






      $scope.appendToBodyDemo = {
        remainingToggleTime: 0,
        present: true,
        startToggleTimer: function () {
          var scope = $scope.appendToBodyDemo;
          var promise = $interval(function () {
            if (scope.remainingTime < 1000) {
              $interval.cancel(promise);
              scope.present = !scope.present;
              scope.remainingTime = 0;
            } else {
              scope.remainingTime -= 1000;
            }
          }, 1000);
          scope.remainingTime = 3000;
        }
      };

      $scope.address = {};
      $scope.refreshAddresses = function (address) {
        var params = {
          address: address,
          sensor: false
        };
        return $http.get(
          'http://maps.googleapis.com/maps/api/geocode/json', {
            params: params
          }
        ).then(function (response) {
          $scope.addresses = response.data.results;
        });
      };

      $scope.addPerson = function (item, model) {
        if (item.hasOwnProperty('isTag')) {
          delete item.isTag;
          $scope.people.push(item);
        }
      }







    })

}(angular.module('spsmodule')));