// NO WATER ! 
// @ELIMINADO EL 'INTENTO DE PAGINA WEB' NORMA ANTERIOR.

var appnormas = angular.module('appnormas',['ui.bootstrap','oitozero.ngSweetAlert','platanus.rut','ngCookies','ngSanitize']); 

appnormas.controller('busquedactrl',['$scope','$http','SweetAlert','$filter','$uibModal','$cookies', '$sce',function($scope,$http,SweetAlert,$filter,$uibModal,$cookies,$sce){

        $scope.region = false;
        $scope.comuna = false;
        $scope.rubro  =  false;
        $scope.producto = false;
        $scope.sector  = false;
        $scope.aglutinadores = [];

        $scope.arrSeleccion = {};
        $scope.mostrarloadingnormas =false;


        $scope.porcentajeIndap = {
          'CA': 0.95, 
          'FR': 0.9, 
          'GA': 0.95,
          'AP': 0.95,
        }

        $scope.rubrosMultiItem = [25,24,29,30]; //BO, OV, GP (Caprino), GM (Camelido)

        $scope.espacioBr = function(obj){
            tmp = obj.replace(' de ', ' ');
            tmp = tmp.replace(' ', '<br>');
            return $sce.trustAsHtml(tmp);
        };

        $scope.obtenerSector = function(){

                $scope.arrSeleccion = {};
                $scope.sector  = false;
                $scope.region = false;
                $scope.comuna = false;
                $scope.rubro  =  false;
                $scope.producto = false;
                $scope.arrNormas = false;
                //console.log(sector);
                        $http({
                          method: 'GET',
                          url: domain + '/api/obtener/sectores',
                           headers: { 'Authorization': authorization }
                            }).then(function successCallback(response) {
                            // this callback will be called asynchronously
                            // when the response is available
                            $scope.arrSectores = response.data;
                            $scope.sector = true;
                            //$scope.arrSeleccion.sector = sector;

                          }, function errorCallback(response) {
                            // called asynchronously if an error occurs
                            // or server returns response with an error status.
                          });
        };

        $scope.obtenerSector();
        $scope.obtenerRegion = function(sector){
          $scope.reiniciarMultiItem();
          $scope.arrSeleccion = {};
          $scope.sector  = true;
          $scope.region = false;
          $scope.comuna = false;
          $scope.rubro  =  false;
          $scope.producto = false;
          $scope.arrNormas = false;
          //console.log(sector);
          $http({
            method: 'GET',
            url: domain + '/api/obtener/regionesPorSector/'+sector,
              headers: { 'Authorization': authorization }
              }).then(function successCallback(response) {
              // this callback will be called asynchronously
              // when the response is available
              //console.log(response.data);
              $scope.arrRegiones = response.data;
              $scope.region = true;
              $scope.arrSeleccion.sector = sector;

            }, function errorCallback(response) {
              // called asynchronously if an error occurs
              // or server returns response with an error status.
            });
        };

        $scope.obtenerComuna = function(idregion){
          $scope.reiniciarMultiItem();
                $scope.comuna = false;
                $scope.rubro = false;
                $scope.producto = false;
                $scope.arrSeleccion.region = idregion;
                $scope.arrSeleccion.variedad = false;
                $scope.arrSeleccion.comuna = false;
                $scope.arrNormas = false;
                //console.log(idregion);
                        $http({
                          method: 'GET',
                          url: domain + '/api/obtener/comunasPorRegion/'+idregion+'/sector/'+$scope.arrSeleccion.sector,
                           headers: { 'Authorization': authorization }
                            }).then(function successCallback(response) {
                            $scope.arrComunas = response.data;
                            $scope.comuna = true;
                          }, function errorCallback(response) {
                            // called asynchronously if an error occurs
                            // or server returns response with an error status.
                          });
        };
        $scope.obtenerRubro = function(idcomuna){
          $scope.reiniciarMultiItem();
                $scope.rubro = false;
                $scope.producto = false;
                $scope.arrSeleccion.comuna = idcomuna;
                $scope.arrSeleccion.rubro = false;
                $scope.arrSeleccion.variedad = false;
                $scope.arrSeleccion.arrVariedad = [];
                $scope.arrNormas = false;
                //console.log(idcomuna);
                  $http({
                    method: 'GET',
                    url: domain + '/api/obtener/rubrosPorComuna/'+idcomuna+'/sector/'+$scope.arrSeleccion.sector,
                    headers: { 'Authorization': authorization }
                    }).then(function successCallback(response) {
                      $scope.arrRubros = response.data;
                      $scope.rubro = true;
                    }, function errorCallback(response) {
                      // called asynchronously if an error occurs
                      // or server returns response with an error status.
                    });
        };
        $scope.obtenerProducto = function(idrubro,objRubro){
                $scope.producto = false;
                $scope.arrSeleccion.rubro = idrubro;
                $scope.arrSeleccion.nombreRubro = objRubro.nombre;
                $scope.arrSeleccion.multiItem = (($scope.rubrosMultiItem).indexOf(idrubro) !== -1) ? true : false;
                $scope.arrSeleccion.variedad = false;
                $scope.arrNormas = false;
                //console.log(idrubro);
                        $http({
                          method: 'GET',
                          url: domain + '/api/obtener/productosPorRubro/'+idrubro+'/comuna/'+$scope.arrSeleccion.comuna,
                           headers: { 'Authorization': authorization }
                            }).then(function successCallback(response) {
                            $scope.arrProductos = response.data;
                            $scope.producto = true;
                          }, function errorCallback(response) {
                            // called asynchronously if an error occurs
                            // or server returns response with an error status.
                          });
        };

        $scope.obtenerNormas = function(idvariedad,objVariedad){
            //$scope.producto = false;
            $scope.arrNormas = false;
            $scope.showPaso3 = false;
            $scope.showPaso4 = false;
            $scope.arrSeleccion.variedad = idvariedad;
            $scope.mostrarloadingnormas = true;
            $scope.arrSeleccion.norma = {};
            $scope.arrSeleccion.normaCompania = {}; //para multiItem
            $scope.objVariedad = objVariedad;
            $scope.multiItem = false;
            //$scope.scroll();
            $scope.scroll();
            $http({
              method: 'POST',
              url: domain + '/api/obtener/normas',
              headers: { 'Authorization': authorization  },
              data: {idcomuna:$scope.arrSeleccion.comuna,items:[{"idvariedad":idvariedad,cantidadasegurada:1}]}

                }).then(function successCallback(response) {
                // this callback will be called asynchronously
                // when the response is available
                //console.log(response.data);
                $scope.arrNormas = response.data.normas;
                angular.forEach(response.data.normas, function(value, key) {
                  $scope.primeraNorma = value;
                  angular.forEach(value, function(value, key) {
                    $scope.moneda = key;
                    $scope.unidad = value[0]["unidad"];
                    $scope.precio = parseFloat(value[0]["precio"]);
                    if(!isNaN(value[0]["rendimientoinferior"])){
                      $scope.rendimientoinferior = parseFloat(value[0]["rendimientoinferior"]);
                      $scope.rendimientosuperior = parseFloat(value[0]["rendimientosuperior"]);
                      $scope.rendimiento = parseFloat(value[0]["rendimientoinferior"]);
                    }else{
                      $scope.rendimientoinferior = 0;
                      $scope.rendimientosuperior = 0;
                    }
                    return;
                  });
                  return;
                });
                //$scope.primeraNorma = response.data.normas[0];
                $scope.arrVectores  = response.data.vectores;
                $scope.mostrarloadingnormas = false;
                $scope.scroll();
                //$scope.producto = true;
              }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
              });


        }

        $scope.obtenerMultiNormas = function(){
          //$scope.producto = false;
          $scope.showPaso3 = false;
          $scope.showPaso4 = false;
          $scope.multiItem = true;
          $scope.mostrarloadingnormas = true;
          $scope.arrSeleccion.norma = {};
          $scope.arrSeleccion.normaCompania = {}; // para MultiItem
          //$scope.scroll();
          variedades = [];
          angular.forEach($scope.arrSeleccion.arrVariedad, function(value, key){
            //console.log(value);
            variedades.push({"idvariedad":value.idvariedad,"cantidadasegurada":value.cantidadasegurada});
            $scope.objVariedad = value.variedad;
          });

          //console.log($scope.objVariedad);
          $http({
                method: 'POST',
                url: domain + '/api/obtener/normas',
                headers: { 'Authorization': authorization  },
                data: {idcomuna:$scope.arrSeleccion.comuna,items:variedades,'arbol':'multiitem'}

                }).then(function successCallback(response) {
                  $scope.arrNormas = response.data.normas;
                  $scope.primeraNorma = response.data.normas[0];
                  $scope.arrVectores  = response.data.vectores;
                  $scope.mostrarloadingnormas = false;
                }, function errorCallback(response) {
                  // called asynchronously if an error occurs
                  // or server returns response with an error status.
                }).then(function(){
                  $scope.scroll();   
                });
                        

      }
        $scope.reiniciarMultiItem = function(){
          if(typeof $scope.arrSeleccion.arrVariedad === 'undefined')
            return;
          if($scope.arrSeleccion.arrVariedad.length == 0)
            return;
          SweetAlert.warning("Acción interrumpida", "Para modificar la selección debes 'Reiniciar Simulación'. ");
          $scope.scroll();
          throw 'Continuar simulando';
        }

        $scope.agregarItem = function(idvariedad, objVariedad){
          $scope.arrSeleccion.cantidadAseguradaItem = 0;
          $scope.arrSeleccion.variedad = false;
          $scope.arrSeleccion.objVariedad = objVariedad;

          $scope.arrSeleccion.arrVariedad.push({"cantidadasegurada":1, idvariedad: idvariedad, variedad:objVariedad});
          $scope.scroll();
            /*$scope.modalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'agregarItem.html',
                  //controller: 'modalAgregarItem',
                  size: 'md',
                  backdrop: 'static',
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  scope: $scope,
                  //resolve: {
                  //data: function () {
                  //    return {objVariedad: objVariedad, arrSeleccion: $scope.arrSeleccion};
                  //  }
                  //}
              });
              */
        }
        /*
        $scope.cancel = function () {
          $scope.modalInstance.close(); //.dismiss('cancel');
        };

        $scope.agregarItemSeleccion = function(objVariedad){
          $scope.errorCantidadAseguradaItem='';
          if($scope.arrSeleccion.cantidadAseguradaItem <= 0 || !angular.isNumber($scope.arrSeleccion.cantidadAseguradaItem)){
            $scope.errorCantidadAseguradaItem = 'Debe ingresar la cantidad asegurada para continuar.';
            return;
          }
          
          $scope.arrSeleccion.arrVariedad.push({"cantidadasegurada":$scope.arrSeleccion.cantidadAseguradaItem, idvariedad: objVariedad.id, variedad:objVariedad});
          $scope.cancel();
        }
        */

        $scope.quitarVariedadItem = function(index){
          $scope.arrSeleccion.arrVariedad.splice(index,1);

        }

        $scope.scroll = function(){
          //console.log($(window). innerHeight() );
          //console.log($(document).height() );
          //await sleep(1500);
          //pixeles = $(document).height() - $(window).innerHeight();
          //if(pixeles > 0)
          $("html, body").animate({ scrollTop: $(document).height() }, 1000);  
        }

        $scope.obtenerAglutinador = function(){
          $http({
              method: 'GET',
              url: domain + '/aglutinadores',
              headers: { 'Authorization': authorization },
              }).then(function successCallback(response) {             
                 //Acá va el Push en response.data  
                //console.log(response.data);

                var arrayAglutinadores =[ {
                    rutaglutinador: 0,
                    dvaglutinador: '0',
                    nombreaglutinador: 'Sin Aglutinador',
                    descripcion: 'Sin Aglu',
                    estado: 1,        
                  }];  

                for (i=0;i<response.data.length;i++) {
                  arrayAglutinadores.push(response.data[i]);
                }     

                $scope.aglutinadores = arrayAglutinadores; 
              }, function errorCallback(response) {            
                  console.log(response);
                });

        }
        $scope.obtenerAglutinador();

        $scope.modalPorcentaje = function(nombre){

          var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: nombre +'.html',
                        controller: 'modalctrl',
                        size: 'md',
                        resolve: {
                          data: function () {
                            return {aglutinadores: $scope.aglutinadores};
                          }
                        }
          });
        }

        $scope.newSimular = function(){

          
          var normasSeleccionadas = 0;
          //console.log($scope.arrSeleccion.norma);
          if($scope.multiItem){
            angular.forEach($scope.arrSeleccion.normaCompania, function(value, key) {
              
                  normasSeleccionadas++;
            });
          }
          console.log($scope.arrNormas);
          console.log($scope.primeraNorma);
          angular.forEach($scope.arrSeleccion.norma, function(value, key) {
              normasSeleccionadas++;
          });

          if(normasSeleccionadas <= 0){
            SweetAlert.warning("Advertencia", "Seleccione una norma de suscripción a simular");
            return;
          } 
          
          
            $scope.mostrarloadingca = true;
            $scope.showPaso3 = true;
            $scope.showPaso4 = false;
            //Hay que hacer autoscroll hasta abajo...
            $scope.scroll();
              $scope.codigoRubro = $scope.objVariedad.idGenProducto.idGenRubro.codigo;
              $scope.codigoSector = $scope.objVariedad.idGenProducto.idGenRubro.idGenSector.codigo;
            //$scope.montoasegurado = 0; //?????    
            //$scope.cantidadasegurada = 0;
            //$scope.aglutinadores = [];
            $scope.conCalibre    = false;
            $scope.conForestal   = false;
            $scope.errorSumaCalibre = false;

            //console.log($scope.codigoRubro);
            //console.log($scope.codigoSector);
            $scope.nombre = "";
            switch($scope.codigoSector){
              case 'CA':
              case 'FL':
              case 'FR':
                $scope.nombre="Hectáreas a asegurar";
                switch($scope.codigoRubro){
                    case 'PO':
                    case 'UV':
                    case 'UM':
                        $scope.conCalibre = true;
                    break;

                }
              break;
              case 'GA':
              case 'AP':
                 $scope.nombre ='Cabezas a asegurar';
                 if($scope.codigoRubro =='AP'){
                    $scope.nombre ='Colmenas a asegurar';
                 }
              break;
              case 'FO': //forestal
                $scope.conForestal = true; 
                $scope.nombre = 'Hectáreas a asegurar';
              break;
              default:
                $scope.nombre = 'Cantidad a asegurar';
              break;
            }



            

              //console.log($scope.user);

            $scope.mostrarloadingca = false;
            $scope.itemsCalibres = { 'E1':0,
                                   'E2':0,
                                   'E3':0,
                                   'E4':0,
                                   'E5':0,
                                   'N1':0,
                                   'N2':0
                                 }
            /*$scope.itemsCalibres = [];
            $scope.itemsCalibres.push($scope.itemCalibre);*/
            //seteamos rut por default y aglutinador 
            var auxRut         = $cookies.get('contratante');
            var auxAglutinador = $cookies.get('aglutinador');
            if(typeof auxRut != "undefined"){
                $scope.rut = auxRut;    
            } 
            if(typeof auxAglutinador != "undefined"){   

              $scope.selectAglutinador =JSON.parse(angular.fromJson(auxAglutinador));

              //console.log($scope.selectAglutinador);
            }
            $scope.mostrarloadingca = false;
            $scope.scroll();
        }


    
    $scope.reiniciar = function(){
      $scope.obtenerSector();
      $("html, body").animate({ scrollTop: 0 }, 1000, function(){ 
          $scope.showPaso2 = false;
          $scope.showPaso3 = false;
          $scope.showPaso4 = false;
          $scope.arrNormas = false;
          $scope.arrSeleccion = {};
          
          $scope.$apply();
        });
      
      
    }

    $scope.simular2 = function () {   

      
      var expireDate = new Date();  
             expireDate.setDate(expireDate.getDate() + 60);

      if ($scope.selectAglutinador != undefined) {
         var strRutAglutinador = $scope.selectAglutinador.rutaglutinador+""+$scope.selectAglutinador.dvaglutinador;
      }
      else{
         var strRutAglutinador = 0;
      }       

      // validar simulacion     
      var objData = {};
      var itemsdetalle= [];
      var montoasegurado =0;

      $scope.error = {};

      //$scope.mostrarloadingca = true; 
      $cookies.put('contratante',$scope.rut,{'expires': expireDate});
      var auxAglutinador0 = angular.toJson($scope.selectAglutinador);
      $cookies.put('aglutinador',JSON.stringify(auxAglutinador0),{'expires': expireDate});    

      //data
      objData.items= [];
      objData.idnormas= [];
      objData.rutaglutinador  = strRutAglutinador;
      objData.rutcontratante  = $scope.rut;
      objData.idcomuna        = $scope.arrSeleccion.comuna;

      //objData.idnormas        = ($scope.arrSeleccion.norma).keys();
      //normas a simular
      

      angular.forEach($scope.arrSeleccion.normaCompania, function(value, key) {
          if(value === true){
            tmpObj = [];
            angular.forEach($scope.arrNormas[key]["UF"], function(value, key){
              tmpObj.push(value.idNsZhsTemporadaVariedad+'-'+value.agrupar)
              
            });
            objData.idnormas.push(tmpObj);
          }   
      });

      angular.forEach($scope.arrSeleccion.norma, function(value, key) {
        if(value === true){
          objData.idnormas.push(key);
        }   
      });



      //console.log($scope.arrSeleccion.norma);

      if(document.getElementById("rendimiento")){ // si es multiitem la cantidad está en el arreglo de items
        $scope.rendimiento = parseFloat(document.getElementById ( "rendimiento" ).value); //no funciona el ng-modal wtf ;
        if($scope.rendimientoinferior != undefined && !isNaN($scope.rendimientoinferior) && ($scope.rendimiento == 0 || $scope.rendimiento == undefined || isNaN($scope.rendimiento))){
            //SweetAlert.warning("Advertencia", "Ingrese la cantidad a asegurar");
            $scope.error.rendimiento = 'Ingrese el rendimiento a asegurar';
            return;
        }
        if($scope.rendimiento < $scope.rendimientoinferior || $scope.rendimiento > $scope.rendimientosuperior){
          $scope.error.rendimiento = 'Debe ingresar un precio menor al de la norma de suscripción';
          return;
        }
      }

      if(document.getElementById("precio")){ // si es multiitem la cantidad está en el arreglo de items
        $scope.precioIngresado = parseFloat(document.getElementById ( "precio" ).value); //no funciona el ng-modal wtf ;
        if($scope.precio != undefined && !isNaN($scope.precio) && ($scope.precioIngresado == 0 || $scope.precioIngresado == undefined || isNaN($scope.precioIngresado))){
            //SweetAlert.warning("Advertencia", "Ingrese la cantidad a asegurar");
            $scope.error.precio = 'Ingrese Precio en ' + $scope.moneda;
            return;
        }
        if($scope.precio != undefined && $scope.precioIngresado > $scope.precio){
          $scope.error.precio = 'Debe ingresar un precio menor al de la norma de suscripción';
          return;
        }
      }

      if(!$scope.multiItem){ // si es multiitem la cantidad está en el arreglo de items
        $scope.cantidadasegurada = parseFloat(document.getElementById ( "cantidadasegurada" ).value); //no funciona el ng-modal wtf ;
        if($scope.cantidadasegurada == 0 || $scope.cantidadasegurada == undefined || isNaN($scope.cantidadasegurada)){
            //SweetAlert.warning("Advertencia", "Ingrese la cantidad a asegurar");
            $scope.error.cantidadasegurada = 'Ingrese la cantidad a asegurar';
            return;
        }
      }
        //GENERAMOS item detalle si es necesario 
        //console.log($scope.codigoSector);
        //console.log($scope.cantidadasegurada);
        //console.log($scope.montoasegurado);
        switch($scope.codigoSector){
            case 'FR':
                //con calibres...
                switch($scope.codigoRubro){
                    case 'PO':
                    case 'UV':
                    case 'UM':
                        //suma de calibres tiene que ser siempre 100
                        var suma = 0;
                        console.log($scope.itemsCalibres);
                        angular.forEach($scope.itemsCalibres, function(value, key){
                          if(value > 0){
                            suma+=value;
                            itemsdetalle.push({calibre:key,porcentaje:value});
                          }
                        });
                        //console.log(itemsdetalle);
                        if(suma != 100){
                            $scope.errorSumaCalibre = true;
                            SweetAlert.warning("Advertencia", "La suma del porcentaje de los calibres debe ser igual a 100");
                            return;
                        }
                        
                    break;

                }
                //
            break;
            case 'AP':
              if($scope.cantidadasegurada < 30){
                $scope.error.cantidadasegurada = 'Mínimo 30 colmenas';
                return;
              }
            break;
            case 'FO': //forestal
            $scope.montoasegurado = parseFloat(document.getElementById ( "montoasegurado" ).value); //no funciona el ng-modal wtf ;
              // 400 ha maximas montoasegurado
              if($scope.cantidadasegurada > 400){
                $scope.error.cantidadasegurada = 'Máximo 400 hectáreas';
                return;
              }
              if($scope.montoasegurado == 0 || $scope.montoasegurado == undefined|| isNaN($scope.montoasegurado)){
                  $scope.error.montoasegurado = 'Ingresar monto asegurado por hectárea';
                  return;
              }
            break;
        }

            if($scope.multiItem){
              angular.forEach($scope.arrSeleccion.arrVariedad, function(value, key){
                objData.items.push({"idvariedad":value.idvariedad,"cantidadasegurada":value.cantidadasegurada,"itemdetalle":itemsdetalle});      
              })
              
            }else{
              if($scope.montoasegurado >0){
                  objData.items.push({"idvariedad":$scope.arrSeleccion.variedad,"precio":$scope.precioIngresado,"rendimiento":$scope.rendimiento,"montoasegurado":$scope.montoasegurado,"cantidadasegurada":$scope.cantidadasegurada,"itemdetalle":itemsdetalle});
              }else{
                  objData.items.push({"idvariedad":$scope.arrSeleccion.variedad,"precio":$scope.precioIngresado,"rendimiento":$scope.rendimiento,"cantidadasegurada":$scope.cantidadasegurada,"itemdetalle":itemsdetalle});      
              }     
            }         
        

        $scope.showPaso4 = true;
      $scope.showPaso4Loading = true;
      
      $scope.scroll();

         $http({
            method: 'POST',
            url: domain + '/api/simular/subsidio2',
            headers: { 'Authorization': authorization },
            data: objData
              }).then(function successCallback(response) {

               if(response.data[0].response.CodigoRespuesta == 200){
              $scope.simulacion = response.data;
              //$scope.mostrarloadingca = false;

              $scope.ParidadUF = $scope.simulacion[0].request.ParidadUF;
              $scope.FechaParidad = $scope.simulacion[0].request.FechaParidad;
              $scope.showSimulacion = true;

              $scope.primeraSimulacion = $scope.simulacion[0].response.ResultDeterminaSubsidio;
              $scope.primeraSimulacionCompleta = $scope.simulacion[0].response;
              $scope.contratante = $scope.simulacion[0].contratante;
              $scope.showPaso4Loading = false;
            }else{

              

              $scope.showSimulacion = true;
              $scope.showPaso4Loading = false;
            }
            $("html, body").animate({ scrollTop: $(document).height() }, 1000);
            }, function errorCallback(response) {
              //$uibModalInstance.close('okk');
              console.log(response)
              });

            //
    };

    $scope.enviarSimulacion = function(){
        var modalInstance = $uibModal.open({
              animation: true,
              templateUrl: 'enviarSimulacion.html',
              controller: 'modalEnviarSimulacion',
              size: 'md',
              backdrop: 'static',
              ariaLabelledBy: 'modal-title',
              ariaDescribedBy: 'modal-body',
              resolve: {
                data: function () {
                  return {arrSeleccion: $scope.arrSeleccion, arrSimulacion: $scope.simulacion, rutAsegurado: $scope.rut, aglutinador: $scope.selectAglutinador};
                }
              }
          });
    };

    

    $scope.agregarCalibre = function(){
        //convierte string, luego parsea a objeto..

        var newItemCalibre = angular.fromJson(angular.toJson($scope.itemCalibre));
        newItemCalibre.porcentaje = 0;
        newItemCalibre.calibre    = null;
        $scope.itemsCalibres.push(newItemCalibre);
    };

    $scope.eliminarCalibre = function(index){
        $scope.itemsCalibres.splice(index, 1);
    }

    }]);



