'use strict';
define(function() {
  var multicritereAutomatisationConfig = 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
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/analye_multicritere/views/directives/multicritere_automatisation_config.html',
      restrict: 'EA',
      scope: {
        res: '=?',
        withDatatable: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        /**
         * Module Config
         * @type {[type]}
         */
        scope.hpoSimplifyVisualize = scope.$parent.$parent.hpoSimplifyVisualize;
        scope.configName =
          HpoCarteAppFactory.getAppFactory().getAppname() +
          '_' +
          'HpoAutomatisationCritereaConfig';
        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 = { geoj: undefined };
        scope.getReturnedTemplate = function(dataHpo) {
          if (dataHpo) {
            if (dataHpo.savedata.uid) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(dataHpo.savedata.uid);
              if (~idx) {
                dataHpo.savedata.fti = scope.ftis[idx];
              } else {
                AlertHpoFactory.showAlertTemplateUpdate();
                dataHpo.savedata.fti = undefined;
                dataHpo.savedata.uid = 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.uid = undefined;
              }
            }
            scope.currentParameter = angular.copy(dataHpo.savedata);
            scope.currentParameter.fti = dataHpo.savedata.fti;
            scope.changedFti(true);
            scope.currentParameter.attributesSelection.map(function(attr) {
              if (attr && attr.name === 'materiau')
                scope.getValuesAttributes(
                  scope.currentParameter.fti,
                  attr.selection
                );
            });
          }
        };

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

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

        /**
         * Get required ftis
         * @type {Array}
         */
        scope.fti_correspondance = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'correspondance'
        )[0];
        scope.fti_correspondanceattributes = scope.fti_correspondance.attributes.filter(
          function(x) {
            if (
              x &&
              ((HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                scope.fti_correspondance.name
              ) &&
                HpoCarteAppFactory.getAppFactory()
                  .getExcludedAttributes(scope.fti_correspondance.name)
                  .indexOf(x.name) === -1) ||
                !HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                  scope.fti_correspondance.name
                ))
            )
              return x;
          }
        );
        var fti_correspondance_item = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'correspondance_items'
        )[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 fti_compare = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'compare'
        )[0];
        var fti_priority = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'priority'
        )[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.ftiAuto = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'auto'
        )[0];
        scope.ftiAutoattributes = scope.ftiAuto.attributes.filter(function(x) {
          if (
            x &&
            ((HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
              scope.ftiAuto.name
            ) &&
              HpoCarteAppFactory.getAppFactory()
                .getExcludedAttributes(scope.ftiAuto.name)
                .indexOf(x.name) === -1) ||
              !HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                scope.ftiAuto.name
              ))
          )
            return x;
        });
        scope.translateFtiAttributes = HpoCarteAppFactory.getAppFactory().getTranslateAttributes(
          scope.ftiAuto.name
        );
        scope.hideFilter = Object.keys(scope.translateFtiAttributes);
        scope.ftis = HpoCarteAppFactory.getAppFactory().getMulticritereFtis();

        var configuredData = HpoCarteAppFactory.getInitProvider().getHpoConfig();

        scope.attributestouseindatatable = HpoCarteAppFactory.getAppFactory().getCreationAutoAttributes();
        scope.attrstotranslate = HpoCarteAppFactory.getAppFactory().HPO_DIVERS_PARAMS();
        /**
         * Init object
         * @type {Object}
         */
        scope.emptyParameter = function(btn) {
          if (btn) {
            var callback = function(isconfirm) {
              if (isconfirm) {
                scope.currentParameter = scope.res || {
                  fti: undefined,
                  categorie: undefined,
                  commentaire: undefined,
                  useprevision: 'prevision',
                  usenombre: 'nombre',
                  previsionmethod: 'rsf',
                  geoj: undefined,
                };
                if (!scope.ftiprevision || !scope.ftiprevision.uid) {
                  scope.currentParameter.useprevision = 'attribute';
                  scope.currentParameter.previsionmethod = undefined;
                }
                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 || {
              fti: undefined,
              categorie: undefined,
              commentaire: undefined,
              useprevision: 'prevision',
              usenombre: 'nombre',
              previsionmethod: 'rsf',
              geoj: undefined,
            };
            if (!scope.ftiprevision || !scope.ftiprevision.uid) {
              scope.currentParameter.useprevision = 'attribute';
              scope.currentParameter.previsionmethod = undefined;
            }
            if (scope.currentParameter.uid) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(scope.currentParameter.uid);
              if (~idx) scope.currentParameter.fti = scope.ftis[idx];

              scope.changedFti(true);
              scope.currentParameter.attributesSelection.map(function(attr) {
                if (attr && attr.name === 'materiau')
                  scope.getValuesAttributes(
                    scope.currentParameter.fti,
                    attr.selection
                  );
              });
            }
          }
        };

        scope.getValuesAttributes = function(fti, attribute) {
          if (attribute) {
            gaDomUtils.showGlobalLoader();
            var promise = QueryFactory.dataattributeCorrectedDate(
              fti.uid,
              attribute
            );
            promise.then(
              function(res) {
                if (res.data.length > 0) {
                  scope.attributeMateriaux = res.data;
                  if (!scope.currentParameter.amianteciment) {
                    scope.currentParameter.amianteciment = HpoCarteAppFactory.getAppFactory().getBestScore(
                      scope.attributeMateriaux,
                      'amiante'
                    );
                    if (!scope.currentParameter.amianteciment)
                      scope.currentParameter.amianteciment = HpoCarteAppFactory.getAppFactory().getBestScore(
                        scope.attributeMateriaux,
                        'ciment'
                      );
                    if (!scope.currentParameter.amianteciment)
                      scope.currentParameter.amianteciment = HpoCarteAppFactory.getAppFactory().getBestScore(
                        scope.attributeMateriaux,
                        'amc'
                      );
                  }
                } else {
                  scope.attributeMateriaux = [];
                }
                gaDomUtils.hideGlobalLoader();
              },
              function(res) {
                scope.attributeMateriaux = [];
                gaDomUtils.hideGlobalLoader();
              }
            );
          }
        };

        scope.getAvailablePrevision = function(fti) {
          var where = '"FINALISER" = TRUE';
          if (scope.ftiprevision && scope.ftiprevision.uid) {
            HpoAppModelServices.getAvailablePrevions(
              fti.uid,
              scope.ftiprevision.uid,
              ftijeudonnee.uid,
              ftimodele.uid,
              where
            ).then(
              function(res) {
                if (res && res.data) {
                  scope.previsions = res.data.features;
                  if (
                    scope.currentParameter.useprevision === 'prevision' &&
                    !scope.currentParameter.prevision &&
                    scope.previsions.length == 1
                  )
                    scope.currentParameter.prevision =
                      scope.previsions[0].properties.IDENTIFIANT;
                }
              },
              function(res) {
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

        scope.changedFti = function(b) {
          if (scope.currentParameter && scope.currentParameter.fti) {
            if (!b) {
              Object.assign(scope.currentParameter, {
                useprevision: 'prevision',
                usenombre: 'nombre',
                prevision: undefined,
                amianteciment: undefined,
              });
              if (!scope.ftiprevision || !scope.ftiprevision.uid) {
                scope.currentParameter.useprevision = 'attribute';
                scope.currentParameter.previsionmethod = undefined;
              }
            }
            if (
              !scope.currentParameter.attributesSelection ||
              scope.currentParameter.attributesSelection.length == 0
            )
              scope.currentParameter.attributesSelection = HpoCarteAppFactory.getAppFactory().getAttributesForAuto(
                scope.currentParameter.fti
              );
            var idx = scope.currentParameter.attributesSelection
              .map(function(x) {
                return x.name;
              })
              .indexOf('materiau');
            if (~idx)
              scope.getValuesAttributes(
                scope.currentParameter.fti,
                scope.currentParameter.attributesSelection[idx].selection
              );
            scope.getAvailablePrevision(scope.currentParameter.fti);
            scope.attributesAuthorised = HpoCarteAppFactory.getAppFactory().getAuthorizedAttributes(
              scope.currentParameter.fti
            );
          }
        };

        scope.changedMateriau = function(attr) {
          if (attr.name === 'materiau')
            scope.getValuesAttributes(
              scope.currentParameter.fti,
              attr.selection
            );
        };

        scope.changedPrevision = function(useprevision) {
          scope.currentParameter.prevision = undefined;
          if (
            scope.currentParameter.useprevision === 'prevision' &&
            !scope.currentParameter.prevision &&
            scope.previsions.length == 1
          )
            scope.currentParameter.prevision =
              scope.previsions[0].properties.IDENTIFIANT;
        };

        scope.emptyParameter(false);

        scope.keys = ['anneepose', 'longueur', 'materiau', 'diametre'];
        scope.checkInformations = function() {
          if (
            !scope.currentParameter ||
            !scope.currentParameter.fti ||
            !scope.currentParameter.fti.uid
          )
            return true;

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

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

          for (var i = 0; i < scope.keys.length; i++) {
            if (
              scope.currentParameter.hasOwnProperty(scope.keys[i]) &&
              !scope.currentParameter[scope.keys[i]]
            ) {
              return true;
            }
          }

          return false;
        };

        scope.saveInfo = function(currentParameter) {
          var sendata = angular.copy(currentParameter);
          sendata.uid = sendata.fti.uid;
          delete sendata.fti;
          Object.assign(sendata, {
            fti_auto: scope.ftiAuto.uid,
            fti_ponderation: fti_ponderation.uid,
            fti_indicateur: fti_indicateur.uid,
            fti_parametrage: fti_parametrage.uid,
            fti_criterea: fti_criterea.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.createGenericParameters(sendata).then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              if (res.data) {
                scope.currentParameter.geoj = res.data.result;
                AlertHpoFactory.getSimpleSuccess(
                  $filter('translate')('hpo.common.success'),
                  $filter('translate')('hpo.data.prepare.analysissuccess'),
                  false,
                  'info'
                );
              } else {
                scope.currentParameter.geoj = undefined;
                AlertHpoFactory.showErrorMessage(res);
              }
              getExistingNames();
              scope.refreshData();
            },
            function(res) {
              scope.currentParameter.geoj = undefined;
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
              scope.refreshData();
            }
          );
        };

        scope.endMethod = function() {
          var callback = function(isconfirm) {
            if (isconfirm) {
              scope.emptyParameter(false);
              try {
                scope.$apply();
              } catch(err) {}
            }
          };
          var message =
            $filter('translate')('hpo.common.finaliseraction') +
            '. ' +
            $filter('translate')('hpo.common.sur');
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        if (scope.withDatatable)
          scope.correctionAnalysisDatatableCrudHpo = {
            extraActions: [
              {
                name: $filter('translate')('hpo.common.finaliseraction'),
                class: 'btn-default',
                func: scope.endMethod,
              },
            ],
            remove: false,
          };

        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.datatableHeightHistoric =
          angular.element('.xgos_content').height() -
          angular.element('#xgos_nav').height() -
          110 +
          'px';

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

        scope.editAuto = function(obj) {
          if (obj) {
            gaDomUtils.showGlobalLoader();
            var sendata = {};
            Object.assign(sendata, {
              fti_auto: scope.ftiAuto.uid,
              fti_ponderation: fti_ponderation.uid,
              fti_indicateur: fti_indicateur.uid,
              fti_parametrage: fti_parametrage.uid,
              fti_criterea: fti_criterea.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.getAuto(
              scope.ftiAuto.uid,
              obj.id,
              sendata
            ).then(
              function(res) {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data) {
                  if (res.data.uid) {
                    var idx = scope.ftis
                      .map(function(x) {
                        return x.uid;
                      })
                      .indexOf(res.data.ftiuid);
                    if (~idx) res.data.fti = scope.ftis[idx];
                  }
                  var newScope = $rootScope.$new();
                  newScope.res = res.data;
                  var dialog = ngDialog.open({
                    template:
                      'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.automatisation.info.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: newScope,
                  });
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

        scope.datatableCalageCrudHpo = {
          update: { func: scope.editAuto },
          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.editPrevision = function(obj) {
          if (obj && scope.ftiprevision && scope.ftiprevision.uid) {
            gaDomUtils.showGlobalLoader();
            HpoAppModelServices.getPrevision(
              scope.ftiprevision.uid,
              obj.properties.IDENTIFIANT,
              obj.properties.IDENTIFIANT_MODELE,
              obj.properties.IDENTIFIANT_CALAGE,
              ftijeudonnee.uid,
              ftimodele.uid,
              fticalage.uid
            ).then(
              function(res) {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data) {
                  scope.newCurrentModel = res.data;
                  if(scope.hpoSimplifyVisualize){
                    scope.newCurrentModel.fti.attributes = scope.newCurrentModel.fti.attributes.filter(
                    function(x){
                      if(x.name.indexOf("_cox") == -1) return x
                    })
                  }
                  if (
                    scope.newCurrentModel &&
                    scope.newCurrentModel.status &&
                    scope.newCurrentModel.status !== 'FINISHED'
                  ) {
                    switch (scope.newCurrentModel.status) {
                      case 'FAILED':
                        scope.newCurrentModel.message =
                          $filter('translate')('hpo.model.calage.failed') +
                          ' ' +
                          scope.newCurrentModel.step +
                          '. ' +
                          $filter('translate')('hpo.model.calage.reason') +
                          ' ' +
                          scope.newCurrentModel.raison;
                        break;
                      case 'RUNNING':
                        scope.newCurrentModel.message = $filter('translate')(
                          'hpo.model.calage.running'
                        );
                        break;
                    }
                  } else {
                    scope.tableName = HpoCarteAppFactory.getAppFactory().getPrevisionTableName(
                      scope.newCurrentModel.identifiantcalage,
                      scope.newCurrentModel.identifiantprevision
                    );
                    scope.newCurrentModel.duree = HpoCarteAppFactory.getAppFactory().differenceDates(
                      scope.newCurrentModel.datestartsimulation,
                      scope.newCurrentModel.dateendsimulation
                    );
                  }
                  var dialog = ngDialog.open({
                    template:
                      'js/XG/widgets/hpoapp/model/views/dialog/hpo.model.prevision.info.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: scope,
                  });
                }
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

        scope.exstingNames = [];
        var getExistingNames = function() {
          gaDomUtils.showGlobalLoader();
          var where = '';
          if (scope.currentParameter && scope.currentParameter.categorie)
            where +=
              ' NOT ("CATEGORIE" = \'' +
              scope.currentParameter.categorie +
              "')";
          QueryFactory.dataattributeCorrectedDate(
            scope.ftiAuto.uid,
            'CATEGORIE',
            where
          ).then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              if (res && res.data) {
                scope.exstingNames = res.data;
              } else {
                AlertHpoFactory.showErrorMessage(res);
              }
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };
        getExistingNames();

        scope.postRemove = function(resultat) {
          getExistingNames();
        };
        scope.end = true;
      },
    };
  };

  multicritereAutomatisationConfig.$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',
  ];
  return multicritereAutomatisationConfig;
});
