'use strict';
define(function() {
  var multicritereRetenuConfig = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    HpoCarteAppFactory,
    $window,
    ImportExportFactory,
    ngDialog,
    $q,
    $filter,
    $rootScope,
    $timeout,
    gaUrlUtils,
    ParametersFactory,
    ngTableParams,
    gaDomUtils,
    EditFactory,
    QueryFactory,
    HpoAppServices,
    ngProgressFactory,
    $location,
    InitProvider,
    $interval,
    HpoMulticritereServices,
    HpoAppModelServices,
    chartFactory,
    StyleFactory,
    authFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/analye_multicritere/views/directives/multicritere_retenu_config.html',
      restrict: 'EA',
      scope: {
        withDatatable: '=?',
        res: '=?',
        confirm: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        /**
         * Module Config
         * @type {[type]}
         */
        scope.configName =
          HpoCarteAppFactory.getAppFactory().getAppname() +
          '_' +
          'HpoRetenuCritereaConfig';
        scope.saveTemplateHtml =
          'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.prepare.templates.html';
        scope.getTemplateHtml =
          'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.prepare.gettemplates.html';
        scope.propertiestoexclude = {
          result: undefined,
          fti: undefined,
        };
        // scope.propertiestoexclude = {};
        scope.getReturnedTemplate = function(dataHpo) {
          if (dataHpo) {
            if (dataHpo.savedata.ftiuid) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(dataHpo.savedata.ftiuid);
              if (~idx) {
                dataHpo.savedata.fti = scope.ftis[idx];
              } else {
                AlertHpoFactory.showAlertTemplateUpdate();
                dataHpo.savedata.fti = undefined;
                dataHpo.savedata.ftiuid = undefined;
              }
            } else if (dataHpo.savedata.fti) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(dataHpo.savedata.fti.uid);
              if (~idx) {
                dataHpo.savedata.fti = scope.ftis[idx];
              } else {
                AlertHpoFactory.showAlertTemplateUpdate();
                dataHpo.savedata.fti = undefined;
                dataHpo.savedata.ftiuid = undefined;
              }
            }

            if (
              scope.currentParameter.isNew &&
              scope.currentParameter.uid !== dataHpo.savedata.uid
            ) {
              dataHpo.savedata.uid = HpoCarteAppFactory.getAppFactory().getRandomInteger();
              scope.oldParameter.uid = dataHpo.savedata.uid;
            } else {
              dataHpo.savedata.uid = scope.currentParameter.uid;
            }
            if (scope.currentParameter.isNew) {
              dataHpo.savedata.isNew = true;
              dataHpo.savedata.date = scope.currentParameter.date;
              delete dataHpo.savedata.id;
              delete scope.oldParameter.id;
            } else {
              dataHpo.savedata.id = scope.currentParameter.id;
            }
            if (scope.currentParameter.name)
              dataHpo.savedata.name = scope.currentParameter.name;
            if (scope.currentParameter.commentaire)
              dataHpo.savedata.commentaire = scope.currentParameter.commentaire;
            scope.currentParameter = angular.copy(dataHpo.savedata);
            scope.currentParameter.fti = dataHpo.savedata.fti;
          }
        };

        /**
         * Conf widgets
         * @type {[type]}
         */
        scope.tabs = [
          {
            title: 'hpo.multicritere.retenu.informations',
          },
        ];
        if (scope.withDatatable) {
          scope.tabs.push({
            title: 'hpo.multicritere.retenu.historic',
          });
        }
        scope.tabs.activeTab = 0;
        scope.loading = false;

        scope.generateReport = (obj) => {
          if (obj) {
            gaDomUtils.showGlobalLoader();
            HpoMulticritereServices.getPriority(
              scope.ftiCompare.uid,
              obj.id
            ).then((res) => {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data) { 
                  if (res.data.featid) {
                    var idx = scope.ftis
                      .map(function(x) {
                        return x.uid;
                      })
                      .indexOf(res.data.featid);
                    if (~idx) res.data.fti = scope.ftis[idx];
                  }
                  var newScope = $rootScope.$new();
                  newScope.res = res.data;
                  ngDialog.open({
                    template:
                      'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.priority.report.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: newScope,
                  });
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              },(err) =>{
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(err);
              }
            );
          }
        }


        scope.buttonSpecialActions = [
          {
            class: 'btn btn-success btn-xs',
            icone: 'fa fa-print',
            text: $filter('translate')('hpo.multicritere.retenu.report.label'),
            callFunction: scope.generateReport,
          },
        ];

        /**
         * Get required ftis
         * @type {Array}
         */
        var fti_correspondance_item = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'correspondance_items'
        )[0];
        var fti_correspondance = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'correspondance'
        )[0];
        var fti_ponderation = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'ponderation'
        )[0];
        var fti_indicateur = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'indicateur'
        )[0];
        var fti_parametrage = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'parameters'
        )[0];
        var fti_criterea = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'critereas'
        )[0];
        var fticalage = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'calage'
        )[0];
        scope.ftiprevision = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'prevision'
        )[0];
        var ftijeudonnee = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'jeu_de_donnee'
        )[0];
        var ftimodele = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'modal_historic'
        )[0];
        scope.ftiCompare = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'priority'
        )[0];
        var fti_filter = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'amc_filter'
        )[0];
        var initialseFilter =function(fti){
          var filter = '"FTI_TABLE" = \'' + fti.uid + "'";
          var promise = QueryFactory.data(
            fti_filter.uid,
            filter,
            HpoCarteAppFactory.getAppFactory().getSrid(),
            '',
            '',
            ''
          );
          promise.then(
            function(res) {
              if (res && res.data && res.data.features.length > 0) {
                let filtredFeature = res.data.features.filter(feature => feature.properties.USED==true);
                 scope.clauseWhere = filtredFeature.length>0?filtredFeature[0].properties.FILTER:"1=1";
              }else{
                 scope.clauseWhere = "1=1";
              }
            },
            function(res) {
               scope.clauseWhere = "1=1";
            }
          );
        }
        scope.ftiCompareattributes = scope.ftiCompare.attributes.filter(
          function(x) {
            if (
              x &&
              ((HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                scope.ftiCompare.name
              ) &&
                HpoCarteAppFactory.getAppFactory()
                  .getExcludedAttributes(scope.ftiCompare.name)
                  .indexOf(x.name) === -1) ||
                !HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                  scope.ftiCompare.name
                ))
            )
              return x;
          }
        );
        scope.ftis = HpoCarteAppFactory.getAppFactory().getMulticritereFtis();

        /**
         * Init object
         * @type {Object}
         */
        scope.emptyParameter = function(btn) {
          if (btn) {
            var callback = function(isconfirm) {
              if (isconfirm) {
                scope.currentParameter = scope.res || {
                  ponderation: undefined,
                  result: undefined,
                  seuil: 'lineaire',
                  date: HpoCarteAppFactory.getAppFactory().formatDate(
                    new Date()
                  ),
                  save: true,
                };
                if (scope.currentParameter.featid) {
                  var idx = scope.ftis
                    .map(function(x) {
                      return x.uid;
                    })
                    .indexOf(scope.currentParameter.featid);
                  if (~idx) scope.currentParameter.fti = scope.ftis[idx];
                }
                if (scope.res && scope.res.data) {
                  Object.assign(scope.currentParameter, scope.res.data);
                  scope.currentParameter.edit = true;
                }
                try {
                  scope.$apply();
                } catch(err) {}
              }
            };
            var message =
              $filter('translate')('hpo.multicritere.parameters.empty') +
              '. ' +
              $filter('translate')('hpo.common.sur');
            AlertHpoFactory.alertConfirmCallback(
              $filter('translate')('hpo.common.warning'),
              message,
              'warning',
              true,
              undefined,
              '#F50072',
              true,
              undefined,
              undefined,
              true,
              true,
              callback
            );
          } else {
            scope.currentParameter = scope.res || {
              ponderation: undefined,
              result: undefined,
              seuil: 'lineaire',
              date: HpoCarteAppFactory.getAppFactory().formatDate(new Date()),
              save: true,
            };
            if (scope.currentParameter.featid) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(scope.currentParameter.featid);
              if (~idx) scope.currentParameter.fti = scope.ftis[idx];
            }
            if (scope.res && scope.res.data) {
              Object.assign(scope.currentParameter, scope.res.data);
              scope.currentParameter.edit = true;
            }
          }
        };
        scope.emptyParameter(false);
        scope.availablePonderations = [];
        scope.availableIndicateurs = [];

        /**
         * Supplements
         * @type {Boolean}
         */
        scope.hasFti = true;
        scope.filterFunc = HpoCarteAppFactory.getAppFactory().filterFunc;

        scope.getAvailableData = function(featuid, fti, data, newscope) {
          var filter = '"FEATID" = \'' + fti.uid + "'";
          var promise = QueryFactory.data(
            featuid,
            filter,
            HpoCarteAppFactory.getAppFactory().getSrid(),
            '',
            '',
            ''
          );
          promise.then(
            function(res) {
              if (res && res.data) {
                if (newscope) newscope[data] = res.data.features;
                else {
                  scope[data] = res.data.features;
                  if (
                    data === 'availableCorrespondance' &&
                    scope[data].length === 0 &&
                    scope.currentParameter.seuil !== 'lineaire'
                  ) {
                    scope.currentParameter.seuil = 'lineaire';
                    scope.currentParameter.priority1 = undefined;
                    scope.currentParameter.priority2 = undefined;
                    scope.currentParameter.priority3 = undefined;
                  }
                }
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
            }
          );
          return promise;
        };

        scope.$watch('currentParameter.fti', function(newval, oldval) {
          if (newval) {
            scope.getAvailableData(
              fti_ponderation.uid,
              newval,
              'availablePonderations'
            );
            scope.getAvailableData(
              fti_correspondance.uid,
              newval,
              'availableCorrespondance'
            );
            initialseFilter(newval);
          } else {
            scope.availablePonderations = [];
            scope.availableCorrespondance = [];
          }
        });

        /**
         * Selection
         * @type {Array}
         */
        scope.selectOrdeAll = function(bool, availabledata, data) {
          if (bool) {
            availabledata.map(function(x) {
              scope.currentParameter[data][x.properties.IDENTIFIANT] = true;
            });
          } else {
            scope.currentParameter[data] = {};
          }
        };

        /**
         * Check form correct
         * @type {Array}
         */
        scope.lang = $rootScope.xgos.portal.lang;
        scope.checkInformations = function() {
          if (
            !scope.currentParameter ||
            !scope.currentParameter.fti ||
            !scope.currentParameter.fti.uid
          )
            return true;

          if (!scope.currentParameter || !scope.currentParameter.ponderation)
            return true;

          if (
            angular.isUndefined(scope.currentParameter.priority1) ||
            angular.isUndefined(scope.currentParameter.priority2) ||
            angular.isUndefined(scope.currentParameter.priority3)
          )
            return true;

          return false;
        };

        scope.elements = [1, 2, 3];
        scope.run = function() {
          var sendata = angular.copy(scope.currentParameter);
          sendata.clauseWhere = scope.clauseWhere;
          sendata.featid = sendata.fti.uid;
          delete sendata.fti;
          Object.assign(sendata, {
            fti_ponderation: fti_ponderation.uid,
            fti_indicateur: fti_indicateur.uid,
            fti_parametrage: fti_parametrage.uid,
            fti_criterea: fti_criterea.uid,
            fti_correspondance: fti_correspondance.uid,
          });
          if (scope.ftiprevision && scope.ftiprevision.uid) {
            Object.assign(sendata, {
              fti_calage: fticalage.uid,
              fti_prevision: scope.ftiprevision.uid,
              fti_jeudonnee: ftijeudonnee.uid,
              fti_modele: ftimodele.uid,
            });
          }
          if (
            sendata &&
            sendata.seuil === 'budget' &&
            scope.availableCorrespondance &&
            scope.availableCorrespondance.length > 0
          )
            sendata.correspondanceConfig = scope.availableCorrespondance
              .map(function(x) {
                return x.id;
              })
              .join(',');
          scope.loading = true;
          gaDomUtils.showGlobalLoader();
          HpoMulticritereServices.calculPriorities(sendata).then(
            function(res) {
              try {
                if (
                  res &&
                  res.data &&
                  (!res.data.code || res.data.code !== 500)
                ) {
                  scope.currentParameter.result = res.data;
                  scope.currentParameter.ids1 = scope.currentParameter.result.priority1.features.map(
                    function(x) {
                      return x.id;
                    }
                  );
                  scope.currentParameter.ids2 = scope.currentParameter.result.priority2.features.map(
                    function(x) {
                      return x.id;
                    }
                  );
                  scope.currentParameter.ids3 = scope.currentParameter.result.priority3.features.map(
                    function(x) {
                      return x.id;
                    }
                  );
                  if (res.data.type === 'lineaire')
                    scope.supplementAttributes = [
                      HpoCarteAppFactory.getAppFactory().getScoreAttribute(),
                    ];
                  else {
                    if (!res.data.show) {
                      scope.supplementAttributes = [
                        HpoCarteAppFactory.getAppFactory().getCoutAttribute(),
                        HpoCarteAppFactory.getAppFactory().getScoreAttribute(),
                      ];
                    } else {
                      // var attribute = HpoCarteAppFactory.getAppFactory().getCoutAttribute();
                      // attribute.name = res.data.attribute;
                      var idx = scope.currentParameter.fti.attributes
                        .map(function(x) {
                          return x.name;
                        })
                        .indexOf(res.data.attribute);
                      if (~idx)
                        scope.currentParameter.result.specialAttributeUse =
                          scope.currentParameter.fti.attributes[idx];
                      scope.supplementAttributes = [
                        HpoCarteAppFactory.getAppFactory().getScoreAttribute(),
                      ];
                    }
                  }
                  scope.attributes = HpoCarteAppFactory.getAppFactory().getAttributesWithFilter(scope.currentParameter.fti.attributes);
                  AlertHpoFactory.getSimpleSuccess(
                    $filter('translate')('hpo.multicritere.compare.succes'),
                    $filter('translate')(
                      'hpo.multicritere.compare.resultavailable'
                    ),
                    true
                  );
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              } catch (e) {
                e.stack;
              }
              scope.loading = false;
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
              scope.loading = false;
            }
          );
        };

        scope.editPriorities = function(obj) {
          if (obj) {
            gaDomUtils.showGlobalLoader();
            var sendata = {};
            Object.assign(sendata, {
              fti_ponderation: fti_ponderation.uid,
              fti_indicateur: fti_indicateur.uid,
              fti_parametrage: fti_parametrage.uid,
              fti_criterea: fti_criterea.uid,
              fti_correspondance: fti_correspondance.uid,
            });
            if (scope.ftiprevision && scope.ftiprevision.uid) {
              Object.assign(sendata, {
                fti_calage: fticalage.uid,
                fti_prevision: scope.ftiprevision.uid,
                fti_jeudonnee: ftijeudonnee.uid,
                fti_modele: ftimodele.uid,
              });
            }
            HpoMulticritereServices.getPriority(
              scope.ftiCompare.uid,
              obj.id,
              sendata
            ).then(
              function(res) {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data) {
                  if (res.data.featid) {
                    var idx = scope.ftis
                      .map(function(x) {
                        return x.uid;
                      })
                      .indexOf(res.data.featid);
                    if (~idx) res.data.fti = scope.ftis[idx];
                  }
                  var newScope = $rootScope.$new();
                  newScope.res = res.data;
                  var prom1 = scope.getAvailableData(
                    fti_ponderation.uid,
                    newScope.res.fti,
                    'newAvailablePonderations',
                    newScope
                  );
                  var prom2 = scope.getAvailableData(
                    fti_correspondance.uid,
                    newScope.res.fti,
                    'availableCorrespondance',
                    newScope
                  );
                  $q.all([prom1, prom2]).then(
                    function() {
                      var dialog = ngDialog.open({
                        template:
                          'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.priority.info.html',
                        className:
                          'ngdialog-theme-plain width1100 nopadding miniclose',
                        scope: newScope,
                      });
                    },
                    function(res1) {
                      gaDomUtils.hideGlobalLoader();
                      AlertHpoFactory.showErrorMessage(res1);
                    }
                  );
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

        var recalcStats = function() {
          var sendata = angular.copy(scope.currentParameter);
          sendata.featid = sendata.fti.uid;
          delete sendata.fti;
          Object.assign(sendata, {
            fti_ponderation: fti_ponderation.uid,
            fti_indicateur: fti_indicateur.uid,
            fti_parametrage: fti_parametrage.uid,
            fti_criterea: fti_criterea.uid,
            fti_correspondance: fti_correspondance.uid,
          });
          if (scope.ftiprevision && scope.ftiprevision.uid) {
            Object.assign(sendata, {
              fti_calage: fticalage.uid,
              fti_prevision: scope.ftiprevision.uid,
              fti_jeudonnee: ftijeudonnee.uid,
              fti_modele: ftimodele.uid,
            });
          }
          gaDomUtils.showGlobalLoader();
          HpoMulticritereServices.recalculPriorities(sendata).then(
            function(res) {
              try {
                if (
                  res &&
                  res.data &&
                  (!res.data.code || res.data.code !== 500)
                ) {
                  Object.assign(scope.currentParameter.result, res.data);
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              } catch (e) {
                e.stack;
              }
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        scope.editPosition = function(obj) {
          scope.obj = obj;
          scope.currentPosition = undefined;
          var ngDialogPromise = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/changeCanaPosition.html',
            scope: scope,
            className: 'ngdialog-theme-plain width600 nopadding miniclose',
          });
          ngDialogPromise.then(function(obj) {
            console.log(obj);
            var oldPosition;
            var oldindex;
            for (var i = 1; i <= 3; i++) {
              var idx = scope.currentParameter['ids' + i].indexOf(obj.id);
              if (~idx) {
                oldPosition = i;
                oldindex = idx;
                break;
              }
            }
            scope.currentParameter.result[
              'priority' + oldPosition
            ].features.splice(idx, 1);
            scope.currentParameter['ids' + oldPosition].splice(idx, 1);
            scope.currentParameter.result[
              'priority' + obj.currentPosition
            ].features.push(obj);
            scope.currentParameter['ids' + obj.currentPosition].push(obj.id);
            $rootScope.$broadcast('reloadDatatable');
            recalcStats();
          });
        };

        scope.buttonEditIcon = [
          {
            type: 'component',
            config: {
              name: 'button',
              click: ['crud_update'],
            },
            cfg: {
              icon: { name: 'pencil-square-o' },
              iconOrLabel: 'icon',
              size: 'btn-xs',
              style: 'btn-default cursorHelp',
              title: 'Editer le dossier',
            },
          },
        ];
        scope.datatableCrudHpo = {
          update: { func: scope.editPosition },
        };

        scope.changedNewCurrent = function(newCurrent, gridHpo) {
          gridHpo.data =
            newCurrent.result['grid_' + newCurrent.indicateurresult];
          newCurrent.chartOpt.chart.forceY = [
            0,
            newCurrent.result['y_' + newCurrent.indicateurresult],
          ];
        };

        var saveData = function(sendata, emptyresult) {
          gaDomUtils.showGlobalLoader();
          sendata.clauseWhere = scope.clauseWhere;
          HpoMulticritereServices.saveScore(sendata).then(
            function(res) {
              if (res && res.data) {
                var callback = function(res) {
                  AlertHpoFactory.successSave();
                  HpoCarteAppFactory.getInitProvider().initialiseApplication();
                  scope.refreshData();
                  if (emptyresult) scope.currentParameter.result = null;
                  else scope.emptyParameter();
                };
                authFactory.getcurrentuser().then(callback, callback);
              } else {
                AlertHpoFactory.failSave();
              }
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        var showDialogAndSave = function(result, allStyles) {
          var idx = scope.supplementAttributes
            .map(function(x) {
              if (x && x.name) return x.name;
            })
            .indexOf('CALC');
          var attributesCalc;
          if (~idx) {
            attributesCalc = scope.supplementAttributes[idx];
          }
          // TODO Result geojson
          scope.newAttributeInformations = {
            existing: [],
            possible: [],
            update: 'add',
            ftiuid: result.fti.uid,
            newAttribute: {},
            updateStyle: 'nothing',
            newStyleName: undefined,
            typeName: true,
            allStyles: allStyles,
            existingStyle: result.fti.defaultStyle,
            savePriority: true,
            name: undefined,
            commentaire: undefined,
            updatedAttribute: undefined,
            type: {
              id: 'java.lang.Double',
              label: 'java.lang.Double',
            },
            data: {
              ponderation: result.ponderation,
              seuil: result.seuil,
              priority1: result.priority1,
              priority2: result.priority2,
              priority3: result.priority3,
            },
            result: result.result,
          };
          var attributesAuthorised = HpoCarteAppFactory.getAppFactory().getAuthorizedAttributes(
            result.fti,
            'w'
          );
          attributesAuthorised.map(function(x) {
            if (
              x &&
              x.name !== attributesCalc.name &&
              x.type === attributesCalc.type
            ) {
              scope.newAttributeInformations.possible.push(x);
              scope.newAttributeInformations.existing.push(x.name);
            } else {
              scope.newAttributeInformations.existing.push(x.name);
            }
          });
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.return.save.html',
            className:
              'ngdialog-theme-plain width800 minheight500 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
          dialog.then(function(data) {
            var sendata = {
              typeAttribute: data.update,
              attribute:
                data.update === 'add'
                  ? data.newAttribute
                  : data.updatedAttribute,
              attributeName:
                data.update === 'add'
                  ? data.newAttribute.name
                  : data.updatedAttribute.name,
              attributeAlias:
                data.update === 'add'
                  ? data.newAttribute.alias
                  : data.updatedAttribute.alias,
              ftiuid: scope.ftiCompare.uid,
              featid: data.ftiuid,
              priorities: true,
              data: data.data,
              result: data.result,
              date: HpoCarteAppFactory.getAppFactory().formatDate(new Date()),
              style: data.newStyleName,
              updateStyle: data.updateStyle,
              savePriority: data.savePriority,
              name: data.name,
              type: data.data.seuil,
              commentaire: data.commentaire,
            };
            saveData(sendata);
          });
        };

        scope.saveScenario = function(result) {
          var allStyles = [];
          StyleFactory.getlist().then(
            function(res) {
              if (res.data && res.data.length > 0) allStyles = res.data;
              showDialogAndSave(result, allStyles);
            },
            function(res) {
              showDialogAndSave(result, allStyles);
            }
          );
        };

        scope.saveAgainScenario = function(currentParameter) {
          var attribute;
          var idx = currentParameter.fti.attributes
            .map(function(x) {
              return x.name;
            })
            .indexOf(currentParameter.attributeName);
          if (~idx) {
            attribute = currentParameter.fti.attributes[idx];
          }
          var sendata = {
            typeAttribute: 'update',
            attribute: attribute,
            attributeName: currentParameter.attributeName,
            attributeAlias: currentParameter.attributeAlias,
            ftiuid: scope.ftiCompare.uid,
            featid: currentParameter.fti.uid,
            priorities: true,
            data: {
              ponderation: currentParameter.ponderation,
              seuil: currentParameter.seuil,
              priority1: currentParameter.priority1,
              priority2: currentParameter.priority2,
              priority3: currentParameter.priority3,
            },
            result: currentParameter.result,
            date: currentParameter.date,
            style: currentParameter.style,
            updateStyle: currentParameter.updateStyle,
            savePriority: true,
            id: currentParameter.id,
            name: currentParameter.name,
            type: currentParameter.seuil,
            commentaire: currentParameter.commentaire,
          };
          saveData(sendata, true);
        };

        scope.validName = function(name, attributesNames) {
          if (name && attributesNames && attributesNames.length > 0) {
            var idx = attributesNames.indexOf(name);
            if (~idx) return false;
          }
          return /^[A-Za-z0-9-_\ éèêûùà]+$/.test(name);
        };

        scope.validNameSpace = function(name) {
          return /^[A-Za-z0-9_]+$/.test(name);
        };

        scope.datatableHeightHistoric =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          110 +
          'px';

        scope.refreshData = function() {
          $rootScope.$broadcast('reloadDatatable', scope.ftiCompare.uid);
        };

        scope.datatableCalageCrudHpo = {
          update: { func: scope.editPriorities },
          remove: true,
          extraActions: [
            {
              name: $filter('translate')('hpo.common.refresh'),
              class: 'btn-default margin-left-right pull-left',
              func: scope.refreshData,
              icon: 'fa-refresh',
              special: true,
            },
          ],
        };

        scope.getPonderationInfo = function(ponderation) {
          HpoMulticritereServices.getPonderation(
            fti_ponderation.uid,
            ponderation.id
          ).then(
            function(res) {
              if (res && res.data) {
                var newScope = $rootScope.$new();
                newScope.currentParameter = res.data[0];
                if (newScope.currentParameter.ftiuid) {
                  var idx = scope.ftis
                    .map(function(x) {
                      return x.uid;
                    })
                    .indexOf(newScope.currentParameter.ftiuid);
                  if (~idx) newScope.currentParameter.fti = scope.ftis[idx];
                }
                newScope.readonly = true;
                newScope.templateTpl =
                  'js/XG/widgets/hpoapp/analye_multicritere/views/templates/analyse.tpl.html';
                newScope.ftis = scope.ftis;
                newScope.filterFunc = HpoCarteAppFactory.getAppFactory().filterFunc;
                var prom2 = scope.getAvailableData(
                  fti_criterea.uid,
                  newScope.currentParameter.fti,
                  'availableCritereas',
                  newScope
                );
                prom2.then(
                  function() {
                    ngDialog.open({
                      template:
                        'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.preview.general.tpl.html',
                      className:
                        'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
                      closeByDocument: false,
                      scope: newScope,
                    });
                  },
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    AlertHpoFactory.showErrorMessage(res);
                  }
                );
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        scope.checkCorrectInformations = function(newAttributeInformations) {
          if (newAttributeInformations.update === 'update') {
            if (
              !newAttributeInformations.updatedAttribute ||
              !newAttributeInformations.updatedAttribute.name ||
              !newAttributeInformations.updatedAttribute.type
            )
              return true;
          } else {
            if (
              !newAttributeInformations.newAttribute ||
              !newAttributeInformations.newAttribute.name ||
              !newAttributeInformations.newAttribute.type
            )
              return true;
          }

          if (newAttributeInformations.updateStyle === 'add') {
            if (
              !newAttributeInformations.newStyleName ||
              !scope.validNameSpace(newAttributeInformations.newStyleName, [])
            )
              return true;
          }

          if (
            newAttributeInformations.savePriority &&
            !newAttributeInformations.name
          )
            return true;

          if (
            newAttributeInformations.updateStyle === 'add' &&
            newAttributeInformations.allStyles &&
            newAttributeInformations.allStyles.indexOf(
              newAttributeInformations.newStyleName
            ) !== -1
          )
            return true;
          return false;
        };

        scope.saveInfo = function(ftiuid, id, name, commentaire, savePriority) {
          gaDomUtils.showGlobalLoader();
          var prom1 = EditFactory.updatebyid(
            ftiuid,
            id,
            'NAME',
            'string',
            name
          );
          var prom2 = EditFactory.updatebyid(
            ftiuid,
            id,
            'COMMENTAIRE',
            'string',
            commentaire
          );
          var prom3 = EditFactory.updatebyid(
            ftiuid,
            id,
            'LAST_APPLIED',
            'boolean',
            savePriority
          );
          var promises = [prom1, prom2, prom3];
          if (savePriority) {
            var where =
              '"FEATID" = \'' +
              scope.currentParameter.fti.uid +
              "' AND NOT IN ('" +
              id +
              "') ";
            var prom4 = EditFactory.updatebyfilter(
              ftiuid,
              where,
              'LAST_APPLIED',
              'boolean',
              false
            );
            promises.push(prom4);
          }
          $q.all(promises).then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.successUpdate();
              scope.refreshData();
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.failUpdate();
            }
          );
        };

        scope.addCorrespondance = function(fti) {
          var newScope = $rootScope.$new();
          newScope.res = {
            featid: fti.uid,
            date: HpoCarteAppFactory.getAppFactory().formatDate(new Date()),
          };
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.correspondance.info.html',
            className: 'ngdialog-theme-plain width1100 nopadding miniclose',
            scope: newScope,
          });
          dialog.then(function() {
            scope.getAvailableData(
              fti_ponderation.uid,
              fti,
              'availablePonderations'
            );
            scope.getAvailableData(
              fti_correspondance.uid,
              fti,
              'availableCorrespondance'
            );
          });
        };
      },
    };
  };

  multicritereRetenuConfig.$inject = [
    'AlertHpoFactory',
    'FeatureTypeFactory',
    'HpoCarteAppFactory',
    '$window',
    'ImportExportFactory',
    'ngDialog',
    '$q',
    '$filter',
    '$rootScope',
    '$timeout',
    'gaUrlUtils',
    'ParametersFactory',
    'ngTableParams',
    'gaDomUtils',
    'EditFactory',
    'QueryFactory',
    'HpoAppServices',
    'ngProgressFactory',
    '$location',
    'InitProvider',
    '$interval',
    'HpoMulticritereServices',
    'HpoAppModelServices',
    'chartFactory',
    'StyleFactory',
    'authFactory',
  ];
  return multicritereRetenuConfig;
});