//resultado de las consultas wsdl.
appnormas.controller('modalresultadoctrl',['$scope','$http','$uibModalInstance','resultado',function($scope,$http,$uibModalInstance,resultado){
    $scope.modalsimulacion = resultado;
    console.log(resultado);
    $scope.ParidadUF = resultado[0].request.ParidadUF;
    $scope.FechaParidad = resultado[0].request.FechaParidad;
    $scope.ok = function () {
            $uibModalInstance.close('okk');
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
  };


}]);


appnormas.controller('modalEnviarSimulacion',['$scope','$http','SweetAlert', '$uibModalInstance','data',function($scope,$http,SweetAlert,$uibModalInstance,data){
  $scope.data = data;
  $scope.asegurado = {};
  var objData = {};

  $scope.asegurado.rut = data.rutAsegurado;
  $scope.error = '';
  $scope.loadingEnvio = false;  

  $scope.send = function(){

    $scope.loadingEnvio = true;
    objData.asegurado = $scope.asegurado;
    objData.trx = [];
    angular.forEach(data.arrSimulacion, function(value, key){
      //console.log(value);
      objData.trx.push(value.response.CodigoTransaccion);
    });
    //console.log(objData);
    $http({
        method: 'POST',
        url: domain + '/api/simular/enviar',
        
        headers: { 'Authorization': authorization },
        data: objData
    }).then(function successCallback(response) {
          
          if(response.data.CodigoRespuesta != "200"){
            $scope.error = response.data.MensajeRepuesta;
            
              
          }else{
            //console.log(response.data.MensajeRespuesta);
            SweetAlert.success('Acción realizada', response.data.MensajeRespuesta);
            $scope.cancel();
          }
          $scope.loadingEnvio = false;
      }, function errorCallback(response) {
        //console.log(response);
        console.log("ERROR");
        SweetAlert.error("Acción interrumpida", "Ha ocurrido un error al enviar el correo electrónico, inténtelo más tarde");
        $scope.loadingEnvio = false;
    });

    
  };

  $scope.cancel = function () {
        $uibModalInstance.close();
    };



}]);


