'use strict';

define(function() {
  /*
   * adminCtrl
   */
  var adminCtrl = function(
    $scope,
    BacAppFactory,
    $location,
    FeatureTypeFactory,
    $timeout,
    ngDialog,
    gaDomUtils,
    $window,
    EditFactory,
    QueryFactory,
    $sce,
    $filter,
    DocumentFactory,
    $rootScope,
    FilesFactory,
    StyleFactory,
    IndicatorParamsFactory,
    $http,
    gaJsUtils,
    $q,
    ElasticFactory,
    ParametersFactory,
    BacAppSearchFactory,
    DataStoreFactory,
    gclayers,
    $compile,
    $interval,
    PortalsFactory
  ) {
    // admins only
    if (!BacAppFactory.appCfg.isAdmin) $location.path('/bac/');

    if ($location.search()['initdb']) {
      $location.search('initdb', null);
      $timeout(function() {
        $window.location.reload();
      });
    }

    $scope.apptype = 'bac';
    var bacappcfg = BacAppFactory.appCfg.main;

    // kinda hacky but we cannot use  table-fill-page="true"
    // on the datatables because they are not displayed on load
    $timeout(function() {
      $scope.adminTableHeights = window.innerHeight - 300;
    });

    var userRoles = $rootScope.xgos.user.roles.map(function(x) {
      return x.name;
    });

    var moduleFactu = {
      title: 'Facturation',
      key: 'facturation',
      content:
        'js/XG/widgets/ancapp/main/views/admin/admin.facturationPeriode.html',
    };

    // console.log(AncAppFactory.appCfg.main);

    if (BacAppFactory.appCfg.main.properties.dolibarr.active) {
      moduleFactu = {
        title: 'Facturation',
        key: 'facturation',
        content:
          'js/XG/widgets/ancapp/main/views/admin/admin.facturation.dolibarr.html',
      };
    }

    // tabs
    $scope.adminTabs = [
      {
        title: 'Origine des données',
        key: 'liaison',
        content:
          'js/XG/widgets/bacapp/main/views/admin/admin.liaison_tables.html',
      },
      {
        title: "Service d'assainissement",
        key: 'sass',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.sass.html',
      },
      {
        title: 'Communes',
        key: 'villes',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.villes.html',
      },
      {
        title: 'Dossiers',
        key: 'dossiers',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.dossiers.html',
      },
      {
        title: 'Instructions',
        key: 'controles',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.controles.html',
      },
      {
        title: 'Parcelles',
        key: 'parcelles',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.parcelles.html',
      },
      {
        title: 'Organismes',
        key: 'organismes',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.entreprises.html',
      },
      {
        title: 'Demandeurs',
        key: 'demandeurs',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.demandeurs.html',
      },
      {
        title: 'Personnes',
        key: 'personnes',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.personnes.html',
      },
      {
        title: 'Cartes',
        key: 'cartes',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.map.html',
      },
      moduleFactu,
      {
        title: 'Documents',
        key: 'tableau_bord',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.dashboard.html',
      },
      {
        title: 'Recherche',
        key: 'recherche',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.recherche.html',
      },
      {
        title: 'Historique',
        key: 'historique',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.historique.html',
      },
      {
        title: 'Tableaux de bord',
        key: 'tab_bord',
        content:
          'js/XG/widgets/bacapp/main/views/admin/admin.tableau_bord.html',
      },
    ];

    if (BacAppFactory.appCfg.main.properties.gestionCivilites === true) {
      $scope.adminTabs.splice(1, 0, {
        title: 'Gestion des civilités',
        key: 'general',
        content: 'js/XG/widgets/ancapp/main/views/admin/admin.general.html',
      });
    }

    if (angular.isDefined(bacappcfg.ddc.active) && bacappcfg.ddc.active) {
      $scope.adminTabs.push({
        title: 'Droit de cité',
        key: 'operis',
        content: 'js/XG/widgets/bacapp/main/views/admin/admin.operis.html',
      });
    }

    if (
      BacAppFactory.appCfg.main.properties.gestionListesDeroulantes === true
    ) {
      $scope.listesDeroulantesTab = {
        title: 'Listes déroulantes',
        key: 'listes_deroulantes',
        content:
          'js/XG/modules/common/views/admin.listes_deroulantes.tabs.html',
        childrenTabsNames: {
          0: 'listesDeroulantesDossierEtInstruction',
        },
        childrenTabsData: [
          {
            title: 'Listes déroulantes des dossiers/instruction',
            key: 'listesDeroulantesDossierEtInstruction',
            content: 'js/XG/modules/common/views/admin.listes_deroulantes.html',
          },
        ],
      };

      $scope.listeDeroulantesSources = {
        listesDeroulantesDossierEtInstruction: [
          {
            name: 'Listes déroulantes des dossiers',
            value: ['kis_bac_dossier', 'kis_bac_dossier_proprietaire'],
          },
          {
            name: 'Listes déroulantes des instructions',
            value: ['kis_bac_listes_deroulantes_controles'],
          },
        ],
      };

      $scope.adminTabs.push($scope.listesDeroulantesTab);
    }

    if (
      userRoles.indexOf('BAC_admin') === -1 &&
      userRoles.indexOf('rootUser') === -1
    )
      $scope.adminTabs.splice($scope.adminTabs.length - 1, 1);

    if ($rootScope.xgos.isroot === true) {
      $scope.editAncObj = {
        data: angular.copy(BacAppFactory.appCfg.main),
        options: { mode: 'tree' },
      };
      $scope.adminTabs.push({
        title: '[ROOT] Paramétrage super admin g2c',
        key: 'supervision',
        content: 'js/XG/widgets/ancapp/main/views/admin/admin.supervision.html',
      });
    }

    /**
     * saveFullCfg
     */
    $scope.saveFullCfg = function() {
      BacAppFactory.appCfg.main = angular.copy($scope.editAncObj.data);
      BacAppFactory.updateAppCfg();
    };

    var activeTab = 0;
    if ($location.hash() != null) {
      for (var i in $scope.adminTabs) {
        if ($scope.adminTabs[i].key == $location.hash()) {
          activeTab = i;
          break;
        }
      }
    }

    $scope.adminTabs.activeTab = activeTab;

    $scope.res = {};

    $scope.civilites = angular.copy(
      BacAppFactory.appCfg.main.properties.civilites
    );

    /*----------------------------------------------
     * OPERIS
     *---------------------------------------------*/

    $scope.featuresAvailable = FeatureTypeFactory.resources.featuretypes;

    // Get available datastore
    DataStoreFactory.get(PortalsFactory.getPortalId()).then(
      function(res) {
        if (res.data) $scope.availableDatastore = res.data;
      },
      function(result) {
        console.log("ERROR DDC - CAN'T GET DATASTORE");
      }
    );

    // Apply config
    $scope.getSelectedCfg = function() {
      $scope.featToShow = {};

      if (angular.isDefined(BacAppFactory.appCfg.main.ddc))
        $scope.ddc = BacAppFactory.appCfg.main.ddc;

      if (angular.isUndefined($scope.selectedDatastore))
        $scope.selectedDatastore = {};

      if (angular.isDefined(BacAppFactory.appCfg.main.ddc)) {
        $scope.selectedDatastore = {
          active:
            angular.isDefined($scope.ddc.active) && $scope.ddc.active.length
              ? $scope.ddc.active
              : 0,
          name:
            angular.isDefined($scope.ddc.name) && $scope.ddc.name.length
              ? $scope.ddc.name
              : '',
          dossier: angular.isDefined($scope.ddc.dossier)
            ? $scope.ddc.dossier
            : {},
          parcelle: angular.isDefined($scope.ddc.parcelle)
            ? $scope.ddc.parcelle
            : {},
          url: angular.isDefined($scope.ddc.url) ? $scope.ddc.url : '',
          where: angular.isDefined($scope.ddc.where) ? $scope.ddc.where : [],
        };
      }
    };

    // get Parcelles feature
    var getParcelleFeature = function() {
      // $scope.parcelleFeature = {};
      $scope.featuresAvailable.filter(function(feat) {
        if (feat.name === BacAppFactory.appCfg.main.parcellesCfg.emplacement) {
          $scope.parcelleFeature = feat;
        }
      });
    };

    $scope.renderParcelleName = function() {
      getParcelleFeature();
      return $scope.parcelleFeature.name;
    };

    var configModalPopup;
    $scope.configPopup = function(type) {
      $scope.toSelect = type;
      $scope.selectedFeature = {};

      if (angular.isUndefined($scope.selectedDatastore[type].feature))
        $scope.selectedDatastore[type].feature = '';

      $scope.selectedFeature.uid = angular.isDefined(
        $scope.selectedDatastore[type].feature
      )
        ? $scope.selectedDatastore[type].feature
        : '';

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

    // render feat name
    var getFeat = function(type) {
      var featureToGet;
      if (angular.isDefined($scope.selectedDatastore[type])) {
        if (angular.isDefined($scope.selectedDatastore[type].feature)) {
          $scope.featuresAvailable.filter(function(feat) {
            if (feat.uid === $scope.selectedDatastore[type].feature) {
              featureToGet = feat;
            }
          });
        }
      }
      return featureToGet;
    };

    $scope.getFeatName = function(type) {
      var feat = getFeat(type);
      return feat.alias;
    };

    var getFeatAttr = function(type) {
      var feat = getFeat(type);
      return feat.attributes;
    };

    $scope.getAttrAlias = function(type) {
      var attrToGet;
      var attrs = getFeatAttr(type);
      if (
        angular.isDefined($scope.selectedDatastore[type].attribut) &&
        $scope.selectedDatastore[type].attribut.length > 0
      ) {
        attrs.filter(function(attr) {
          if (attr.name === $scope.selectedDatastore[type].attribut) {
            attrToGet = attr;
          }
        });
      }

      return attrToGet.alias;
    };

    var configAttrModal;
    $scope.configAttrConfig = function(type) {
      if (angular.isUndefined($scope.selectedDatastore[type].attribut))
        $scope.selectedDatastore[type].attribut = '';

      $scope.toSelect = type;
      $scope.selectedFeature = {};
      $scope.attributeToShow = getFeatAttr(type);
      $scope.selectedFeature.name = angular.isDefined(
        $scope.selectedDatastore[type].attribut
      )
        ? $scope.selectedDatastore[type].attribut
        : '';

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

    // Select feature
    $scope.updateCfgOperis = function(type) {
      if (type) {
        if (angular.isDefined($scope.selectedDatastore[type].feature)) {
          $scope.selectedDatastore[type].feature = angular.isDefined(
            $scope.selectedFeature.uid
          )
            ? $scope.selectedFeature.uid
            : $scope.selectedDatastore[type].feature;
          if (configModalPopup) configModalPopup.close();
        }

        if (angular.isDefined($scope.selectedDatastore[type].attribut)) {
          $scope.selectedDatastore[type].attribut = angular.isDefined(
            $scope.selectedFeature.name
          )
            ? $scope.selectedFeature.name
            : $scope.selectedDatastore[type].attribut;
          if (configAttrModal) configAttrModal.close();
        }
      }

      if (configWhereModal) {
        $scope.renderWhereClause();
        configWhereModal.close();
      }
    };

    // Save config
    $scope.enregistrerOperisCfg = function() {
      BacAppFactory.appCfg.main.ddc = $scope.selectedDatastore;
      BacAppFactory.updateAppCfg().then(function() {
        require('toastr').success('Configuration enregistrée');
      });
    };

    // modal Where
    var configWhereModal;
    $scope.configWhere = function() {
      configWhereModal = ngDialog.open({
        template:
          'js/XG/widgets/bacapp/main/views/modals/modal.operis.config_where.html',
        className: 'ngdialog-theme-plain width800 miniclose nopadding',
        closeByDocument: false,
        scope: $scope,
      });
    };

    $scope.addAttrWhereClause = function() {
      $scope.data.selectedAttribute.forEach(function(attr) {
        $scope.selectedDatastore.where.push(attr.name);
      });
    };

    $scope.deleteAttrWhere = function(idx) {
      $scope.selectedDatastore.where.splice(idx, 1);
      $scope.selectedDatastore.where = $scope.selectedDatastore.where.filter(
        function(val) {
          return val;
        }
      );
    };

    $scope.renderWhereClause = function() {
      var renderWhere = ' ';
      if (
        angular.isDefined($scope.selectedDatastore.where) &&
        $scope.selectedDatastore.where.length > 0
      ) {
        $scope.selectedDatastore.where.forEach(function(name) {
          if (angular.isDefined(name) && name != '') renderWhere += name + ' ';
        });
      }
      return renderWhere;
    };

    /*----------------------------------------------
     * HISTORIQUE
     *---------------------------------------------*/

    $scope.ftiHistorique = [];
    FeatureTypeFactory.resources.featuretypes.forEach(function(fti) {
      if (fti.name.indexOf('historique_') == 0) {
        $scope.ftiHistorique.push(fti);
      }
    });

    var editTableModale;
    $scope.selectedAttribute = '';
    $scope.openEditHistoriqueModale = function(table) {
      $scope.currentTable = table || {};

      if (angular.isDefined(bacappcfg.properties.configHistorique)) {
        bacappcfg.properties.configHistorique.forEach(function(config) {
          table.attributes.forEach(function(attr) {
            if (config.attribut === attr.name && config.name === table.name) {
              $scope.currentTable.selectedAttribute = attr.name;
            }
          });
        });
      }

      console.log($scope.currentTable);
      editTableModale = ngDialog.open({
        template:
          'js/XG/widgets/bacapp/main/views/modals/modal.admin.historique.edit.html',
        className: 'ngdialog-theme-plain width800 miniclose nopadding',
        closeByDocument: false,
        scope: $scope,
      });
    };

    $scope.appliquerAttributHistorique = function() {
      var toUpdate = false;
      var index;
      if (
        angular.isDefined($scope.currentTable.selectedAttribute) &&
        angular.isDefined($scope.currentTable.name)
      ) {
        if (
          angular.isDefined(bacappcfg.properties) &&
          angular.isUndefined(bacappcfg.properties.configHistorique)
        )
          bacappcfg.properties.configHistorique = [];

        if (bacappcfg.properties.configHistorique.length > 0) {
          for (
            var i = 0;
            i < bacappcfg.properties.configHistorique.length;
            i++
          ) {
            if (
              angular.isDefined(bacappcfg.properties.configHistorique[i]) &&
              bacappcfg.properties.configHistorique[i].name ==
                $scope.currentTable.name
            ) {
              index = i;
              toUpdate = true;
            }
          }

          if (!toUpdate) {
            var newConfigHistorique = {
              name: $scope.currentTable.name,
              attribut: $scope.currentTable.selectedAttribute,
            };

            bacappcfg.properties.configHistorique.push(newConfigHistorique);
          }

          if (toUpdate) {
            bacappcfg.properties.configHistorique[index].attribut =
              $scope.currentTable.selectedAttribute;
            toUpdate = false;
          }
        } else {
          var newConfigHistorique = {
            name: $scope.currentTable.name,
            attribut: $scope.currentTable.selectedAttribute,
          };
          bacappcfg.properties.configHistorique.push(newConfigHistorique);
        }
      }
      editTableModale.close();
    };

    $scope.enregistrerConfigHistorique = function() {
      BacAppFactory.appCfg.main.properties.configHistorique =
        bacappcfg.properties.configHistorique;
      BacAppFactory.updateAppCfg().then(function() {});
    };

    $scope.getAttributeName = function(ftiName) {
      var value = '';
      if (
        angular.isDefined(
          BacAppFactory.appCfg.main.properties.configHistorique
        ) &&
        BacAppFactory.appCfg.main.properties.configHistorique.length > 0
      ) {
        BacAppFactory.appCfg.main.properties.configHistorique.forEach(function(
          config
        ) {
          if (config.name === ftiName) {
            value = config.attribut;
          }
        });
      }

      return value;
    };

    /*----------------------------------------------
     * PERSONNES
     *---------------------------------------------*/

    $scope.personnesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
      BacAppFactory.appCfg.main.datastore,
      'kis_anc_personne'
    );

    $scope.refreshPersonnes = function() {
      $rootScope.$broadcast('refreshDatatable', {
        uid: $scope.personnesFti.uid,
      });
    };

    var editPersonneModale;
    $scope.openEditPersonneModale = function(personne) {
      $scope.currentPerson = personne || {};
      editPersonneModale = ngDialog.open({
        template: 'js/XG/widgets/ancapp/main/views/modals/modal.person.html',
        className: 'ngdialog-theme-plain width800 miniclose nopadding',
        closeByDocument: false,
        scope: $scope,
      });
    };

    /** when a person is edited */
    $scope.editedPerson = function() {
      editPersonneModale.close();
      $scope.refreshPersonnes();
    };
    $scope.datatablePersonCrud = {
      create: { func: $scope.openEditPersonneModale },
      update: { func: $scope.openEditPersonneModale },
      remove: true,
    };

    $scope.entreprisesCfg = BacAppFactory.appCfg.main.entreprisesCfg;
    $scope.parcellesCfg = BacAppFactory.appCfg.main.parcellesCfg;

    /*
         LISTE DEMANDEURS
         */
    $scope.demandeursFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
      BacAppFactory.appCfg.main.datastore,
      'kis_anc_demandeur'
    );
    $scope.displayTiersCivil =
      BacAppFactory.appCfg.main.properties.dolibarr.active == true;
    var addDemandeurModal;
    $scope.openAddDemandeurModal = function(demandeur) {
      $scope.currentDemandeur = demandeur || {};
      $scope.labelToShow = 'Demandeur';
      addDemandeurModal = ngDialog.open({
        template: 'js/XG/widgets/ancapp/main/views/modals/modal.demandeur.html',
        className: 'ngdialog-theme-plain width800 miniclose nopadding',
        closeByDocument: false,
        scope: $scope,
      });
    };
    $scope.datatableDemandeurCrud = {
      create: { func: $scope.openAddDemandeurModal },
      update: { func: $scope.openAddDemandeurModal },
      remove: true,
    };

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

      gaDomUtils.showGlobalLoader();

      if (angular.isUndefined($scope.currentDemandeur.id)) {
        featureCollection.features.push({
          type: 'Feature',
          properties: $scope.currentDemandeur.properties,
        });
        EditFactory.add($scope.demandeursFti.uid, featureCollection).then(
          function(res) {
            require('toastr').success('Enregistré');
            addDemandeurModal.close();
            gaDomUtils.hideGlobalLoader();
            $rootScope.$broadcast('refreshDatatable', {
              uid: $scope.demandeursFti.uid,
            });
          },
          function() {
            require('toastr').error(
              'Erreur lors de la sauvegarde du demandeur.'
            );
            gaDomUtils.hideGlobalLoader();
          }
        );
      } else {
        featureCollection.features.push($scope.currentDemandeur);
        EditFactory.update($scope.demandeursFti.uid, featureCollection).then(
          function(res) {
            require('toastr').success('Enregistré');
            addDemandeurModal.close();
            gaDomUtils.hideGlobalLoader();
            $rootScope.$broadcast('refreshDatatable', {
              uid: $scope.demandeursFti.uid,
            });
          },
          function() {
            require('toastr').error(
              'Erreur lors de la sauvegarde du demandeur.'
            );
            gaDomUtils.hideGlobalLoader();
          }
        );
      }
    };

    /*
         LISTE ENTREPRISE
         */

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

      var addEntrepriseModal;
      $scope.openAddEntrepriseModal = function(Entreprise) {
        $scope.currentEntreprise = Entreprise || {};
        addEntrepriseModal = ngDialog.open({
          template:
            'js/XG/widgets/bacapp/main/views/modals/modal.entreprise.html',
          className: 'ngdialog-theme-plain width800 miniclose nopadding',
          closeByDocument: false,
          scope: $scope,
        });
      };

      $scope.datatableEntrepriseCrud = {
        create: { func: $scope.openAddEntrepriseModal },
        update: { func: $scope.openAddEntrepriseModal },
        remove: true,
      };
    }

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

      gaDomUtils.showGlobalLoader();

      if (angular.isUndefined($scope.currentEntreprise.id)) {
        featureCollection.features.push({
          type: 'Feature',
          properties: $scope.currentEntreprise.properties,
        });
        EditFactory.add($scope.entreprisesFti.uid, featureCollection).then(
          function(res) {
            require('toastr').success('Enregistré');
            addEntrepriseModal.close();
            gaDomUtils.hideGlobalLoader();
            $rootScope.$broadcast('refreshDatatable', {
              uid: $scope.entreprisesFti.uid,
            });
          }
        );
      } else {
        featureCollection.features.push($scope.currentEntreprise);
        EditFactory.update($scope.entreprisesFti.uid, featureCollection).then(
          function(res) {
            require('toastr').success('Enregistré');
            addEntrepriseModal.close();
            gaDomUtils.hideGlobalLoader();
            $rootScope.$broadcast('refreshDatatable', {
              uid: $scope.entreprisesFti.uid,
            });
          }
        );
      }
    };

    /*----------------------------------------------
     * LISTE
     *---------------------------------------------*/

    if ($scope.parcellesCfg) {
      $scope.parcellesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
        BacAppFactory.appCfg.main.datastore,
        $scope.parcellesCfg.emplacement
      );

      var addParcelleModal;
      $scope.openAddParcelleModal = function(parcelle) {
        $scope.currentParcelle = parcelle || {};
        addParcelleModal = ngDialog.open({
          template:
            'js/XG/widgets/ancapp/main/views/modals/modal.parcelle.html',
          className: 'ngdialog-theme-plain width800 miniclose nopadding',
          closeByDocument: false,
          scope: $scope,
        });
      };

      $scope.datatableParcelleCrud = {
        create: { func: $scope.openAddParcelleModal },
        update: { func: $scope.openAddParcelleModal },
        remove: false,
      };
      $scope.editedParcelle = function() {
        addParcelleModal.close();
        $scope.refreshParcelles();
      };

      $scope.refreshParcelles = function() {
        $rootScope.$broadcast('refreshDatatable', {
          uid: $scope.parcellesFti.uid,
        });
      };
    }

    /*----------------------------------------------
     * cfg des tables branchement
     *---------------------------------------------*/
    console.log(bacappcfg);

    $scope.branchementsCfg = bacappcfg.extra.branchementsCfg
      ? bacappcfg.extra.branchementsCfg
      : {};
    $scope.branchementsCfgSet =
      bacappcfg.extra.branchementsCfg &&
      bacappcfg.extra.branchementsCfg.branchement &&
      bacappcfg.extra.branchementsCfg.jonction &&
      bacappcfg.extra.branchementsCfg.livraison;

    /**
     * saveBranchementCfg
     */
    $scope.saveBranchementCfg = function() {
      bacappcfg.extra.branchementsCfg = $scope.branchementsCfg;

      gaDomUtils.showGlobalLoader();
      BacAppFactory.updateAppCfg().then(function() {
        $scope.branchementsCfgSet =
          bacappcfg.extra.branchementsCfg.branchement &&
          bacappcfg.extra.branchementsCfg.jonction &&
          bacappcfg.extra.branchementsCfg.livraison;

        gaDomUtils.hideGlobalLoader();
      });
    };

    /*----------------------------------------------
     * CONTROLE
     *---------------------------------------------*/
    /*$scope.controletype = BacAppFactory.appCfg.main.controleCfg;
         $scope.enregistrerCfgControle = function () {
         BacAppFactory.appCfg.main.controleWorkflowCfg = $scope.controlesWorkflow;
         BacAppFactory.appCfg.main.controleCfg = $scope.controletype;
         BacAppFactory.updateAppCfg().then(function () {
         });

         };*/

    /*----------------------------------------------
     * Configuration Informations du SPANC
     *---------------------------------------------*/
    $scope.infosSass = {};
    $scope.infosSassAreSet = false;

    var setInfosSass = function() {
      if (BacAppFactory.appCfg.main.infosSass) {
        $scope.infosSass = BacAppFactory.appCfg.main.infosSass;
        $scope.infosSassAreSet = true;

        $scope.infosSassListeVillesCfg =
          BacAppFactory.appCfg.main.extra.infosSassListeVillesCfg;
        $scope.listeDesVilles = $scope.infosSassListeVillesCfg.filter( element => element.extra_ville !== true);
        $scope.listeDesVillesExtra = $scope.infosSassListeVillesCfg.filter( element => element.extra_ville === true);
        if (!angular.isDefined($scope.listeDesVilles))
          $scope.listeDesVilles = [];
      }
    };
    setInfosSass();

    $scope.enregistrerInfoSpanc = function() {
      BacAppFactory.appCfg.main.infosSass = $scope.infosSass;
      BacAppFactory.appCfg.main.extra.infosSassListeVillesCfg =
        $scope.infosSassListeVillesCfg;

      BacAppFactory.updateAppCfg().then(function() {});
    };

    /**
     * uploadSpancLogo
     * @param input
     */
    $scope.uploadSpancLogo = function(input) {
      $scope.staticFile = input.files[0];

      if ($scope.staticFile.size >= 1024 * 100) {
        require('toastr').error(
          'Le poids du fichier est supérieur à la limite autorisée (100kb).'
        );
        return;
      }

      var fd = new FormData();
      fd.append('file', $scope.staticFile);

      gaDomUtils.showGlobalLoader();
      FilesFactory.uploadprocess(fd).then(function(data) {
        $scope.infosSass.logo =
          '/services/' +
          PortalsFactory.getPortalId() +
          '/files/getfile?fileName=' +
          $scope.staticFile.name;
        gaDomUtils.hideGlobalLoader();
      });
    };

    $scope.removeLogo = function() {
      delete $scope.infosSass.logo;
    };

    //ouvrirFormulaireTemplateDialog
    var nouveauFormulaireTemplateDialog;
    $scope.ouvrirFormulaireTemplateDialog = function() {
      nouveauFormulaireTemplateDialog = ngDialog.open({
        template:
          'js/XG/widgets/bacapp/main/views/modals/modal.nouveauFormulaireTemplateDialog.html',
        className: 'ngdialog-theme-plain width800 miniclose nopadding',
        closeByDocument: false,
        scope: $scope,
      });
    };

    //nouveau controletype
    $scope.nouveauEmplacementFormulaire = function(nouveauEmplacement) {
      if (
        angular.isUndefined(nouveauEmplacement) ||
        angular.isUndefined(nouveauEmplacement.label) ||
        angular.isUndefined(nouveauEmplacement.type) ||
        nouveauEmplacement.label == '' ||
        nouveauEmplacement.type == ''
      ) {
        require('toastr').error('Il manque des informations.');
        return false;
      }

      if (angular.isUndefined(nouveauEmplacement.document_types)) {
        nouveauEmplacement.document_types = [];
      }

      $scope.controletype.push(nouveauEmplacement);
      nouveauFormulaireTemplateDialog.close();
    };

    //Supprimer ControleType
    $scope.supprimerControleType = function(index) {
      var r = confirm('Êtes-vous sûr de vouloir supprimer ?');
      if (r == true) {
        BacAppFactory.appCfg.main.controleCfg.splice(index, 1);
      }
    };

    /*----------------------------------------------
     * PERIODES DE FACTURATION
     *---------------------------------------------*/

    $scope.choixDateReferenceFacturation = [
      {
        value: 'date_saisie_controle',
        label: 'Date de saisie du controle',
      },
      {
        value: 'date_passage',
        label: 'Date de passage',
      },
      {
        value: 'date_avis',
        label: "Date de l'avis",
      },
    ];

    $scope.periodesCfg = BacAppFactory.appCfg.main.periodesCfg;
    for (var i in $scope.periodesCfg.tarification) {
      $scope.periodesCfg.tarification[i].tva = parseFloat(
        $scope.periodesCfg.tarification[i].tva
      );
    }

    var periodeDialog;
    $scope.ouvrirPeriodeDialog = function() {
      $scope.nouvellePeriode = {};

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

    $scope.savePeriode = function() {
      // add a unique key
      $scope.nouvellePeriode.key = Date.now();
      $scope.periodesCfg.periodes.push($scope.nouvellePeriode);
      periodeDialog.close();
    };
    $scope.supprimerPeriode = function(index) {
      var ans = confirm(
        'Êtes-vous certain de vouloir supprimer cette période ?'
      );
      if (ans) {
        BacAppFactory.appCfg.main.periodesCfg.periodes.splice(index, 1);
      }
    };

    $scope.choixDebiteur = [
      {
        value: 'proprietaire',
        label: 'Propriétaire',
      },
      {
        value: 'locataire',
        label: 'Occupant',
      },
      {
        value: 'demandeur',
        label: 'Demandeur',
      },
    ];

    $scope.retrieveDataPeriode = function(key) {
      var value = '';
      for (var i in $scope.periodesCfg.periodes) {
        var p = $scope.periodesCfg.periodes[i];
        if (p.key == key) {
          p.nom = p.nom || '';
          value =
            p.nom +
            ' - du ' +
            $filter('date')(p.debut) +
            ' au ' +
            $filter('date')(p.fin);
        }
      }
      return $sce.trustAsHtml(value);
    };

    var periodeFacturationDialog;
    $scope.ouvrirPeriodeFacturationDialog = function() {
      $scope.currentPeriodeFacturation = {
        tva: 0,
      };

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

    $scope.savePeriodeFacturation = function() {
      $scope.periodesCfg.tarification.push($scope.currentPeriodeFacturation);
      periodeFacturationDialog.close();
    };

    $scope.supprimerFacturationPeriode = function(index) {
      var r = confirm('Êtes-vous certain de vouloir supprimer cet élément ?');
      if (r == true) {
        BacAppFactory.appCfg.main.periodesCfg.tarification.splice(index, 1);
      }
    };

    $scope.saveFacturationPeriodeCfg = function() {
      BacAppFactory.appCfg.main.periodesCfg = $scope.periodesCfg;
      BacAppFactory.updateAppCfg().then(function() {});
    };

    $scope.saveCurrentDocumentType = function() {
      if (currentColumnIndex == undefined) {
        $scope.controletype[currentRownIndex].document_types.push(
          $scope.currentDocumentType
        );
      } else {
        $scope.controletype[currentRownIndex].document_types[
          currentColumnIndex
        ] = $scope.currentDocumentType;
      }
      currentColumnIndex = undefined;
      currentRownIndex = undefined;
      documentTypeDialog.close();
    };

    $scope.supprimerDocumentType = function(rownIndex, columnIndex) {
      var r = confirm('Êtes-vous sûr de vouloir supprimer ?');
      if (r == true) {
        $scope.controletype[rownIndex].document_types.splice(columnIndex, 1);
      }
    };

    /*
         Dossier Doc Cfg
         */

    $scope.dossiersCfg = angular.copy(BacAppFactory.appCfg.main.dossierCfg);

    $scope.enregistrerDossierCfg = function(dossiersCfg) {
      BacAppFactory.appCfg.main.dossierCfg = dossiersCfg;
      gaDomUtils.showGlobalLoader();
      BacAppFactory.updateAppCfg().then(function() {
        gaDomUtils.hideGlobalLoader();
      });
    };

    $scope.goToGestionModeles = function() {
      $window.open('#/documents/');
    };
    $scope.goToListeUtilisateurs = function() {
      $window.open('#/users/');
    };
    $scope.goToGestionCalendar = function() {
      $window.open('#/calendar/');
    };

    $scope.jasperIndicatorsTypes = [
      {
        key: 'text',
        label: 'Texte',
      },
      {
        key: 'real',
        label: 'Nombre réel',
      },
      {
        key: 'int',
        label: 'Entier positif',
      },
      {
        key: 'relativeint',
        label: 'Entier relatif',
      },
      {
        key: 'date',
        label: 'Date',
      },
    ];

    /**
     * setJasperIndicators
     */
    var jasperIndicatorsDialog;
    $scope.setJasperIndicators = function(rapport) {
      if (!angular.isDefined(rapport.indicateurs)) rapport.indicateurs = [];
      $scope.currentlyEditeRapport = rapport;
      $scope.indicateurs = angular.copy(rapport.indicateurs);

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

    /**
     * removeIndicator
     * @param index
     */
    $scope.removeIndicator = function(index) {
      var ans = confirm('Supprimer cet indicateur ?');
      if (ans) {
        $scope.indicateurs.splice(index, 1);
      }
    };

    /**
     * moveDashboardItem
     * @param index
     * @param direction
     * @returns {boolean}
     */
    $scope.moveDashboardItem = function(index, direction) {
      if (
        (index == 0 && direction == 'up') ||
        (index == $scope.dashboardCfg.length - 1 && direction == 'down')
      )
        return false;
      var newIndex = direction == 'up' ? index - 1 : index + 1;
      $scope.dashboardCfg.splice(
        index,
        0,
        $scope.dashboardCfg.splice(newIndex, 1)[0]
      );
    };

    /**
     * saveIndicators
     */
    $scope.saveIndicators = function() {
      $scope.currentlyEditeRapport.indicateurs = $scope.indicateurs;
      jasperIndicatorsDialog.close();
    };

    /**
     * generateJasperReport
     */
    $scope.generateJasperReport = function(rapport) {
      var jsonParameters = IndicatorParamsFactory.buildJsonParams(
        rapport.indicateurs
      );
      gaDomUtils.showGlobalLoader();

      BacAppFactory.generatereport(
        rapport.fichier.replace('.jasper', ''),
        jsonParameters
      ).then(
        function(res) {
          //BacAppFactory.generatereport(
          gaDomUtils.hideGlobalLoader();
          require('toastr').success(
            "La génération du rapport s'est correctement déroulée."
          );
        },
        function(reason) {
          gaDomUtils.hideGlobalLoader();
          require('toastr').error(
            'Erreur lors de la génération du rapport.\nLes images incluses dans le rapport ont elle été chargées ?'
          );
        }
      );
    };

    /**
     *  SpancInfo liste des villes
     */

    var nouvelleVilleModale;
    $scope.currentVilleIndex = false;
    var currentVilleIndex = false;

    /**
     *
     * @param v
     * @param index
     * @param update
     */
    $scope.openNouvelleVilleDialog = function(v, index, update) {
      if (v) {
        $scope.nouvelle_ville = angular.copy(v);
        let arrayName = $scope.nouvelle_ville.extra_ville === true
            ? 'listeDesVillesExtra' : 'listeDesVilles';
        currentVilleIndex = $scope[arrayName]
          .map(function(v) {
            return v.value;
          })
          .indexOf(v.value);
      } else {
        $scope.nouvelle_ville = { cp: [''] };
        currentVilleIndex = false;
      }

      $scope.currentVilleIndex = update;
      $scope.openVilleDialog();
    };

    $scope.openNouvelleExtraVilleDialog = function(v, index, update) {
      $scope.nouvelle_ville = { extra_ville: true, cp: [''] };
      $scope.openVilleDialog();
    };

    $scope.openVilleDialog = function() {
      if (nouvelleVilleModale) nouvelleVilleModale.close();

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

    $scope.add_ville_cp = function(cp) {
      $scope.nouvelle_ville.cp.push(undefined);
    };

    $scope.remove_ville_cp = function(index) {
      $scope.nouvelle_ville.cp.splice(index, 1);
    };

    /**
     *
     */
    $scope.updateVille = function() {
      let isExtraVille = $scope.nouvelle_ville.extra_ville === true;
      let arrayName = isExtraVille
          ? 'listeDesVillesExtra' : 'listeDesVilles';
      let oldVilleName = $scope[arrayName][currentVilleIndex].value;
      let copyVille = angular.copy($scope.nouvelle_ville);
      $scope[arrayName][currentVilleIndex] = copyVille;
      $scope.currentVilleIndex = false;
      let oldVilleIndex = $scope.infosSassListeVillesCfg.findIndex(
          element => element.value === oldVilleName && ((isExtraVille
              && element.extra_ville === true) || (!isExtraVille
              && element.extra_ville !== true)));
      $scope.infosSassListeVillesCfg[oldVilleIndex] = copyVille;
      nouvelleVilleModale.close();
      currentVilleIndex = false;
      $scope.nouvelle_ville = { cp: [] };
    };

    $scope.nouvelle_ville = { cp: [] };

    /**
     * nouvelleVille
     */
    $scope.nouvelleVille = function() {
      let isExtraVille = $scope.nouvelle_ville.extra_ville === true;
      if(!isExtraVille) {
        $scope.nouvelle_ville.gere_sass = true;
        $scope.listeDesVilles.push($scope.nouvelle_ville);
      } else {
        $scope.listeDesVillesExtra.push($scope.nouvelle_ville);
      }
      $scope.infosSassListeVillesCfg.push(
          $scope.nouvelle_ville
      );
      nouvelleVilleModale.close();
    };

    /**
     *
     * @param index
     */
    $scope.supprimer_ville_spanc = function(ville) {
      let isExtraVille = ville.extra_ville === true;
      let arrayName = isExtraVille
          ? 'listeDesVillesExtra' : 'listeDesVilles';
      var index = $scope[arrayName].indexOf(ville);
      $scope[arrayName].splice(index, 1);
      let oldVilleIndex = $scope.infosSassListeVillesCfg.findIndex(
          element => element.value === ville.value && ((isExtraVille
              && element.extra_ville === true) || (!isExtraVille
              && element.extra_ville !== true)));
      $scope.infosSassListeVillesCfg.splice(oldVilleIndex, 1);
    };

    $scope.setGereSass = function(ville) {
      let isExtraVille = ville.extra_ville === true;
      let oldVilleIndex = $scope.infosSassListeVillesCfg.findIndex(
          element => element.value === ville.value && ((isExtraVille
              && element.extra_ville === true) || (!isExtraVille
              && element.extra_ville !== true)));
      $scope.infosSassListeVillesCfg[oldVilleIndex].gere_spanc = ville.gere_sass;
    };

    /*
            Filtres sur la liste des villes
         */

    $scope.setDefaultVillesFilter = function() {
      $scope.villesfilter = {};
      $scope.extraVillesfilter = {};
    };
    $scope.setDefaultVillesFilter();

    $scope.setGereSpancFilter = function() {
      if ($scope.villesfilter.gere_sass == 'whatever') {
        delete $scope.villesfilter.gere_sass;
      }
    };
    $scope.gestionSpancOptions = [
      { k: 'whatever', v: 'Indifférent' },
      { k: true, v: 'Oui' },
      { k: false, v: 'Non' },
    ];

    // Sorting
    $scope.villesExtraOrderBy = {field:'value',reverse:false};
    $scope.villesOrderBy = {field:'value',reverse:false};

    $scope.sortBy = function(field, sortObject) {
      if(sortObject.field === field) {
        sortObject.reverse = !sortObject.reverse;
      } else {
        sortObject.field = field;
        sortObject.reverse = false;
      }
    };

    $scope.liste_ville = [];
    BacAppFactory.getdossier_villes().then(function(res) {
      res.data.forEach(function(v) {
        var v_upper = v.charAt(0).toUpperCase() + v.slice(1);
        $scope.liste_ville.push(v_upper);
      });
    });

    $scope.delaitypes = ['jour', 'semaine', 'mois', 'année'];

    /** recherche **/
    $scope.dossierFTI = FeatureTypeFactory.getFeatureByNameAndDatastore(
      BacAppFactory.appCfg.main.datastore,
      'kis_bac_dossier'
    );
    $scope.controleFTI = FeatureTypeFactory.getFeatureByNameAndDatastore(
      BacAppFactory.appCfg.main.datastore,
      'kis_bac_dossier_controle'
    );

    /**
     * supprimeIndexationPortail
     */
    $scope.supprimeIndexationPortail = function() {
      var ans = confirm($filter('translate')('common.confirm_action'));

      if (ans) {
        gaDomUtils.showGlobalLoader();
        var portalid = (portalid = PortalsFactory.getPortalId());
        if (portalid)
          ElasticFactory.deleteIndex(portalid).then(
            function() {
              $window.location.reload();
              require('toastr').success(
                $filter('translate')('portals.elastic.ok')
              );
            },
            function() {
              gaDomUtils.hideGlobalLoader();
              require('toastr').error(
                $filter('translate')('portals.elastic.nok')
              );
            }
          );
      }
    };

    $scope.showSearch = true;
    $scope.visibleSearch = function() {
      $scope.showSearch = !$scope.showSearch;
    };

    /*$scope.$watch("resultatElastic",function(newval){
         if ( !newval.features ) return;
         $scope.showSearch = false;
         })*/
    $scope.searchquerydb = undefined;
    $scope.$on('resultelastic', function(event, q, t, r) {
      $scope.searchquerydb = q;
      $scope.searchType = t;
      $scope.searchconfig = r;
      $scope.showSearch = false;
    });

    $scope.resultatElastic = {};
    $scope.resultatElasticdb = {};

    var hgl = function() {
      gaDomUtils.hideGlobalLoader();
    };

    /**
     * showProgression
     * @param {*} type
     * @param {*} def
     * @param {*} ftiname
     */
    var showProgression = function(type, def, ftiname) {
      var stop = $interval(function() {
        //console.log(def);

        var portalid = PortalsFactory.getPortalId();
        ElasticFactory.getprogressiondetaillee(portalid, ftiname).then(
          function(res) {
            $scope.indexProgressQuantites[type] = res.data.qte;

            var prcent = res.data.prcent;
            // controles
            if (ftiname == 'kis_bac_dossier_controle_reponse' && prcent == 99)
              prcent = 100;

            if (prcent < 100) {
              var p = parseInt(res.data.prcent);
              $scope.indexProgress[type] = p;
            } else if (prcent == 100) {
              $interval.cancel(stop);
              $timeout(function() {
                $scope.indexProgress[type] = 100;
                def.resolve();
              }, 100);
            }
          },
          function() {
            $interval.cancel(stop);
          }
        );
      }, 1000);
    };

    var fastIndexing = true;
    /**
     * pre_indexcontroles
     */
    $scope.pre_indexcontroles = function() {
      var def = $q.defer();

      BacAppFactory.setindexation().then(
        function() {
          ElasticFactory.createCompleteType(
            $scope.dossierFTI.name,
            $scope.dossierFTI.srid,
            fastIndexing
          ).then(
            function() {
              showProgression('dossiers', def, $scope.dossierFTI.name);
            },
            function() {
              def.reject();
            }
          );
        },
        function() {
          def.reject();
        }
      );

      return def.promise;
    };

    /**
     * indexcontroles
     */
    $scope.indexControle = function() {
      var def = $q.defer();
      ElasticFactory.createCompleteType(
        $scope.controleFTI.name,
        $scope.controleFTI.srid,
        fastIndexing
      ).then(
        function() {
          showProgression('controles', def, $scope.controleFTI.name);
        },
        function() {
          def.reject();
        }
      );
      return def.promise;
    };

    $scope.indexProgress = {
      dossiers: -1,
      controles: -1,
      json: -1,
    };
    $scope.indexProgressQuantites = angular.copy($scope.indexProgress);

    /**
     * doIndexControles
     */
    $scope.doIndexControles = function() {
      var def = $q.defer();
      showProgression('json', def, 'kis_bac_dossier_controle_reponse');
      BacAppFactory.indexcontroles().then(
        function(res) {
          // def.resolve();
          $scope.showSearch = true;
        },
        function() {
          def.reject();
        }
      );
      return def.promise;
    };

    /**
     * lancerIndexationBac
     */
    $scope.indexationEncours = false;
    $scope.lancerIndexationBac = function() {
      $scope.indexationEncours = true;

      // dossiers
      $scope.pre_indexcontroles().then(function() {
        // controles
        $scope.indexControle().then(function() {
          // controles json
          $scope.indexationCtrlEnCours = true;
          $scope.doIndexControles().then(function() {
            $scope.indexProgress.json = 100;
            $scope.indexationEncours = false;
            $scope.indexationCtrlEnCours = false;
            require('toastr').success('Indexation terminée.');
          });
        });
      });
    };

    $scope.showTableAfterSearch = function() {
      $scope.showSearch = false;
    };

    $scope.showGraphic = function() {
      $location.path($location.path().replace('admin', 'dashboard'));
      $location.replace($location.url());
    };

    $scope.addGraphicalDashbord = function() {
      var dashbord = {
        id: Math.floor(Math.random() * 10000000000),
        position: $scope.dashboards.length + 1,
        configdashboardsearch: false,
        configdashboardgraphic: false,
        showSearch: true,
        attributes: [],
        relations: [],
        resultsearch: {},
        fti: undefined,
        ftid: undefined,
      };
      $scope.dashboards.push(dashbord);
      getParametersConf();
    };

    $scope.removeChartDashboard = function(idx) {
      var ans = confirm(
        'Êtes-vous sûr de vouloir supprimer définitivement cette configuration ?'
      );
      if (ans) {
        var position = $scope.dashboards[idx].position;
        $scope.dashboards.splice(idx, 1);
        $scope.dashboards.map(function(x) {
          if (x.position > position) {
            x.position = position;
            position += 1;
          }
        });
      }
    };

    $scope.dashboards = [];

    ParametersFactory.getbytype('relationalElastic').then(
      function(res) {
        if (res.data.length > 0) {
          $scope.searchdatas = res.data;
          $scope.saved = {
            realNames: $scope.searchdatas,
            queries: $scope.searchdatas
              .map(function(x) {
                return x.name;
              })
              .filter(function(x) {
                if (x) return x;
              }),
            query: '',
          };
        }
        BacAppSearchFactory.getConfig().then(
          function(res) {
            if (res.data.etat === 'fini')
              $scope.dashboards = JSON.parse(res.data.content);
          },
          function() {
            console.info('aucune configuration du dashboard');
          }
        );
      },
      function() {
        throw new error('pas de config');
      }
    );

    function getParametersConf() {
      ParametersFactory.getbytype('relationalElastic').then(
        function(res) {
          if (res.data.length > 0) {
            $scope.searchdatas = res.data;
            $scope.saved = {
              realNames: $scope.searchdatas,
              queries: $scope.searchdatas
                .map(function(x) {
                  return x.name;
                })
                .filter(function(x) {
                  if (x) return x;
                }),
              query: '',
            };
          }
        },
        function() {
          throw new error('pas de config');
        }
      );
    }

    $scope.changedQuerySelect = function(idx) {
      getParametersConf();
      var filename = $scope.dashboards[idx].query;
      var filenames = $scope.searchdatas.map(function(x) {
        return x.name;
      });
      var index = filenames.indexOf(filename);
      var datas = $scope.searchdatas[index].data.relations;
      $scope.dashboards[idx].relations = [];
      datas.map(function(x) {
        $scope.dashboards[idx].relations.push(x);
      });

      if (
        $scope.searchdatas[index].data.jointure &&
        $scope.searchdatas[index].data.jointure.length > 0
      ) {
        $scope.dashboards[idx].parsedElementsForRelationDashbord =
          $scope.searchdatas[index].data.jointure;
      } else {
        $scope.dashboards[idx].parsedElementsForRelationDashbord = undefined;
      }

      $scope.editQueryDashboard(idx);
    };

    $scope.editQueryDashboard = function(idx, type) {
      $scope.dashBoardType = type;
      $scope.dashBoardIndex = idx;
      $scope.dashboards.map(function(x, i) {
        x.configdashboardgraphic = false;
        x.configdashboardsearch = false;
      });
      getParametersConf();
      $scope.dashboards[idx].configdashboardgraphic = false;
      $scope.dashboards[idx].configdashboardsearch = true;
      $scope.dashboards[idx].showSearch = true;
    };

    $scope.editChartDashboard = function(idx, type) {
      $scope.dashBoardType = type;
      $scope.dashBoardIndex = idx;
      $scope.dashboards.map(function(x, i) {
        x.configdashboardgraphic = false;
        x.configdashboardsearch = false;
      });
      getParametersConf();
      $scope.dashboards[idx].configdashboardgraphic = true;
      $scope.dashboards[idx].configdashboardsearch = false;
    };

    $scope.visibleSearchResult = function(idx, type) {
      $scope.dashBoardType = type;
      $scope.dashBoardIndex = idx;
      $scope.dashboards.map(function(x, i) {
        x.configdashboardgraphic = false;
        x.configdashboardsearch = false;
      });
      getParametersConf();
      $scope.dashboards[idx].configdashboardgraphic = false;
      $scope.dashboards[idx].configdashboardsearch = true;
      $scope.dashboards[idx].showSearch = false;
    };

    $scope.reduceQueryDashboard = function(idx, type) {
      $scope.dashBoardType = type;
      $scope.dashBoardIndex = idx;
      getParametersConf();
      $scope.dashboards[idx].configdashboardgraphic = false;
      $scope.dashboards[idx].configdashboardsearch = false;
      $scope.dashboards[idx].showSearch = false;
    };

    $scope.confirm = function() {
      $scope.elementsHasNoconfigName.map(function(x, i) {
        var saveData = {
          user: $rootScope.xgos.user.login,
          relations: x.dashboard.relations,
        };

        ParametersFactory.getbytype('relationalElastic').then(function(res) {
          var nameSaved = res.data.map(function(x) {
            return x.name;
          });
          if (nameSaved.indexOf(x.dashboard.query) !== -1) {
            var idx = res.data
              .map(function(x) {
                return x.name;
              })
              .indexOf(x.dashboard.query);
            var id = res.data[idx].id;
            var ans = confirm(
              $filter('translate')('elastic.search.existsconf')
            );
            if (ans)
              ParametersFactory.remove(id).then(
                function() {
                  ParametersFactory.add(
                    saveData,
                    'relationalElastic',
                    x.dashboard.query
                  ).then(
                    function() {
                      getParametersConf();
                      BacAppSearchFactory.saveConfig($scope.dashboards).then(
                        function() {
                          require('toastr').success(
                            'Tableau de bord enregistré'
                          );
                        },
                        function() {
                          require('toastr').error(
                            "erreur d'enregistrement du tableau de bord"
                          );
                        }
                      );
                    },
                    function() {
                      require('toastr').info(
                        $filter('translate')('elastic.search.save_nok')
                      );
                    }
                  );
                },
                function() {
                  require('toastr').info(
                    $filter('translate')('elastic.search.save_nok')
                  );
                }
              );
          } else {
            ParametersFactory.add(
              saveData,
              'relationalElastic',
              x.dashboard.query
            ).then(
              function() {
                getParametersConf();
                BacAppSearchFactory.saveConfig($scope.dashboards).then(
                  function() {
                    require('toastr').success('Tableau de bord enregistré');
                  },
                  function() {
                    require('toastr').error(
                      "erreur d'enregistrement du tableau de bord"
                    );
                  }
                );
              },
              function() {
                require('toastr').info(
                  $filter('translate')('elastic.search.save_nok')
                );
              }
            );
          }
        });
      });
    };

    $scope.$on('searchsuccesssahbord', function(evt, args) {
      $scope.visibleSearchResult(args, 'datatable');
    });

    $scope.saveQueryDashboard = function() {
      $scope.elementsHasNoconfigName = [];
      var parametersCompleted = true;
      $scope.dashboards.map(function(x, i) {
        x.configdashboardgraphic = false;
        x.configdashboardsearch = false;
        if (!x.searchquery || !x.chartconfig || !x.chartoptions || !x.name) {
          if (!x.searchquery)
            require('toastr').error(
              'Recherche non enregistrée pour la configuration Numéro ' +
                (i + 1) +
                "<br> Lancer la recherche pour l'enregistrer."
            );
          if (!x.chartconfig || !x.chartoptions)
            require('toastr').error(
              'Graphe non enregistrée pour la configuration Numéro ' +
                (i + 1) +
                "<br> Créez un graphe et lancez la récupération des données pour l'enregistrer."
            );
          if (!x.name)
            require('toastr').error(
              'Graphe non enregistrée pour la configuration Numéro ' +
                (i + 1) +
                '<br> Renseignez le nom du graphe.'
            );
          parametersCompleted = false;
        } else {
          require('toastr').info(
            'Configuration Numéro ' + (i + 1) + ' est correcte.'
          );
          if (parametersCompleted) parametersCompleted = true;
        }

        if ((!x.query || !x.name) && x.searchquery && x.searchquery.query)
          $scope.elementsHasNoconfigName.push({
            index: x.position,
            dashboard: x,
          });
      });
      if (parametersCompleted) {
        if ($scope.elementsHasNoconfigName.length > 0) {
          ngDialog.open({
            template:
              'js/XG/widgets/bacapp/main/views/admin/modals/modal.dashboard.saveconf.html',
            className: 'ngdialog-theme-plain width600 miniclose nopadding',
            closeByDocument: false,
            scope: $scope,
          });
        } else {
          BacAppSearchFactory.saveConfig($scope.dashboards).then(
            function() {
              require('toastr').success('Tableau de bord enregistré');
              $scope.dashBoardType = undefined;
              $scope.dashBoardIndex = -1;
            },
            function() {
              require('toastr').error(
                "erreur d'enregistrement du tableau de bord"
              );
              $scope.dashBoardType = undefined;
              $scope.dashBoardIndex = -1;
            }
          );
        }
      } else {
        require('toastr').error(
          "Echec de la sauvegarde. Remplissez les champs manquants d'abord."
        );
        $scope.dashBoardType = undefined;
        $scope.dashBoardIndex = -1;
      }
    };

    $scope.$on('resultsavednewsearch', function(event, data) {
      $scope.nomRequeteEnCours = data.name;
      if (data.place == 'dashboard') {
        getParametersConf();
      }
    });

    $scope.dashboardMove = function(idx, d) {
      if (idx !== -1) {
        if (d === 'up') {
          var dashboard = $scope.dashboards[idx];
          dashboard.position = dashboard.position - 1;
          $scope.dashboards.map(function(x) {
            if (x.id !== dashboard.id && x.position == dashboard.position) {
              x.position = x.position + 1;
            }
          });
          $scope.dashboards.splice(idx, 1);
          $scope.dashboards.splice(idx - 1, 0, dashboard);
        } else {
          var dashboard = $scope.dashboards[idx];
          dashboard.position = dashboard.position + 1;
          $scope.dashboards.map(function(x) {
            if (x.id !== dashboard.id && x.position == dashboard.position) {
              x.position = x.position - 1;
            }
          });
          $scope.dashboards.splice(idx, 1);
          $scope.dashboards.splice(idx + 1, 0, dashboard);
        }
      }
    };
  };

  adminCtrl.$inject = [
    '$scope',
    'BacAppFactory',
    '$location',
    'FeatureTypeFactory',
    '$timeout',
    'ngDialog',
    'gaDomUtils',
    '$window',
    'EditFactory',
    'QueryFactory',
    '$sce',
    '$filter',
    'DocumentFactory',
    '$rootScope',
    'FilesFactory',
    'StyleFactory',
    'IndicatorParamsFactory',
    '$http',
    'gaJsUtils',
    '$q',
    'ElasticFactory',
    'ParametersFactory',
    'BacAppSearchFactory',
    'DataStoreFactory',
    'gclayers',
    '$compile',
    '$interval',
    'PortalsFactory',
  ];
  return adminCtrl;
});
