'use strict';
define(function() {
  var ancVidangeLogic = function(
    $compile,
    $filter,
    BacAppFactory,
    AncAppFactory,
    $timeout,
    FeatureTypeFactory,
    QueryFactory,
    ngDialog,
    EditFactory,
    $rootScope,
    gaJsUtils,
    dateUtils
  ) {
    return {
      restrict: 'EA',
      link: {
        pre: function(scope, elt, attrs, ctrl) {
          var apptype = angular.isDefined(attrs.apptype)
            ? attrs.apptype
            : 'anc';

          scope.vidangeFormFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
            AncAppFactory.appCfg.main.datastore,
            'kis_anc_vidange_formulaire'
          );
          scope.currentAppFactory =
            apptype == 'anc' ? AncAppFactory : BacAppFactory;
          scope.entreprisesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
            scope.currentAppFactory.appCfg.main.datastore,
            scope.currentAppFactory.appCfg.main.entreprisesCfg.emplacement
          );
          scope.kis_anc_listes_deroulantes_controles = FeatureTypeFactory.getFeatureByUid(
            'kis_anc_listes_deroulantes_controles'
          );
        },
        post: function(scope, elt, attrs, ctrl) {
          let vidangeDateNames = ['date_controle', 'date_creation'];

          var periodesFacturation =
            AncAppFactory.appCfg.main.periodesCfg.periodes;
          var servicesFacturation =
            AncAppFactory.appCfg.main.periodesCfg.tarification;
          var templatesFacturation =
            AncAppFactory.appCfg.main.periodesCfg.templates;
          scope.currentLoaded = false;

          scope.ctrl_clos = false;
          var watchVdata = scope.$watch('currentVidange', function(cv) {
            if (angular.isDefined(cv)) {
              if (angular.isDefined(scope.triggerDate))
                delete scope.triggerDate;
              if (angular.isDefined(cv.properties))
                scope.ctrl_clos = cv.properties.etat == 'clos';
              if (angular.isDefined(cv.properties))
                scope.itvFacture = cv.properties.statut_facture == 'facture';
              scope.reoponedVidange = false;
            }
          });

          scope.$on('vdataToLogic', function(event, args) {
            if (
              angular.isDefined(args.vdata.date_controle) &&
              moment(args.vdata.date_controle).isValid()
            ) {
              scope.triggerDate = {};

              if (args.vdata.date_controle != scope.triggerDate.date_controle) {
                scope.triggerDate.date_controle = args.vdata.date_controle;
              }
            }

            scope.vdata = args.vdata;
          });

          scope.display = {
            vidangeur: 'reduced',
          };

          /* -------------------------------------------------------------------------
                     ctrlCfgValid
                     */
          scope.restrictionsConfig = {
            sort: {
              type: 'ASC',
            },
          };

          /* -------------------------------------------------------------------------
           * INTERVENTION PICKER
           */

          function inOblig(itv) {
            var count = scope.idPrestaObligatoire.length;
            for (var i = 0; i < count; i++) {
              if (scope.idPrestaObligatoire[i] === itv.id_service) {
                return true;
              }
            }
            return false;
          }

          var sumPrice = function() {
            scope.totalItv = 0;
            var globalPercent = [];
            var sumPrestaObligatoire = 0;

            // add all price
            scope.vdata.itvData.forEach(function(itv) {
              var tarif = inOblig(itv);

              if (tarif == false) scope.totalItv += itv.prix * itv.quantite;
              if (tarif == false && angular.isDefined(itv.percent))
                globalPercent.push(itv.percent);
              if (tarif == true)
                sumPrestaObligatoire += itv.prix * itv.quantite;
            });

            // add global % on price
            globalPercent.forEach(function(p) {
              scope.totalItv += (scope.totalItv / 100) * p;
            });

            //add obligatoire après majoration
            scope.totalItv = scope.totalItv + sumPrestaObligatoire;

            scope.vdata.totalVidange = precisionRound(scope.totalItv, 2);
          };

          var precisionRound = function(number, precision) {
            var factor = Math.pow(10, precision);
            return Math.round(number * factor) / factor;
          };

          scope.getBaseIntervention = function() {
            if (angular.isDefined(scope.triggerDate.date_controle)) {
              var period = getInterventionPeriod(
                scope.triggerDate.date_controle
              );
              if (!period) {
                require('toastr').warning(
                  'Aucune période de facturation ne correspond à la date de contrôle',
                  '',
                  {
                    positionClass: 'toast-bottom-left',
                  }
                  );
              }

              if (angular.isDefined(selectedServices)) {
                console.log(scope.servicesToGet);

                var base = scope.servicesToGet.filter(function(template) {
                  return (
                    angular.isDefined(template.obligatoire) &&
                    template.obligatoire == true
                  );
                });

                if (
                  angular.isUndefined(scope.vdata.itvData) ||
                  scope.vdata.itvData.length == 0
                ) {
                  scope.vdata.itvData = [];

                  base.forEach(function(presta_obligatoire) {
                    scope.vdata.itvData.push({
                      prix: presta_obligatoire.prix,
                      id_service: presta_obligatoire.id_service,
                      label: presta_obligatoire.label,
                      tva: presta_obligatoire.tva,
                      description: presta_obligatoire.description,
                      quantite: 1,
                      destination_matieres_vidanges: null,
                      volume_vidange: null,
                      commentaire: null,
                      lineaire_cure: null,
                      dispositif: null,
                      percent: null,
                    });
                  });
                }

                sumPrice();
              }
            }
          };
          /**
           * getServicesToShow
           */
          var selectedServices;
          var getServicesToShow = function() {
            scope.idPrestaObligatoire = [];

            var hasServices = false;
            var selectedTemplate;

            if (angular.isDefined(scope.keyPeriod)) {
              selectedTemplate = templatesFacturation.filter(function(
                template
              ) {
                return (
                  angular.isDefined(template.vidanges) &&
                  template.periode === scope.keyPeriod
                );
              });
              selectedServices = servicesFacturation.filter(function(service) {
                return service.periode === scope.keyPeriod;
              });
            }
            
            scope.servicesToGet = [];
            scope.servicesToShow = [];
            if (
              angular.isDefined(selectedTemplate[0]) &&
              selectedTemplate[0].associations.configuration.length > 0
            ) {
              console.log(servicesFacturation);
              selectedTemplate[0].associations.configuration.forEach(function(
                config
              ) {
                //keep presta obligatoire
                if (
                  angular.isDefined(config.obligatoire) &&
                  config.obligatoire == true
                ){
                  scope.idPrestaObligatoire.push(config.id_service);
                }

                servicesFacturation.forEach(function(service) {
                  if (config.id_service === service.dolibarrId) {
                    var newService = angular.copy(config);
                    newService.label = service.nom;
                    newService.prix = service.prix;
                    newService.description = service.description;
                    newService.tva = service.tva;
                    scope.servicesToGet.push(newService);
                    if (config.obligatoire != true) {
                      scope.servicesToShow.push(newService);
                    }
                  }
                });
              });
            }

            if (scope.servicesToGet.length > 0) hasServices = true;

            return hasServices;
          };

          /**
           * getInterventionPeriod
           * @param {*} date
           */
          var getInterventionPeriod = function(date) {
            var hasInterventionPeriod = false;

            if (
              angular.isDefined(periodesFacturation) &&
              angular.isDefined(templatesFacturation) &&
              angular.isDefined(date) &&
              periodesFacturation.length > 0 &&
              templatesFacturation.length > 0
            ) {
              var inside = false;

              periodesFacturation.forEach(function(periode) {
                var startDate = new Date(periode.debut),
                  endDate = new Date(periode.fin);

                inside = moment(date).isBetween(startDate, endDate);
                if (inside) {
                  scope.keyPeriod = periode.key;
                  hasInterventionPeriod = true;
                  scope.debutPeriode = periode.debut;
                  scope.finPeriode = periode.fin;
                }
              });
            }

            return hasInterventionPeriod;
          };
          scope.$watch('triggerDate.date_controle', function(date_controle) {
            if (scope.currentBranch
              && scope.currentBranch.identifier !== "vidange" ){
              return;
            }

            /**
             * Initialisation de la date de vidange
             */
            const controlDateExist =scope.cdata && scope.cdata.datesDossier
              && scope.cdata.datesDossier.hasOwnProperty('date_controle');
            if (!scope.triggerDate && controlDateExist) {
              scope.triggerDate = {};
              if (angular.isDefined(scope.cdata)) { 
                scope.triggerDate.date_controle = angular.copy(
                  scope.cdata.datesDossier.date_controle
                );
                scope.cdata.datesDossier.date_controle = angular.copy(
                  scope.triggerDate.date_controle
                );
              }
            }
            if(controlDateExist){
              scope.cdata.datesDossier.date_controle = angular.copy(
                scope.triggerDate.date_controle
              );
            }

            if (angular.isDefined(scope.servicesToGet))
              delete scope.servicesToGet;
            if (angular.isDefined(scope.keyPeriod)) delete scope.keyPeriod;

            if (
              angular.isDefined(scope.vdata) &&
              scope.currentVidange.statut_facture != 'facture'
            ) {
              if (
                (angular.isDefined(date_controle) &&
                  angular.isUndefined(scope.vdata.itvData)) ||
                (angular.isDefined(date_controle) &&
                  scope.vdata.itvData.length == 0)
              ) {
                if (moment(date_controle).isValid())
                  scope.getBaseIntervention();
              } else if (
                angular.isDefined(date_controle) &&
                angular.isDefined(scope.vdata.itvData)
              ) {
                var inside = getInterventionPeriod(date_controle);

                if (inside) {
                  var hasServices = getServicesToShow();

                  if (!hasServices)
                  require('toastr').warning(
                    $filter('translate')('vidange.warning.aucunService'),
                    '',
                    {
                      positionClass: 'toast-bottom-left',
                    }
                  );
                } else {
                  require('toastr').error(
                    $filter('translate')('vidange.warning.aucunPeriode'),
                    '',
                    {
                      positionClass: 'toast-bottom-left',
                    }
                  );
                }
              }
            }
          });

          /*
           * Ajouter une intervention dialog
           */
          var addInterventionDialog;
          scope.preAddIntervention = function () {
            if(!scope.triggerDate || !scope.triggerDate.date_controle){
              require('toastr').warning(
                $filter('translate')('vidange.warning.aucuneDate'),
                '',
                {
                  positionClass: 'toast-bottom-left',
                }
              );
              return;
            }
            let hasInterventionPeriod = getInterventionPeriod(
                scope.triggerDate.date_controle
            );
            if (hasInterventionPeriod) {
              getServicesToShow();
            }
            if (scope.servicesToGet) {
              scope.newIntervention = {};
              scope.selectedIntervention = {};
              addInterventionDialog = ngDialog.open({
                template:
                  'js/XG/widgets/ancapp/main/views/modals/modal.vidange.intervention.html',
                className: 'ngdialog-theme-plain width800 miniclose nopadding',
                closeByDocument: false,
                scope: scope,
              });
            }else {
              require('toastr').warning(
                $filter('translate')('vidange.warning.aucunService'),
                '',
                {
                  positionClass: 'toast-bottom-left',
                }
              );
            }
          };

          scope.setNewInterventionData = function() {
            scope.hasSpecificTemplate = false;
            if (
              angular.isDefined(scope.selectedIntervention.service) &&
              Object.keys(scope.selectedIntervention.service).length > 0
            ) {
              if (
                angular.isDefined(scope.selectedIntervention.service.majoration)
              ) {
              }

              scope.newIntervention = {
                id_service: scope.selectedIntervention.service.id_service,
                label: scope.selectedIntervention.service.label,
                tva: scope.selectedIntervention.service.tva,
                prix: scope.selectedIntervention.service.prix,
                description: scope.selectedIntervention.service.description,
                quantite: 1,
                destination_matieres_vidanges: null,
                volume_vidange: null,
                commentaire: null,
                lineaire_cure: null,
                dispositif: null,
                percent: null,
              };
            }

            if (
              scope.selectedIntervention &&
              scope.selectedIntervention.service &&
              scope.selectedIntervention.service.majoration &&
              scope.selectedIntervention.service.majoration['0'] &&
              scope.selectedIntervention.service.majoration['0'].declencheur
            )
              scope.hasSpecificTemplate =
                scope.selectedIntervention.service.majoration['0'].declencheur;
          };

          var getMajorationService = function(serviceToAdd) {
            var majoration = selectedServices.filter(function(service) {
              return service.dolibarrId == serviceToAdd.id;
            });
            return majoration;
          };

          var addInterventionMajoree = function(itv) {
            var toAdd = [];
            itv.forEach(function(majoration) {
              if (
                angular.isDefined(majoration.services) &&
                majoration.services.length
              ) {
                majoration.services.forEach(function(service) {
                  var serviceMajoration = getMajorationService(service);
                  serviceMajoration[0].declencheur = majoration.declencheur;
                  serviceMajoration[0].max_value = service.max_value;
                  serviceMajoration[0].tranche = service.tranche;
                  toAdd.push(serviceMajoration[0]);
                });
              }
            });

            toAdd.forEach(function(service) {
              if (
                scope.newIntervention[service.declencheur] > service.max_value
              ) {
                var diff =
                  scope.newIntervention[service.declencheur] -
                  service.max_value;
                var quantiteToAdd = Math.floor(diff / service.tranche);

                //Si aucune quantité car valeur trop faible --> on n'ajoute pas la ligne
                if (quantiteToAdd == 0) return;

                var serviceMajoration = {
                  id_service: service.dolibarrId,
                  description: service.description,
                  label: service.nom,
                  quantite: quantiteToAdd,
                  prix: service.prix,
                  tva: service.tva,
                  destination_matieres_vidanges: null,
                  volume_vidange: null,
                  commentaire: null,
                  lineaire_cure: null,
                  dispositif: null,
                  percent: null,
                };

                // petit timeout pour que la ligne s'ajoute en dessous de l'autre
                $timeout(function() {
                  scope.vdata.itvData.push(serviceMajoration);
                  require('toastr').warning(
                    'La prestation ' +
                      scope.newIntervention.label +
                      ' est majorée par la prestation ' +
                      serviceMajoration.label +
                      '.',
                    '',
                    {
                      positionClass: 'toast-bottom-right',
                    }
                  );

                  sumPrice();
                }, 100);
              }
            });
          };

          var addGlobalMajoration = function(itv) {
            itv.forEach(function(itglobal) {
              var newPriceItv;
              if (angular.isDefined(itglobal.percent))
                scope.newIntervention.percent = itglobal.percent;
            });
          };

          var checkMajoration = function(intervention) {
            var majGlobal = [];
            var majInterventions = [];

            if (angular.isDefined(intervention.majoration)) {
              intervention.majoration.forEach(function(majoration) {
                if (majoration.type === 'global') majGlobal.push(majoration);
                else if (majoration.type === 'prestation')
                  majInterventions.push(majoration);
              });
            }

            if (majGlobal.length > 0) addGlobalMajoration(majGlobal);
            if (majInterventions.length > 0)
              addInterventionMajoree(majInterventions);
          };

          /*
           * Ajouter une intervention
           */
          scope.addIntervention = function(i) {
            if (angular.isDefined(scope.newIntervention)) {
              if (!scope.vdata.itvData){
                scope.vdata.itvData = [];
                scope.getBaseIntervention();
              }

              if (
                angular.isDefined(scope.updateItv) &&
                scope.updateItv === true
              ) {
                scope.vdata.itvData[i] = scope.newIntervention;
                scope.updateItv = false;
              } else {
                checkMajoration(scope.selectedIntervention.service);
                scope.vdata.itvData.push(scope.newIntervention);
              }
            }

            sumPrice();

            addInterventionDialog.close();
          };

          /*
           * Editer une intervention
           */
          scope.editIntervention = function(index) {
            scope.selectedIntervention = {};

            if (angular.isDefined(scope.vdata.itvData[index])) {
              scope.newIntervention = scope.vdata.itvData[index];

              if (
                (angular.isDefined(scope.itvFacture) && !scope.itvFacture) ||
                angular.isUndefined(scope.itvFacture)
              ) {
                scope.servicesToGet.forEach(function(service) {
                  if (service.id_service === scope.newIntervention.id_service)
                    scope.selectedIntervention.service = service;
                });
              }

              scope.updateItv = true;

              addInterventionDialog = ngDialog.open({
                template:
                  'js/XG/widgets/ancapp/main/views/modals/modal.vidange.intervention.html',
                className: 'ngdialog-theme-plain width800 miniclose nopadding',
                closeByDocument: false,
                scope: scope,
              });
            }
          };

          /*
           * Supprimer une intervention
           */
          scope.removeIntervention = function(idx) {
            var ans = confirm(
              'Etes-vous sur de vouloir supprimer cette intervention ?'
            );

            if (ans) {
              if (angular.isDefined(scope.vdata.itvData)) {
                scope.vdata.itvData.splice(idx, 1);
              }

              sumPrice();
            }
          };

          scope.reinitIntervention = function() {
            var ans = confirm(
              "Êtes-vous sur de vouloir réinitialiser l'intervention ?"
            );
            if (ans) {
              if (
                angular.isDefined(scope.vdata) &&
                angular.isDefined(scope.vdata.itvData)
              )
                delete scope.vdata.itvData;
            }
          };

          /* -------------------------------------------------------------------------
           * ENTREPRISE PICKER
           */
          var pickInstallateurDialog;
          scope.prePickInstallateur = function(type) {
            if (angular.isUndefined(scope.entreprisesFti)) {
              scope.entreprisesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
                AncAppFactory.appCfg.main.datastore,
                scope.entreprisesCfg.emplacement
              );
            }

            scope.displayAttributesEntreprise = [];
            scope.entreprisesFti.attributes.forEach(function(att) {
              if (
                ~[
                  'nom',
                  'type',
                  'siret',
                  'num_tel',
                  'num_port',
                  'fax',
                  'email',
                  'adresse_num_rue',
                  'adresse_num_rue_extra',
                  'adresse_rue',
                  'adresse_ville',
                  'adresse_cp',
                  'adresse_bp',
                  'adresse_pays',
                  'adresse_batiment',
                  'adresse_appt',
                  'adresse_etage',
                  'adresse_escalier',
                  'adresse_complement',
                  'actif',
                ].indexOf(att.name)
              ) {
                if (att.name === 'type') {
                  scope.displayAttributesEntreprise.splice(0, 0, att);
                } else {
                  scope.displayAttributesEntreprise.push(att);
                }
              }
            });

            scope.typeEntreprise = type;
            scope.selectEntrepriseFilter = 'type =';
            if (type == 'vidangeur') scope.selectEntrepriseFilter += '3';

            // seulement les entreprises actives
            if (typeof userAndroid !== 'undefined')
              scope.selectEntrepriseFilter +=
                " AND actif = 'true' AND nom IS NOT NULL ";
            else {
              scope.selectEntrepriseFilter +=
                ' AND actif = true AND nom IS NOT NULL ';
            }

            pickInstallateurDialog = ngDialog.open({
              template:
                'js/XG/widgets/ancapp/main/views/controle/modals/modal.pick.entreprise.html',
              className: 'ngdialog-theme-plain width600 nopadding miniclose',
              closeByDocument: false,
              scope: scope,
            });
          };

          /*
           * Ajouter une entreprise
           */
          var addEntrepriseDialog;
          scope.ouvrirEntrepriseDialog = function(typeEntreprise) {
            scope.type = typeEntreprise;
            scope.currentEntreprise = {
              properties: {
                type: typeEntreprise,
                actif: true,
              },
            };
            scope.forceType = true;
            scope.forceActif = true;

            addEntrepriseDialog = ngDialog.open({
              template:
                'js/XG/widgets/ancapp/main/views/modals/modal.entreprise.html',
              className: 'ngdialog-theme-plain width800 miniclose nopadding',
              closeByDocument: false,
              scope: scope,
            });
          };

          scope.saveEntreprise = function() {
            var featureCollection = {
              type: 'FeatureCollection',
              features: [],
            };

            featureCollection.features.push({
              type: 'Feature',
              properties: scope.currentEntreprise.properties,
            });
            EditFactory.add(scope.entreprisesFti.uid, featureCollection).then(
              function(res) {
                require('toastr').success('Enregistré', '', {
                  positionClass: 'toast-bottom-left',
                });

                scope.currentVidange.properties.id_vidangeur =
                  res.data.create['0'].id;

                addEntrepriseDialog.close();
              }
            );

            // Si vidangeur
            if (scope.currentEntreprise.properties.type === '3')
              scope.vdata.vidangeur = scope.currentEntreprise.properties;
          };

          /*
           * Changement entreprise
           */
          scope.entreprisesCfg =
            scope.currentAppFactory.appCfg.main.entreprisesCfg;

          if (scope.entreprisesCfg) {
            scope.entreprisesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
              scope.currentAppFactory.appCfg.main.datastore,
              scope.entreprisesCfg.emplacement
            );
          }

          scope.getInfosEntreprise = function(entreprise) {
            if (scope.typeEntreprise === 'vidangeur') {
              scope.vdata.vidangeur = entreprise[0].properties;
              scope.currentVidange.properties.id_vidangeur = entreprise[0].id;
            }

            pickInstallateurDialog.close();
          };

          /**
           * Afficher/cacher les informations de l'entreprise
           */

          scope.toggleDisplayEntreprise = function(type) {
            if (type === 'vidangeur') {
              scope.display.vidangeur =
                scope.display.vidangeur == 'full' ? 'reduced' : 'full';
            }
          };

          /**
           * entrepriseNotSet
           */

          scope.entrepriseNotSet = function(type) {
            if (angular.isUndefined(scope.vdata)) scope.vdata = {};

            if (type == 'vidangeur')
              return (
                !angular.isDefined(scope.vdata.vidangeur) ||
                !Object.keys(scope.vdata.vidangeur).length
              );
          };

          /**
           * unlinkEntreprise
           */

          scope.unlinkEntreprise = function(type) {
            if (type == 'vidangeur' && angular.isDefined(scope.vdata.vidangeur))
              delete scope.vdata.vidangeur;
            if (
              angular.isDefined(scope.display.vidangeur) &&
              scope.display.vidangeur === 'full'
            )
              scope.display.vidangeur = 'reduced';
            if (
              angular.isDefined(scope.currentVidange) &&
              angular.isDefined(scope.currentVidange.properties)
            )
              scope.currentVidange.properties.id_vidangeur = null;
          };

          /**
           * unlinkStatut
           */
          scope.unlinkStatut = function() {
            if (angular.isDefined(scope.vdata.statut_rdv))
              delete scope.vdata.statut_rdv;
          };

          /**
           * sauvegarde formulaire de vidange
           */
          scope.saveVidangeDetail = function(close) {
            // mise à jour des informations de facturation
            if (!scope.itvFacture) {
              if (scope.vdata.itvData && scope.vdata.itvData.length) {
                var fData = {},
                  missingService = false;

                scope.vdata.itvData.forEach(function(itv) {
                  // recuperation de l'identifiant
                  var svc = selectedServices.filter(function(x) {
                    return x.dolibarrId == itv.id_service;
                  });

                  if (!svc.length) {
                    missingService = angular.copy(itv);
                  } else {
                    var id = angular.isDefined(svc[0].identifiant)
                      ? svc[0].identifiant
                      : 'identifiant_manquant';
                    if (angular.isUndefined(fData[id])) fData[id] = 0;
                    fData[id] += itv.quantite;
                  }
                });
                scope.vdata.facturation_data = fData;
                // si le service n'existe plus, throw error
                if (missingService) {
                  require('toastr').error(
                    'Le service <b>' +
                      missingService.label +
                      "</b> n'a pas pu être retrouvé dans la configuration de l'application.",
                    'Erreur',
                    {
                      positionClass: 'toast-bottom-left',
                    }
                  );
                  return;
                }
              }
            }

            if (angular.isDefined(scope.triggerDate)) {
              if (
                angular.isDefined(scope.triggerDate.date_controle) &&
                scope.triggerDate.date_controle !=
                  scope.currentVidange.properties.date_controle
              ) {
                scope.vdata.date_controle = scope.triggerDate.date_controle;
                scope.currentVidange.properties.date_controle =
                  scope.triggerDate.date_controle;
                scope.currentBranch.label =
                  'Vidange ' +
                  $filter('date')(
                    scope.triggerDate.date_controle,
                    'dd-MM-yyyy'
                  );
              }
            }

            if (close) {
              let ans = confirm(
                'Êtes-vous certain de vouloir clôturer cette intervention ?'
              );

              if (ans) {
                scope.currentVidange.properties.etat = 'clos';
                let currentVidange = angular.copy(scope.currentVidange);

                dateUtils.convertAllDatesToTimestamps(
                  currentVidange.properties,
                  vidangeDateNames
                );

                EditFactory.update(
                  scope.vidangeFormFti.uid,
                  gaJsUtils.setNewFeatureCollection(currentVidange),
                  ''
                ).then(function() {
                  require('toastr').success(
                    'Vidange enregistrée et clôturée',
                    '',
                    {
                      positionClass: 'toast-bottom-left',
                    }
                  );

                  let vData = angular.copy(scope.vdata);
                  dateUtils.convertAllDatesToTimestamps(
                    vData,
                    vidangeDateNames
                  );
                  AncAppFactory.addvidangedetail(
                    vData,
                    scope.currentReport.id,
                    scope.currentVidange.id
                  ).then(function() {
                    require('toastr').success(
                      'Formulaire de vidange mis à jour',
                      '',
                      {
                        positionClass: 'toast-bottom-left',
                      }
                    );
                  });
                });

                scope.ctrl_clos = true;
              }
            } else {
              let currentVidange = angular.copy(scope.currentVidange);

              dateUtils.convertAllDatesToTimestamps(
                currentVidange.properties,
                vidangeDateNames
              );
              EditFactory.update(
                scope.vidangeFormFti.uid,
                gaJsUtils.setNewFeatureCollection(currentVidange),
                ''
              ).then(function() {
                require('toastr').success('Vidange enregistrée', '', {
                  positionClass: 'toast-bottom-left',
                });

                AncAppFactory.addvidangedetail(
                  scope.vdata,
                  scope.currentReport.id,
                  scope.currentVidange.id
                ).then(function() {
                  require('toastr').success(
                    'Formulaire de vidange mis à jour',
                    '',
                    {
                      positionClass: 'toast-bottom-left',
                    }
                  );
                });
              });
            }

            $rootScope.$broadcast('refresh_bkp_vidange', scope.vdata);
          };

          scope.reopenVidange = function() {
            if (angular.isDefined(scope.ctrl_clos)) scope.ctrl_clos = false;
            scope.reoponedVidange = true;
          };

          scope.stripDescription = function(desc) {
            var strippedDesc;

            if (angular.isDefined(desc) && desc != null && desc.length > 30)
              strippedDesc = desc.slice(0, 30) + '...';
            else if (angular.isDefined(desc) && desc != null && desc.length > 0)
              strippedDesc = desc;
            else strippedDesc = '';

            return strippedDesc;
          };

          var checkDirtyVidangesDereg = $rootScope.$on(
            'check_dirty_vidanges',
            function(event, oldData) {
              //Prevent bubbling effect

              //Remove all empty object
              var cleanData = gaJsUtils.removeEmpty(oldData);
              var cleanNewData = gaJsUtils.removeEmpty(scope.vdata);

              //Compare ONLY data
              if (JSON.stringify(cleanData) != JSON.stringify(cleanNewData)) {
                var ans = confirm(
                  'Voulez-vous sauvegarder les modifications apportées à la vidange ?'
                );
                if (ans) scope.saveVidangeDetail();
                $timeout(function() {
                  $rootScope.$broadcast('resolve_change_vidange');
                });
              } else {
                $timeout(function() {
                  $rootScope.$broadcast('resolve_change_vidange');
                });
              }
            }
          );

          // cleanup
          scope.$on('$destroy', function() {
            delete scope.vdata;
            watchVdata();
            checkDirtyVidangesDereg();
          });
        },
      },
    };
  };

  ancVidangeLogic.$inject = [
    '$compile',
    '$filter',
    'BacAppFactory',
    'AncAppFactory',
    '$timeout',
    'FeatureTypeFactory',
    'QueryFactory',
    'ngDialog',
    'EditFactory',
    '$rootScope',
    'gaJsUtils',
    'dateUtils',
  ];
  return ancVidangeLogic;
});