appnormas.controller('modalAgregarItem',['$scope','$http','SweetAlert', '$uibModalInstance','data',function($scope,$http,SweetAlert,$uibModalInstance,data){
  $scope.data = data;
  $scope.asegurado = {};
  var objData = {};

  $scope.objVariedad = data.objVariedad;
  $scope.arrSeleccion = data.arrSeleccion;

  $scope.cancel = function () {
        $uibModalInstance.close();
    };



}]);

appnormas.controller('modalctrl',['$scope', '$http','$uibModalInstance', 'data', function($scope,$http,$uibModalInstance,data){
  //console.log(data);
  $scope.loadingRecontratacion = false;

  $scope.cancel = function () {
        $uibModalInstance.close();
  };
  $scope.renovacion = {};
  $scope.error = ''; 

  $scope.aglutinadores = data.aglutinadores;

  $scope.consultarRecontratacion = function(){
    $scope.loadingRecontratacion = true;
        $http({
          method: 'POST',
          url: domain + '/api/porcentaje/renovacion',
          data: {rutcontratante:$scope.rut},
          headers: { 'Authorization': authorization },
          }).then(function successCallback(response) {      
            $scope.error = response.data.error;
            $scope.renovacion = response.data;
            $scope.loadingRecontratacion = false;
             //Acá va el Push en response.data  
            //console.log(response.data);
            //console.log(response);

          }, function errorCallback(response) {            
              console.log(response);
            });
    };


    $scope.evaluarContratante = function(){
      $scope.loadingContratante = true;
          $http({
            method: 'POST',
            url: domain + '/api/porcentaje/tope',
            data: {rutcontratante:$scope.rutEvaluacion},
            headers: { 'Authorization': authorization },
            }).then(function successCallback(response) {  
              $scope.error = response.data.error;
              $scope.contratante = response.data;
              $scope.loadingContratante = false;
            }, function errorCallback(response) {            
                console.log(response);
              });
      };

}]);



