'use strict';
define(function() {
  var modelValidationHpo = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    HpoCarteAppFactory,
    $window,
    ImportExportFactory,
    ngDialog,
    $q,
    $filter,
    $rootScope,
    $timeout,
    gaUrlUtils,
    HpoAppModelServices,
    gaDomUtils,
    QueryFactory,
    InitProvider,
    chartFactory,
    EditFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/model/views/directives/model/model_validation_hpo.html',
      restrict: 'EA',
      scope: {
        model: '=?',
        uniqueElement: '=?',
        whereFilter: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.hpoSimplifyVisualize = scope.$parent.$parent.hpoSimplifyVisualize;
        scope.ended = false;
        scope.ftihistory = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'modal_historic'
        )[0];
        scope.ftijeudonnee = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'jeu_de_donnee'
        )[0];
        scope.fticalage = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'calage'
        )[0];
        scope.ftivalidation = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'validation'
        )[0];
        scope.ftivalidationattributes = scope.ftivalidation.attributes.filter(
          function(x) {
            if (
              x &&
              ((HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                scope.ftivalidation.name
              ) &&
                HpoCarteAppFactory.getAppFactory()
                  .getExcludedAttributes(scope.ftivalidation.name)
                  .indexOf(x.name) === -1) ||
                !HpoCarteAppFactory.getAppFactory().getExcludedAttributes(
                  scope.ftivalidation.name
                ))
            )
              return x;
          }
        );
        scope.ftiprevsion = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'prevision'
        )[0];
        scope.translateFtiAttributes = HpoCarteAppFactory.getAppFactory().getTranslateAttributes(
          scope.ftivalidation.name
        );
        scope.hideFilter = Object.keys(scope.translateFtiAttributes);

        scope.tabs = [
          {
            title: 'hpo.model.calage.informations',
          },
          {
            title: 'hpo.model.calage.historic',
          },
        ];
        scope.tabs.activeTab = 0;

        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',
            },
          },
        ];

        Array.prototype.sum = function() {
          var ar = this;
          var sum = 0;
          for (var i = 0; i < ar.length; i++) {
            sum += parseFloat(ar[i]); //don't forget to add the base
          }
          return sum;
        };

        scope.changedOrder = function(neworder) {
          if (neworder === 'nombre') {
            scope.newCurrentModel.chartOpt.chart.xAxis.axisLabel = $filter(
              'translate'
            )('hpo.common.nbcasses');
            scope.newCurrentModel.chartOpt.chart.yAxis.axisLabel = $filter(
              'translate'
            )('hpo.common.evite');
            scope.newCurrentModel.chartOpt.title.text = $filter('translate')(
              'hpo.common.evitetitle'
            );
          } else {
            scope.newCurrentModel.chartOpt.chart.xAxis.axisLabel = $filter(
              'translate'
            )('hpo.common.nbcasseslng');
            scope.newCurrentModel.chartOpt.chart.yAxis.axisLabel = $filter(
              'translate'
            )('hpo.common.evite');
            scope.newCurrentModel.chartOpt.title.text = $filter('translate')(
              'hpo.common.evitetitlelng'
            );
          }
        };

        var calcRapportTaux = function(
          percentage,
          data,
          name,
          longueur,
          nb_casses_pred,
          nb_casses
        ) {
          var values = Object.values(data[name][longueur]);
          var p = values.length;
          for (var i = 0; i < values.length; i++) {
            if (values[i] >= percentage) {
              p = i;
              break;
            }
          }
          return (
            Object.values(data[name][nb_casses_pred])
              .slice(0, p)
              .sum() /
            Object.values(data[name][nb_casses])
              .slice(0, p)
              .sum()
          );
        };

        scope.changedAirePercentage = function(percentage, type) {
          if (
            angular.isUndefined(percentage) ||
            percentage > 100 ||
            percentage < 0
          ) {
            scope.newCurrentModel.percentage = 100;
            percentage = 100;
            require('toastr').info(
              $filter('translate')('hpo.common.calculatedairemax')
            );
          }
          switch (type) {
            case 'nombre':
              var v = Object.values(
                scope.newCurrentModel.validationInfo.values[type].fitcox
                  .nb_casses
              ).length;
              var p = Math.round((v * percentage) / 100);
              scope.newCurrentModel.validationInfo.rapport[type][
                'calculated'
              ] = {};
              if (
                Object.values(
                  scope.newCurrentModel.validationInfo.values[type].fitcox[
                    'nb_casses'
                  ]
                )
                  .slice(0, p)
                  .sum() > 0
              )
                scope.newCurrentModel.validationInfo.rapport[type][
                  'calculated'
                ].fitcox =
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type].fitcox[
                      'nb_casses_cox'
                    ]
                  )
                    .slice(0, p)
                    .sum() /
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type].fitcox[
                      'nb_casses'
                    ]
                  )
                    .slice(0, p)
                    .sum();
              if (
                Object.values(
                  scope.newCurrentModel.validationInfo.values[type].fitcox_surv[
                    'nb_casses'
                  ]
                )
                  .slice(0, p)
                  .sum()
              )
                scope.newCurrentModel.validationInfo.rapport[type][
                  'calculated'
                ].fitcox_surv =
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type]
                      .fitcox_surv['nb_casses_cox_survival']
                  )
                    .slice(0, p)
                    .sum() /
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type]
                      .fitcox_surv['nb_casses']
                  )
                    .slice(0, p)
                    .sum();
              if (
                Object.values(
                  scope.newCurrentModel.validationInfo.values[type].rsf[
                    'nb_casses'
                  ]
                )
                  .slice(0, p)
                  .sum()
              )
                scope.newCurrentModel.validationInfo.rapport[type][
                  'calculated'
                ].rsf =
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type].rsf[
                      'nb_casses_rsf'
                    ]
                  )
                    .slice(0, p)
                    .sum() /
                  Object.values(
                    scope.newCurrentModel.validationInfo.values[type].rsf[
                      'nb_casses'
                    ]
                  )
                    .slice(0, p)
                    .sum();
              break;
            case 'taux':
              if (
                !scope.newCurrentModel.validationInfo.rapport[
                  type
                ].hasOwnProperty('calculated')
              )
                scope.newCurrentModel.validationInfo.rapport[type][
                  'calculated'
                ] = {};
              scope.newCurrentModel.validationInfo.rapport[type][
                'calculated'
              ].fitcox = calcRapportTaux(
                percentage,
                scope.newCurrentModel.validationInfo.values[type],
                'fitcox',
                'longueur_cumul_fitcox',
                'nb_casses_cox',
                'nb_casses'
              );
              scope.newCurrentModel.validationInfo.rapport[type][
                'calculated'
              ].fitcox_surv = calcRapportTaux(
                percentage,
                scope.newCurrentModel.validationInfo.values[type],
                'fitcox_surv',
                'longueur_cumul_fitcox_surv',
                'nb_casses_cox_survival',
                'nb_casses'
              );
              scope.newCurrentModel.validationInfo.rapport[type][
                'calculated'
              ].rsf = calcRapportTaux(
                percentage,
                scope.newCurrentModel.validationInfo.values[type],
                'rsf',
                'longueur_cumul_rsf',
                'nb_casses_rsf',
                'nb_casses'
              );
              break;
          }

          require('toastr').success(
            $filter('translate')('hpo.common.calculatedaire')
          );
        };

        scope.editValidation = function(obj) {
          if (obj) {
            gaDomUtils.showGlobalLoader();
            HpoAppModelServices.getValidation(
              scope.ftivalidation.uid,
              obj.properties.IDENTIFIANT,
              obj.properties.IDENTIFIANT_MODELE,
              scope.ftijeudonnee.uid,
              scope.ftihistory.uid
            ).then(
              function(res) {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data && !res.data.code && res.data.code != 500) {
                  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 !== '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.newCurrentModel.chartOpt = chartFactory.getLineOption(
                      500,
                      500
                    );
                    scope.newCurrentModel.chartOpt.chart.xAxis.domain = [0, 1];
                    scope.newCurrentModel.chartOpt.chart.xAxis.range = [0, 1];
                    scope.newCurrentModel.chartOpt.chart.xAxis.axisLabel = $filter(
                      'translate'
                    )('hpo.common.nbcasses');
                    scope.newCurrentModel.chartOpt.chart.xAxis.tickSize = 6;
                    scope.newCurrentModel.chartOpt.chart.yAxis.domain = [0, 1];
                    scope.newCurrentModel.chartOpt.chart.yAxis.range = [0, 1];
                    scope.newCurrentModel.chartOpt.chart.yAxis.axisLabel = $filter(
                      'translate'
                    )('hpo.common.evite');
                    scope.newCurrentModel.chartOpt.chart.showLegend = true;
                    scope.newCurrentModel.chartOpt.title.enable = true;
                    scope.newCurrentModel.chartOpt.title.className = 'h5';
                    scope.newCurrentModel.chartOpt.title.text = $filter(
                      'translate'
                    )('hpo.common.evitetitle');
                    scope.newCurrentModel.percentage = 100;
                    scope.neworder = 'nombre';
                    scope.types = [];
                    var rsfFunc;
                    if (
                      res.data &&
                      res.data.validationInfo &&
                      res.data.validationInfo.nombre
                    ) {
                      for (var key in res.data.validationInfo.nombre) {
                        if (
                          key &&
                          res.data.validationInfo.nombre.hasOwnProperty(key) &&
                          res.data.validationInfo.nombre[key]
                        ) {
                          if(!scope.hpoSimplifyVisualize || key === 'rsf'){
                            switch (key) {
                              case 'fitcox':
                                var position = 1;
                                break;
                              case 'fitcoxsurv':
                                var position = 2;
                                break;
                              case 'rsf':
                                var position = 0;
                                break;
                            }
                            var d = {
                              id: key,
                              alias: $filter('translate')('hpo.common.' + key),
                              position: position,
                            };
                            if (key === 'rsf') scope.newval = d;
                            scope.types.push(d);
                          }
                        }
                      }
                    }
                    if (!scope.newval && scope.types.length > 0)
                      scope.newval = scope.types[0];
                    scope.tableName = HpoCarteAppFactory.getAppFactory().getValidationTableName(
                      scope.newCurrentModel.identifiantdata,
                      scope.newCurrentModel.identifiantcalage
                    );
                    if (
                      scope.newCurrentModel.validationInfo &&
                      scope.newCurrentModel.validationInfo.rapport &&
                      scope.newCurrentModel.validationInfo.rapport['nombre']
                    ) {
                      scope.extractedValue = Object.keys(
                        scope.newCurrentModel.validationInfo.rapport['nombre']
                      );
                      scope.extractedValue = scope.extractedValue.map(function(
                        x
                      ) {
                        return parseFloat(x);
                      });
                      scope.extractedValue.sort(sortNumber);
                      scope.extractedValueMessage = 'ok';
                    } else {
                      scope.extractedValue = [];
                      scope.extractedValueMessage =
                        scope.newCurrentModel.validationInfo;
                    }
                    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.validation.info.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: scope,
                  });
                } else {
                  AlertHpoFactory.showErrorMessage(res);
                }
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

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

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

        scope.datatableCalageCrudHpo = {
          update: { func: scope.editValidation },
          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,
            },
          ],
        };

        var keys = [
          'name',
          'commentaire',
          'namedata',
          'namecalage',
          'commentairedata',
          'commentairecalage',
          'fti',
          'ftidefail',
        ];
        scope.disableAnalyseButton = function(currentModel) {
          if (!currentModel) return true;

          var noexists = false;
          for (var i = 0; i < keys.length; i++) {
            if (!currentModel.hasOwnProperty(keys[i])) {
              noexists = true;
              break;
            }
          }
          if (
            !currentModel ||
            !currentModel.editTypeList ||
            !currentModel.editTypeList.rightData ||
            currentModel.editTypeList.rightData.length === 0
          )
            noexists = true;
          return noexists;
        };

        function sortNumber(a, b) {
          return a - b;
        }

        $timeout(function() {
          scope.height =
            angular.element('.xgos_content').height() -
            angular.element('.nav.nav-tabs').height() -
            angular.element('.gcDatatableCrud').height() -
            angular.element('.add-border').height() -
            110 +
            'px';
          angular.element('.contenu-hpo').height(scope.height);
        }, 500);
        scope.ended = true;

        scope.finaliserStep = function(newCurrentModel) {
          gaDomUtils.showGlobalLoader();
          HpoAppModelServices.updateValue(
            scope.fticalage.uid,
            scope.ftivalidation.uid,
            newCurrentModel.identifiantcalage,
            'FINALISER',
            'boolean',
            true
          ).then(
            function(res) {
              gaDomUtils.hideGlobalLoader();
              if (res.data && JSON.parse(res.data)) {
                newCurrentModel.finaliser = true;
                AlertHpoFactory.successUpdate();
                $rootScope.$broadcast(
                  'reloadDatatable',
                  scope.ftivalidation.uid
                );
              } else {
                AlertHpoFactory.showErrorMessage(res);
              }
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        scope.postRemove = function(resultat) {
          var identifiants = resultat
            .map(function(x) {
              return x.properties.IDENTIFIANT;
            })
            .join("','");
          $timeout(function() {
            var callback = function(confirmed) {
              if (confirmed) {
                var where = '"IDENTIFIANT" IN (\'' + identifiants + "')";
                gaDomUtils.showGlobalLoader();
                EditFactory.deleteWhere(scope.fticalage.uid, where).then(
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    AlertHpoFactory.successDelete();
                    $timeout(function() {
                      var callback = function(confirmed) {
                        if (confirmed) {
                          var where =
                            '"IDENTIFIANT_CALAGE" IN (\'' + identifiants + "')";
                          gaDomUtils.showGlobalLoader();
                          EditFactory.deleteWhere(
                            scope.ftiprevsion.uid,
                            where
                          ).then(
                            function(res) {
                              gaDomUtils.hideGlobalLoader();
                              AlertHpoFactory.successDelete();
                            },
                            function(res) {
                              gaDomUtils.hideGlobalLoader();
                              AlertHpoFactory.showErrorMessage(res);
                            }
                          );
                        }
                      };
                      AlertHpoFactory.alertConfirmCallback(
                        $filter('translate')('hpo.common.info'),
                        $filter('translate')(
                          'hpo.model.validation.removeprevision'
                        ),
                        'info',
                        true,
                        undefined,
                        '#F50072',
                        true,
                        undefined,
                        undefined,
                        true,
                        true,
                        callback
                      );
                    }, 2000);
                  },
                  function(res) {
                    gaDomUtils.hideGlobalLoader();
                    AlertHpoFactory.showErrorMessage(res);
                  }
                );
              } else {
                $timeout(function() {
                  var callback = function(confirmed) {
                    if (confirmed) {
                      var where =
                        '"IDENTIFIANT_CALAGE" IN (\'' + identifiants + "')";
                      gaDomUtils.showGlobalLoader();
                      EditFactory.deleteWhere(
                        scope.ftiprevsion.uid,
                        where
                      ).then(
                        function(res) {
                          gaDomUtils.hideGlobalLoader();
                          AlertHpoFactory.successDelete();
                        },
                        function(res) {
                          gaDomUtils.hideGlobalLoader();
                          AlertHpoFactory.showErrorMessage(res);
                        }
                      );
                    }
                  };
                  AlertHpoFactory.alertConfirmCallback(
                    $filter('translate')('hpo.common.info'),
                    $filter('translate')(
                      'hpo.model.validation.removeprevision'
                    ),
                    'info',
                    true,
                    undefined,
                    '#F50072',
                    true,
                    undefined,
                    undefined,
                    true,
                    true,
                    callback
                  );
                }, 2000);
              }
            };
            AlertHpoFactory.alertConfirmCallback(
              $filter('translate')('hpo.common.info'),
              $filter('translate')('hpo.model.validation.removecalage'),
              'info',
              true,
              undefined,
              '#F50072',
              true,
              undefined,
              undefined,
              true,
              true,
              callback
            );
          }, 2000);
        };
      },
    };
  };

  modelValidationHpo.$inject = [
    'AlertHpoFactory',
    'FeatureTypeFactory',
    'HpoCarteAppFactory',
    '$window',
    'ImportExportFactory',
    'ngDialog',
    '$q',
    '$filter',
    '$rootScope',
    '$timeout',
    'gaUrlUtils',
    'HpoAppModelServices',
    'gaDomUtils',
    'QueryFactory',
    'InitProvider',
    'chartFactory',
    'EditFactory',
  ];
  return modelValidationHpo;
});
