'use strict';

define(function() {
  /*
   * mailsCtrl
   */
  var mailsCtrl = function(
    $scope,
    BacAppFactory,
    DocumentFactory,
    FeatureTypeFactory,
    ConfigFactory,
    gaDomUtils
  ) {
    $scope.listTemplates = BacAppFactory.appCfg.main.dossierCfg.templates;
    ConfigFactory.checkTemplates($scope.listTemplates).then(function(res) {
      $scope.listTemplates = res.data;
    });
    $scope.dossierFti = angular.copy(
      FeatureTypeFactory.getFeatureByNameAndDatastore(
        BacAppFactory.appCfg.main.datastore,
        'kis_bac_dossier'
      )
    );

    var listeDossiersCfg = BacAppFactory.getListeDossiersCfg($scope.dossierFti);

    $scope.dossierAttributes = listeDossiersCfg['attributes'];
    $scope.renduTitleColonneDossier =
      listeDossiersCfg['renduTitleColonneDossier'];
    $scope.renduColonnesEtatDossier =
      listeDossiersCfg['renduColonnesEtatDossier'];
    $scope.filterRender = listeDossiersCfg['filterRender'];

    // getReports
    $scope.getReports = function(p) {
      return BacAppFactory.getdossiers(
        'tous',
        p.filter,
        p.crs,
        p.page,
        p.count,
        p.liaisonFilter,
        p.case_sensitive,
        p.sort,
        ''
      );
    };

    $scope.checkboxSelected = {};
    $scope.selected = { dossiers: [] };
    $scope.searchText = {};

    $scope.restrictFtids = [$scope.dossierFti.uid];

    $scope.dossierAttributes = [];
    $scope.dossierFti.attributes.forEach(function(att) {
      if (
        ~[
          'ref_dossier',
          'date_creation',
          'prochain_controle',
          'date_prochain_controle',
        ].indexOf(att.name)
      ) {
        $scope.dossierAttributes.push(att);
      }
    });

    /**
     * Return whether zip can be generated and downloaded
     * @returns {boolean}
     */
    $scope.canGenerate = function() {
      if (!$scope.selected.dossiers.length) return false;
      if (!Object.keys($scope.checkboxSelected).length) return false;

      for (var i in $scope.checkboxSelected) {
        if (!$scope.checkboxSelected[i]) return false;
      }

      return true;
    };

    /**
     * download zip
     */
    $scope.getDocumentsZip = function() {
      var list_dossier_ids = [],
        name_list = [];

      for (var i in $scope.selected.dossiers) {
        list_dossier_ids.push($scope.selected.dossiers[i].id);
      }
      for (var i in $scope.checkboxSelected) {
        if ($scope.checkboxSelected[i]) name_list.push(i);
      }

      gaDomUtils.showGlobalLoader();
      BacAppFactory.getZipDocumentsTypes(
        list_dossier_ids,
        name_list.join(',')
      ).then(
        function(res) {
          console.log(res.data);
          window.open(
            '/services/' +
              res.data.portalid +
              '/documents/downloaddocx?' +
              '&name=' +
              res.data.name
          );
          gaDomUtils.hideGlobalLoader();
        },
        function() {
          gaDomUtils.hideGlobalLoader();
        }
      );
    };

    // used to render column values (see renderValue function)
    var contoleCfg = BacAppFactory.appCfg.main.controleCfg;
    var remplaceNomControle = function(controle) {
      var value = controle;
      contoleCfg.forEach(function(item) {
        if (controle == item.type) {
          value = item.label;
        }
      });
      return value;
    };

    $scope.renduColonnesEtatDossier = {
      prochain_controle: remplaceNomControle,
      type_dernier_controle: remplaceNomControle,
    };

    /** advancedFilters **/
    $scope.showAdvanced = false;
    $scope.toggleAdvancedFilters = function() {
      $scope.showAdvanced = !$scope.showAdvanced;
      $scope.advancedFiltersResult = { res: {} };
    };
    $scope.filterfti = {};
    $scope.advancedFiltersResult = { res: {} };
    $scope.$watch(
      'advancedFiltersResult',
      function(af) {
        console.log(af);
        console.log(af.res);

        if (!$scope.filterfti.data) return;
        if ($scope.filterfti.data.name != 'kis_anc_dossier') {
          require('toastr').error('Veuillez sélectionner des dossiers ANC');
          return;
        }

        var finalWhere = '';

        if (af.res.totalFeatures == 0) {
          finalWhere = '1=0';
        }
        if (af.res.totalFeatures > 0) {
          var filteredReportsIds = af.res.features.map(function(f) {
            return f.properties.ref_dossier;
          });

          finalWhere =
            "ref_dossier IN ('" + filteredReportsIds.join("','") + "')";
        }
        $scope.listeDossiersWhere = finalWhere;
      },
      1
    );
  };

  mailsCtrl.$inject = [
    '$scope',
    'BacAppFactory',
    'DocumentFactory',
    'FeatureTypeFactory',
    'ConfigFactory',
    'gaDomUtils',
  ];
  return mailsCtrl;
});