appnormas.controller('modalcultivoanualctrl',['$scope','$http','$uibModalInstance','objConsulta','$uibModal','$cookies',function($scope,$http,$uibModalInstance,objConsulta,$uibModal,$cookies){

     var expireDate = new Date();
     expireDate.setDate(expireDate.getDate() + 60);

      //console.log($scope.user);

    $scope.mostrarloadingca = false;
    var itemCalibre = { list: [
                                {nombre:'Exportacion 1',id:'E1'},
                                {nombre:'Exportacion 2',id:'E2'},
                                {nombre:'Exportacion 3',id:'E3'},
                                {nombre:'Exportacion 4',id:'E4'},
                                {nombre:'Exportacion 5',id:'E5'},
                                {nombre:'Nacional 1',id:'N1'},
                                {nombre:'Nacional 2',id:'N2'},
                             ],
                        porcentaje:0,
                        calibre:null,
                    };
    //calibres e items.
    $scope.itemsCalibres = [];
    $scope.itemsCalibres.push(itemCalibre);
    //seteamos rut por default y aglutinador 
    var auxRut         = $cookies.get('contratante');
    var auxAglutinador = $cookies.get('aglutinador');
    if(typeof auxRut != "undefined"){
        $scope.rut = auxRut;    
    } 
    if(typeof auxAglutinador != "undefined"){   

      $scope.selectAglutinador =JSON.parse(angular.fromJson(auxAglutinador));

      //console.log($scope.selectAglutinador);
    }

    $scope.montoasegurado = 01; //?????    
    $scope.nombre        = objConsulta.nombre;
    $scope.codigoRubro   = objConsulta.codigoRubro;
    $scope.aglutinadores = [];
    $scope.conCalibre    = false;
    $scope.conForestal   = false;
    $scope.errorSumaCalibre = false;
    // define si usa calibre
    //console.log("*****************");
    //console.log(objConsulta.codigoSector); 
    //console.log(objConsulta.codigoRubro);


    switch(objConsulta.codigoSector){
        case 'FR':
            //con calibres...
            switch(objConsulta.codigoRubro){
                case 'PO':
                case 'UV':
                case 'UM':
                    $scope.conCalibre = true;
                break;

            }
            //
        break;
        case 'FO': //forestal
        $scope.conForestal = true; 
        break;
        case '':
        break;
    }

    //
    //obtener listador de aglutinadores 
    //
    $http({
          method: 'GET',
          url: domain + '/aglutinadores',
          headers: { 'Authorization': authorization },
          }).then(function successCallback(response) {             
             //Acá va el Push en response.data  
            //console.log(response.data);

            var arrayAglutinadores =[ {
                rutaglutinador: 0,
                dvaglutinador: '0',
                nombreaglutinador: 'Sin Aglutinador',
                descripcion: 'Sin Aglu',
                estado: 1,        
              }];  

            for (i=0;i<response.data.length;i++) {
              arrayAglutinadores.push(response.data[i]);
            }     

          $scope.aglutinadores = arrayAglutinadores; 
          }, function errorCallback(response) {            
              console.log(response);
            });

    $scope.ok = function (superficie = $scope.cantidadasegurada) {
      if(superficie <0 || !superficie){
        $scope.errorSuperficie = true;
            return false;
      }        
        $scope.consultar();
    }

    $scope.consultar = function () {   

      if ($scope.selectAglutinador != undefined) {
         var strRutAglutinador = $scope.selectAglutinador.rutaglutinador+""+$scope.selectAglutinador.dvaglutinador;
      }
      else{
         var strRutAglutinador = 0;
      }       

      // validar simulacion     
      var objData = {};
      var itemsdetalle= [];
      var montoasegurado =0;

      $scope.mostrarloadingca = true; 
      $cookies.put('contratante',$scope.rut,{'expires': expireDate});
      var auxAglutinador0 = angular.toJson($scope.selectAglutinador);
      $cookies.put('aglutinador',JSON.stringify(auxAglutinador0),{'expires': expireDate});    

      //data
      objData.items= [];
      objData.rutaglutinador  = strRutAglutinador;
      objData.rutcontratante  = $scope.rut;
      objData.idcomuna        = objConsulta.arrSeleccion.comuna;

        //GENERAMOS item detalle si es necesario 
        switch(objConsulta.codigoSector){
            case 'FR':
                //con calibres...
                switch(objConsulta.codigoRubro){
                    case 'PO':
                    case 'UV':
                    case 'UM':
                        //suma de calibres tiene que ser siempre 100
                        var suma = 0;
                        for(x=0;x <$scope.itemsCalibres.length;x++){
                            suma+=($scope.itemsCalibres[x].porcentaje-0);
                            itemsdetalle.push({calibre:$scope.itemsCalibres[x].calibre.id,porcentaje:$scope.itemsCalibres[x].porcentaje});
                        }
                        //console.log(itemsdetalle);
                        if(suma != 100){
                            $scope.errorSumaCalibre = true;
                            return false;
                        }
                        
                    break;

                }
                //
            break;
            case 'FO': //forestal
            // 400 ha maximas montoasegurado
            //$scope.conForestal      = true;
            //console.log("###");
            $scope.montoasegurado = document.getElementById ( "montoasegurado" ).value; //no funciona el ng-modal wtf 
            //console.log("###");
            //objData.montoasegurado= montoasegurado;
            break;
            case '':
            break;
        }
  //console.log($scope.montoasegurado);
            if($scope.montoasegurado >0){
                objData.items.push({"idvariedad":objConsulta.arrSeleccion.variedad,montoasegurado:$scope.montoasegurado,cantidadasegurada:$scope.cantidadasegurada,itemdetalle:itemsdetalle});
            }else{
                objData.items.push({"idvariedad":objConsulta.arrSeleccion.variedad,cantidadasegurada:$scope.cantidadasegurada,itemdetalle:itemsdetalle});      
            }              
        
         $http({
            method: 'POST',
            url: domain + '/api/simular/subsidio2',
            headers: { 'Authorization': authorization },
            data: objData
              }).then(function successCallback(response) {
              $scope.simulacion = response.data;
              $scope.mostrarloadingca = false;

              var modalInstance = $uibModal.open({
                    animation: true,
                    backdrop: 'static',
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'resultadosimulacion.html',
                    controller: 'modalresultadoctrl',
                    size: 'lg',
                    resolve: {
                      resultado: function () {
                        return response.data;
                      }
                    }
              });
              $uibModalInstance.close('okk');

            }, function errorCallback(response) {
              $uibModalInstance.close('okk');
              });

            //
    };

    $scope.agregarCalibre = function(){
        //convierte string, luego parsea a objeto..

        var newItemCalibre = angular.fromJson(angular.toJson(itemCalibre));
        newItemCalibre.porcentaje = 0;
        newItemCalibre.calibre    = null;
        $scope.itemsCalibres.push(newItemCalibre);
    }
    $scope.eliminarCalibre = function(index){
        $scope.itemsCalibres.splice(index, 1);
    }

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
  };


}]);

appnormas.directive('soloNumero', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';
        //console.log(scope.codigoRubro);
        // Remove forbidden characters
        cleanInputValue = inputValue.replace(',', '.') // change commas to dots
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, "."); // change X to dot
        if(scope.codigoRubro =='AP'){ //apicola es entero
            cleanInputValue.replace(',', '').replace('.', '');
        }
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});
/*appnormas.directive('soloInt', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';
        console.log(scope.codigoRubro);
        // Remove forbidden characters
        cleanInputValue = inputValue.replace(',', '')
          .replace('.', '') 
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, "."); // change X to dot
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});*/
