'use strict';

define(function() {
  var AUDCtrl = function(
    $scope,
    FeatureTypeFactory,
    gaJsUtils,
    BacAppFactory,
    $timeout) {
    /*******************************************************************************
     *    Ftis
     * ********************************************************************************/
    $scope.activitePrincipaleEtablissementFti = FeatureTypeFactory.getFeatureByUid(
      'kis_bac_etablissement_activite_principale'
    );

    $scope.kis_bac_listes_deroulantes_controles = FeatureTypeFactory.getFeatureByUid(
      'kis_bac_listes_deroulantes_controles'
    );

    $scope.etablissementFti = FeatureTypeFactory.getFeatureByUid(
      'kis_bac_etablissement'
    );
    /**
     *Ajouter une ligne
     */
    $scope.addLines = function(number, type, indice) {
      for (let i = 0; i < number; i++) {
        switch(type) {
          case 'tableau_majoration':
          case 'tableau_pollution':
          case 'tableau_rejet': {
            $scope.cdata[type].push({
              numero_branchement: '',
              methode_calcul: '',
              valeur_coefficient: '',
            });
            break;
          }
          case 'tableaux_parametres_eaux_pluviale':{
              $scope.cdata.tableaux_parametres_eaux_pluviale[indice]
                .parameters.push({
                  autosurveillance_parametre_ep: '',
                  autosurveillance_sandre_ep: '',
                  autosurveillance_limite_ep: '',
                  flux_limite: '',
                  frequence_analyse: '',
                  modalites: ''
                });
              break;
            }
          case 'tableaux_parametres_eaux_uses':{
            $scope.cdata.tableaux_parametres_eaux_uses[indice]
              .parameters.push({
                autosurveillance_parametre_eu: '',
                autosurveillance_sandre_eu: '',
                autosurveillance_limite_eu: '',
                flux_limite: '',
                frequence_analyse: '',
                modalites: ''
              });
            break;
          }
          case 'points_rejet': {
              $scope.cdata[type].push({
                rejet_branchement_type: null,
                rejet_branchement_adresse: '',
                rejet_branchement_localisation: {},
                rejet_niveau_evacuation: {},
                rejet_clapet: {},
                commentaire: '',
              });
              break;
            }
          case 'transmission_etablissement': {
              $scope.cdata[type].push({
                date_transmission: null,
                objet_transmission: {},
                destinaire_transmission: {},
                commentaire: '',
              });
              break;
            }
          case 'eaux_usees': {
              $scope.cdata[type].push({
                eaux_usees_origine_rejet: null,
                eaux_usees_caracteristiques_effluents: {},
                eaux_usees_type_ouvrage: {},
                eaux_usees_localisation: '',
                eaux_usees_dimensions: '',
                eaux_usees_entretien: {},
                eaux_usees_avis: {},
                commentaire: '',
              });
              break;
            }
          case 'eaux_pluviales': {
              $scope.cdata[type].push({
                eaux_pluviales_origine_rejet: null,
                eaux_pluviales_caracteristiques_effluents: {},
                eaux_pluviales_type_ouvrage: {},
                eaux_pluviales_localisation: '',
                eaux_pluviales_dimensions: '',
                eaux_pluviales_entretien: {},
                eaux_pluviales_avis: {},
                commentaire: '',
              });
              break;
            }
          case 'bilan_conformite': {
              $scope.cdata[type].push({
                conformite_priorite: null,
                conformite_insuffisance: '',
                conformite_preconisations: '',
                conformite_delais: '',
                commentaire: '',
              });
              break;
            }
          case 'tableau_produit': {
              $scope.cdata[type].push({
                reference: null,
                fiche_produit: {},
                toxicite: {},
                securite_transmise: {},
                commentaire: '',
              });
              break;
            }
          case 'dechets_produit': {
              $scope.cdata[type].push({
                quantite_dechet: '',
                origine_dechet: '',
                risque_dechet: null,
                type_dechet: '',
                stockage_dechet: {},
                destination_dechet: {},
                commentaire: '',
              });
              break;
            }
          case'activite_secondaire': {
            $scope.cdata[type].push({
              batiment_activite: '',
              nature_activite: null,
              commentaires: '',
              id_etablissement: '',
            });
            break;
          }
          case 'details_icpe':{
            $scope.cdata[type].push({
              numero_icpe: '',
              intitule_icpe: '',
              seuil_icpe: '',
              regime_icpe: null,
              document_icpe: '',
              commentaires: '',
            });
            break;
          }
        }
      }
    };

    $scope.initTable = function(type) {
      if (!$scope.cdata[type]) {
        $scope.cdata[type] = [];
      }

      if ($scope.cdata[type].length === 0){
        $scope.addLines(1, type);
      }
    };

    $scope.deleteLine = function(index, type) {
      $scope.cdata[type].splice(index, 1);
    };

    $scope.deleteTableParameterLine = function(index, type, lineIndex) {
      if (!isNaN(lineIndex)) {
        $scope.cdata[type][index].parameters.splice(lineIndex, 1);
      }
    };

    [
      'tableau_produit',
      'dechets_produit',
      'tableau_coefficient',
      'tableau_pollution',
      'activite_secondaire',
      'details_icpe',
      'bilan_conformite',
      'points_rejet',
      'eaux_usees',
      'eaux_pluviales',
      'transmission_etablissement',
    ].forEach(function(type) {
      $timeout(()=>{
        $scope.initTable(type);
        }, 0);
    });

    $scope.resetTab = function(type, index) {
      let nomtableau = '';
      switch (type) {
        case 'tableau_produit':
          nomtableau = 'des produits';
          break;
        case 'dechets_produit':
          nomtableau = 'des déchets';
          break;
        case 'points_rejet':
          nomtableau = 'des rejets';
          break;
        case 'eaux_usees':
          nomtableau = 'Eaux usées';
          break;
        case 'eaux_pluviales':
          nomtableau = 'Eaux pluviales';
          break;
        case 'transmission_etablissement':
          nomtableau = 'Transmission vers établissement';
          break;
        case 'conformite':
          nomtableau = 'Bilan conformité';
          break;
        case 'tableaux_parametres_eaux_uses':
          nomtableau = 'Paramétres Analyse Eaux usées';
          break;
        case 'tableaux_parametres_eaux_pluviale':
          nomtableau = 'Paramétres Analyse Eaux pluviales';
          break;
      }
      var ans = confirm(
        'Êtes-vous certain de vouloir réinitialiser le tableau ' +
          nomtableau +
          ' ?'
      );

      if (ans) {
        if (type == 'tableaux_parametres_eaux_uses'
        ||type == 'tableaux_parametres_eaux_pluviale') {
          $scope.cdata[type][index] = {
            point_rejet:'',
            parameters:[],
            eaux_uses_commentaires:''
          };
          $scope.addLines(1, type, index);
        } else {
          $scope.cdata[type] = [];
          $scope.addLines(1, type);
        }
      }
    };

    /**
     * Récupération de la liste des pâys
     */
    $scope.getListePays = function() {
      gaJsUtils.getListePays().then(function(listePays) {
        $scope.listePays = listePays;
      });
    };

    $scope.getListePays();
    /**
     *ajout d'un point de rejet
     */
    $scope.ajoutPointRejet = function(type) {
      if (!$scope.cdata[type]) {
        $scope.cdata[type] = [];
      }
      const index = $scope.cdata[type].length;
      $scope.cdata[type].push( {
          point_rejet:'',
          parameters:[],
          eaux_uses_commentaires:''
        });
      $scope.addLines(1, type, index);
    };
    /**
     *get listofValues From ListeDeroulantes
     */
    $scope.getAliasFromListeDeroulantes = function(attributeName) {
      let attributeTarget = $scope.kis_bac_listes_deroulantes_controles.attributes.filter(
        attribute => attribute.name === attributeName
      );
      let restrictionTarget = attributeTarget.restrictions.filter(
        restriction => restriction.type === 'Domain'
      );
      return restrictionTarget.listofValues;
    };

    /**
     *get Key By Value
     */
    $scope.getKeyByValue = function(object, value) {
      return Object.keys(object).find(key => object[key] === value);
    };
    /**
     *calcule des Dates Fin Validite
     */
    $scope.calculeDateFinValidite = function() {
      if ($scope.cdata.datesDossier.date_signature_arrete) {
        var dateSignature = new Date(
          $scope.cdata.datesDossier.date_signature_arrete
        );
        if ($scope.cdata.datesDossier.duree_arrete) {
          var amountOfYears = $scope.cdata.datesDossier.duree_arrete;
          dateSignature.setFullYear(
            dateSignature.getFullYear() + amountOfYears
          );
          $scope.cdata.datesDossier.date_fin_arrete = dateSignature;
        } else {
          $scope.cdata.datesDossier.date_fin_arrete = null;
        }
      }
    };
    /***********************************************
      get data on existCCIControle
    ************************************************/
    $scope.getCCIControleData = function() {
      let cciControleId;
      if ($scope.currentControles)
        $scope.currentControles.forEach(function(currentControle) {
          if (currentControle.properties.type == 'CCI') {
            cciControleId = currentControle.id;
          }
        });
      if (cciControleId)
        BacAppFactory.getcontroledetail(
          $scope.currentReport.id,
          cciControleId
        ).then(function(res) {
          if (res.data !== '') {
            $scope.cciControleData = res.data;
          }
        });
    };

    $scope.getCCIControleData();
    /*******************************************
      fill Data from CCI controle 
    *******************************************/
    $scope.fillEtablissementDescriptifData = function(type) {
      /**
       * get data existCCIControle
       */
      $scope.getCCIControleData();
      if ($scope.cciControleData) {
        switch (type) {
          case 'tableau_produit':
            $scope.cdata.info_generales.stockage_produits_dangereux =
              $scope.cciControleData.info_generales.stockage_produits_dangereux;
            break;
          case 'dechets_produit':
            $scope.cdata.info_generales.stockage_dechetsdangereux =
              $scope.cciControleData.info_generales.stockage_dechetsdangereux;
            break;
          case 'points_rejet':
            $scope.cdata.info_generales.rejet_nondomestique_specifique =
              $scope.cciControleData.info_generales.rejet_nondomestique_specifique;
            break;
        }
        $scope.cdata[type] = $scope.cciControleData[type];
      }
    };
  };

  AUDCtrl.$inject = [
    '$scope',
    'FeatureTypeFactory',
    'gaJsUtils',
    'BacAppFactory',
    '$timeout'
  ];

  return AUDCtrl;
});
