'use strict';
define(function() {
  var completenessDataQuantitativeModalite = function(
    HpoCarteAppFactory,
    HpoDataVisServices,
    FeatureTypeFactory,
    $filter,
    gaDomUtils,
    $q,
    $rootScope
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/home_admin_data/views/utilities/data/completenessDataQuantitativeModalite.html',
      restrict: 'EA',
      link: function(scope) {
        const MSG_PREFIX = 'hpo.admin.dashBoardAutomatique';
        let alreadyLoaded = false;
        let directiveFunction = () => {
          if (alreadyLoaded) return;   // éviter 2e chargement
          alreadyLoaded = true; 
          var cfg = HpoCarteAppFactory.getInitProvider().getHpoConfig();
          let defined = false;
          scope.baseMap = cfg.baseMap?cfg.baseMap:'toner-lite';
          let ftiStat;
          let ftiStatdefail;
          scope.portalid = $rootScope.xgos.portal.uid;


          const setBoxDiagram0 = (res, colors) => {
            let dataQuantitativeModalite = [];
            let i=0;
            Object.keys(res.data['quantitativeModalite']).forEach(key => {
              let trace = {
                y: res.data['quantitativeModalite'][key],
                type: 'box',
                name: key,
                marker: {color: colors[i++]},
              };
              dataQuantitativeModalite.push(trace);
            });

            let layoutQuantitativeModalite = {};

            Plotly.newPlot('quantitativeModalite', dataQuantitativeModalite,
              layoutQuantitativeModalite);
            scope.quantitativeModalite = true;
          };


          scope.boxDiagram1Draw = () => {
            // Supprimer l'ancien code de traçage
            let dataQuantitativeModalite = []; // Réinitialiser le tableau

            for (const modalite of scope.quantitativeModaliteData) {
              if (!modalite.showBox){
                continue;
              }
              const stats = modalite.stats;
              const allValues = [
                stats.min,
                stats.q1,
                stats.median,
                stats.q3,
                stats.max,
                ...stats.aberrations
              ].filter(v => v !== null && v !== undefined);

              dataQuantitativeModalite.push({
                y: allValues,
                type: 'box',
                name: modalite.name,
                marker: {
                  color: modalite.color,
                  size: 8
                },
                boxpoints: stats.aberrations.length > 0 ? 'suspectedoutliers' : false,
                // Pour forcer l'affichage des boîtes même avec peu de données
                boxmean: false,
                jitter: 0.3,
                pointpos: 0 //,
                //boxpoints: 'all' // Affiche tous les points
              });
            }

            // Configuration du layout pour Plotly 2.4.2
            let layoutQuantitativeModalite = {
              title: 'Statistiques descriptives',
              yaxis: {
                title: 'Valeurs',
                gridcolor: '#e0e0e0',
                showgrid: true,
                zeroline: false
              },
              showlegend: true,
              legend: {
                orientation: 'v',
                y: 1.1
              },
              margin: {
                t: 50,
                b: 50,
                l: 50,
                r: 50
              }
            };

            // Détruire l'ancien graphique
            const element = document.getElementById('quantitativeModalite');
            if (element && element.data) {
              Plotly.purge('quantitativeModalite');
            }

            // Créer le nouveau graphique
            Plotly.newPlot('quantitativeModalite', dataQuantitativeModalite,
              layoutQuantitativeModalite);
          };


          const setBoxDiagram1 = (res, colors) => {
            scope.showFieldChoice = false;
            scope.quantitativeModaliteData = [];
            // Créer les traces pour Plotly 2.4.2
            Object.entries(res.data.quantitativeModalite).forEach(([key, stats], index) => {
              scope.quantitativeModaliteData.push({
                name: key,
                showBox: true,
                stats: stats,
                color: colors[index % colors.length]
              });
            });
            scope.boxDiagram1Draw();
          };


          const setBoxDiagram = (res, colors) => {
            if (res.data.version && res.data.version==='avec pgsql') {
              setBoxDiagram1(res, colors) ;
            }
            else {
              setBoxDiagram0(res, colors) ;
            }
          };


          if(scope.objStandardisation){
            defined = true;
            scope.components = {
              uidJeu: HpoCarteAppFactory.getAppFactory().getFeatureTypes(
                'jeu_de_donnee'
              )[0].uid,
              identifiantJeuDonnee: scope.objStandardisation.properties.SELECTED_JEU,
              composant: scope.objStandardisation.properties.COMPOSANT,
              cfg: cfg,
              s3: true,
              type:'standardisation'
            };
            ftiStat
              = FeatureTypeFactory.getFeatureByName(scope.objStandardisation.properties.COMPOSANT);
            ftiStat.visible = true;
            let resource = HpoCarteAppFactory.getAppFactory().getResourceFromUidCana(ftiStat.uid);
            ftiStatdefail = FeatureTypeFactory.getFeatureByUid(resource.defail_uid);
            ftiStatdefail.visible = true;
          }
          else if( cfg.ftiStatuid || cfg.ftiStatdefailuid){
            defined = true;
            scope.components = {
              canalisation: cfg.ftiStatuid,
              defailcanalisation: cfg.ftiStatdefailuid,
              cfg: cfg,
              s3: false
            };
            ftiStat = FeatureTypeFactory.getFeatureByUid(cfg.ftiStatuid);
            ftiStat.visible = true;
            if(cfg.ftiStatdefailuid){
              ftiStatdefail = FeatureTypeFactory.getFeatureByUid(cfg.ftiStatdefailuid);
              ftiStatdefail.visible = true;
            }
          }
          if (defined){
            scope.previewftis = [ftiStat];
            if(cfg.ftiStatdefailuid){
              scope.previewftis.push(ftiStatdefail);
            }
            const colors = ['#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1',
              '#296d8a','#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
              '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb','#9986b3',
              '#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
              '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a',
              '#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
              '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb',
              '#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
              '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a',
              '#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
              '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb',
              '#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
              '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a',
              '#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
              '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb',
              '#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8',
              '#EB5389','#47B8DD','#eb795e','#289E75','#46ebb1','#296d8a',
              '#96B1FA','#EDB3A6','#42616b','#EBBA34','#c0504d','#9bbb59',
              '#9986B3','#fa9b2f','#be6fa0','#6d607f','#c9ffa6','#4095cb',
              '#9986b3','#62ddff','#b8406a','#89E3FA','#5bcfbd','#EE9BB8'];
            const colorCompletude = ['#9BC9DD','#EE9BB8','#6D607F','#71E3DB',
              '#46ebb','#be6fa0','#96B1FA','#EDB3A6','#42616b','#9bbb59',
              '#c0504d','#89E3FA','#9986B3','#296d8a','#be6fa0','#6d607f',
              '#c9ffa6','#4095cb','#9986b3','#9BC9DD','#b8406a','#fa9b2f','#5bcfbd','#EE9BB8'];
            let promises = [];
            gaDomUtils.showGlobalLoader();
            let promiseAutoCompletude
              = HpoDataVisServices.getStatsDashboardAutoCompletude(scope.components).then((res)=>{
                var trace5 = {
                  x: Object.keys(res.data['completude']),
                  y: Object.values(res.data['completude']),
                  name: $filter('translate')(MSG_PREFIX + '.presenceData'),
                  type: 'bar',
                  marker: {color: '#9BC9DD'}
                };

                var trace6 = {
                  x: Object.keys(res.data['nonCompletude']),
                  y: Object.values(res.data['nonCompletude']),
                  name: $filter('translate')(MSG_PREFIX + '.noData'),
                  type: 'bar',
                  marker: {color: '#EB795E'}
                };

                var data5 = [trace5, trace6];

                var layout5 = {barmode: 'stack',yaxis: {
                  title: {
                    text: $filter('translate')(MSG_PREFIX + '.completenessPercentage')
                  },
                }};

                Plotly.newPlot('completenessData', data5, layout5);
                scope.completenessData = true;
                let size = 0;
                Object.values(res.data['completudeModalite']).forEach(val=> {
                  size = Object.values(val).length>size?Object.values(val).length:size;
                });
                var data6 = [];
                for (let i = 0; i < size; i++) {
                  let values= [];
                  let keys= [];
                  Object.values(res.data['completudeModalite']).forEach(key => {
                    if(Object.keys(key).length>=i && Object.keys(key)[i] !='nan'){
                      values.push((key[Object.keys(key)[i]]/1000).toFixed(2));
                      keys.push(Object.keys(key)[i]);
                    }
                    else {
                      values.push(0);
                      keys.push('');
                    }
                  });
                  var trace8 = {
                    y: Object.keys(res.data['completudeModalite']),
                    x: values,
                    orientation: 'h',
                    type: 'bar',
                    text:keys,
                    marker: {color: colorCompletude[i]},
                  };
                  data6.push(trace8);
                }
                let values= [];
                let keys= [];
                Object.values(res.data['completudeModalite']).forEach(key => {
                  values.push(key['nan']/1000);
                  keys.push('Nan');
                });
                trace8 = {
                  y: Object.keys(res.data['completudeModalite']),
                  x: values,
                  orientation: 'h',
                  type: 'bar',
                  text:keys,
                  marker: {color: '#EB795E'},
                };
                data6.push(trace8);

                let completudeModaliteLength = Object.keys(res.data['completudeModalite']).length;

                var layout6 = {
                  barmode: 'stack',
                  showlegend: false,
                  xaxis: {
                    title: {
                      text: $filter('translate')(MSG_PREFIX + '.totalLengthOfTheNetwork')
                    },
                  }
                };

                if(completudeModaliteLength>15){
                  layout6.height = completudeModaliteLength *25;
                }

                Plotly.newPlot('completenessDataDistribution', data6, layout6);
                scope.completenessDataDistribution = true;

                // -- Diagramme à moustaches
                setBoxDiagram(res, colors);
              });
            promises.push(promiseAutoCompletude);
            $q.all(promises).then(()=>{
              gaDomUtils.hideGlobalLoader();
            }, () =>{
              gaDomUtils.hideGlobalLoader();
            });
          }
        };
        scope.$on("PRELOAD_COMPLETENESS", () => {
          if (!alreadyLoaded) {
            directiveFunction();
          }
        }); 
        // Chargement normal si l’utilisateur ouvre l’onglet avant le préchargement
        if (!alreadyLoaded) {
          directiveFunction();
        } 
        // on reload la fonction quand on change la langue en locale
        $rootScope.$on('localeChanged', () => {
          directiveFunction();
        });
      },
    };
  };

  completenessDataQuantitativeModalite.$inject = [
    'HpoCarteAppFactory',
    'HpoDataVisServices',
    'FeatureTypeFactory',
    '$filter',
    'gaDomUtils',
    '$q',
    '$rootScope'
  ];
  return completenessDataQuantitativeModalite;
});
