{% extends "balafon/bs_base.html" %}
{% load i18n balafon_utils %}

{% block extra_head %}
{{block.super}}
<style>
  table.table td, table.table th{
    font-size: 0.7em;
  }
  .title h2 {
    margin: 0;
    font-size: 1.5em;
  }
  th {
    text-align: center;
  }
</style>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/angular/angular.js"></script>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/moment/moment.js"></script>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/angular-messages/angular-messages.js"></script>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/angular-i18n/angular-locale_{{ LANGUAGE_CODE }}-{{ LANGUAGE_CODE }}.js"></script>
<script src="{{ DOMAIN }}{{ STATIC_URL }}modules/angular-translate/angular-translate.js"></script>
<script>
  var app = angular.module('storeStatsApp', ['ui.bootstrap', 'pascalprecht.translate']);
  var from_year = {{ from_year }};

  app.config(['$httpProvider', '$translateProvider', function($httpProvider, $translateProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

    $translateProvider.translations('en', {
      BY_CATEGORY: 'By Category',
      BY_FAMILY: 'By Family',
      BY_TAG: 'By Tag',
      CATEGORY: 'Category',
      LOADING: 'loading',
      NO_ITEMS: 'No items',
      STATS_BY_CATEGORY: 'Monthly sales (No VAT) by category',
      STATS_BY_FAMILY: 'Monthly sales (No VAT) by family',
      STATS_BY_TAG: 'Monthly sales (No VAT) by tag',
      STATS_TOTAL:  'Total monthly sales (No VAT)',
      TOTAL: 'Total',
      '': ''
    });

    $translateProvider.translations('fr', {
      BY_CATEGORY: 'Par Catégorie',
      BY_FAMILY: 'Par Famille',
      BY_TAG: 'Par Tag',
      CATEGORY: 'Catégorie',
      LOADING: 'Chargement en cours',
      NO_ITEMS: 'Aucun élément',
      STATS_BY_CATEGORY: 'Chiffre d\'affaires mensuel (HT) par catégorie',
      STATS_BY_FAMILY: 'Chiffre d\'affaires mensuel (HT) par famille',
      STATS_BY_TAG: 'Chiffre d\'affaires mensuel (HT) par tag',
      STATS_TOTAL: 'Chiffre d\'affaires mensuel (HT) total',
      TOTAL: 'Total',
      '': ''
    });
    $translateProvider.preferredLanguage('{{ LANGUAGE_CODE }}');
    $translateProvider.useSanitizeValueStrategy('escape');
  }]);

  app.controller('storeStatsCtrl',
    ['$scope', '$modal', '$http', '$translate', '$filter', '$log',
    function ($scope, $modal, $http, $translate, $filter, $log) {
      $scope.loading = false;
      $scope.statistics = [];
      $scope.mode = '';
      $scope.months = [];
      $scope.years = [];

      $scope.toDate = new Date();
      for (var i=from_year; i<=$scope.toDate.getFullYear(); i++){
        $scope.years.push(i);
      }

      $scope.fromDate = new Date($scope.toDate.getFullYear(), 0, 1);
      $scope.toDate = new Date($scope.toDate.getFullYear(), 11, 31);
      $scope.selectedYear = $scope.toDate.getFullYear();

      var sumArray = function(array) {
        var total = 0;
        for (var i=0, l=array.length; i<l; i++){
          total += parseFloat(array[i].value);
        }
        return total;
      };

      var copyData = function(respData) {
        $scope.months = respData.months;
        $scope.statistics = respData.data;
        for (var i=0, l=respData.data.length; i<l; i++){
          $scope.statistics[i].total_amount = sumArray(respData.data[i].values)
        }
      };

      var buildUrl = function(prefix) {
        var url = prefix + $scope.fromDate.getFullYear() + '-' + ($scope.fromDate.getMonth() + 1);
        url += '/' + $scope.toDate.getFullYear() + '-' + ($scope.toDate.getMonth() + 1) + '/';
        return url;
      };

      $scope.loadCategoriesStatistics = function () {
        $scope.loading = true;
        $scope.currentItem = null;
        $scope.mode = 'categories';

        var url = buildUrl('/store/api/stats/sales-by-category/');

        $http.get(url).success(function(respData) {
          copyData(respData);
          $scope.loading = false;
        });
      };

      $scope.loadFamiliesStatistics = function () {
        $scope.loading = true;
        $scope.currentItem = null;
        $scope.mode = 'families';

        var url = buildUrl('/store/api/stats/sales-by-family/');

        $http.get(url).success(function(respData) {
          copyData(respData);
          $scope.loading = false;
        });
      };

      $scope.loadTagsStatistics = function () {
        $scope.loading = true;
        $scope.currentItem = null;
        $scope.mode = 'tags';
        var url = buildUrl('/store/api/stats/sales-by-tag/');
        $http.get(url).success(function(respData) {
          copyData(respData);
          $scope.loading = false;
        });
      };

      $scope.loadTotalSalesStatistics = function () {
        $scope.loading = true;
        $scope.currentItem = null;
        $scope.mode = 'total';
        var url = buildUrl('/store/api/stats/total-sales/');
        $http.get(url).success(function(respData) {
          copyData(respData);
          $scope.loading = false;
        });
      };

      $scope.loadItemStatistics = function(item) {
        $scope.loading = true;
        $scope.currentItem = item;

        var url = '';
        if ($scope.mode === 'categories') {
          url = '/store/api/stats/sales-by-item-cat/' + item.id + '/';
        } else if ($scope.mode === 'tags') {
          url = '/store/api/stats/sales-by-item-tag/' + item.id + '/';
        } else if ($scope.mode === 'families') {
          url = '/store/api/stats/sales-by-item-family/' + item.id + '/';
        }

        if (url) {
          url = buildUrl(url);
          $scope.mode = '';
          $http.get(url).success(function (respData) {
            copyData(respData);
            $scope.loading = false;
          });
        }
      };

      $scope.isCategories = function () {
        return $scope.mode === 'categories';
      };

      $scope.isFamilies = function () {
        return $scope.mode === 'families';
      };

      $scope.isTags = function () {
        return $scope.mode === 'tags';
      };

      $scope.isTotal = function () {
        return $scope.mode === 'total';
      };

      $scope.yearChanged = function() {
        //January the 1st
        $scope.fromDate = new Date($scope.selectedYear, 0, 1);
        //December 31st
        $scope.toDate = new Date($scope.selectedYear, 11, 31);

        //refresh
        if ($scope.isCategories()) {
          $scope.loadCategoriesStatistics();
        }
        else if ($scope.isTags()) {
          $scope.loadTagsStatistics();
        } else if ($scope.isFamilies()) {
          $scope.loadFamiliesStatistics();
        } else if ($scope.isTotal()) {
          $scope.loadTotalSalesStatistics();
        } else {
          $scope.loadItemStatistics($scope.currentItem());
        }
      };

      $scope.loadTotalSalesStatistics();

    }]
  );
</script>


{% endblock %}

{% block document_content %}
{% verbatim %}
  <div ng-app="storeStatsApp">
    <div ng-controller="storeStatsCtrl" class="container-fluid">

      <div class="row" style="margin-bottom: 10px;">
        <div class="col-md-5">
          <div class="title">
            <h2 ng-show="mode==='total'"> {{ 'STATS_TOTAL' | translate }} </h2>
            <h2 ng-show="mode==='categories'"> {{ 'STATS_BY_CATEGORY' | translate }} </h2>
            <h2 ng-show="mode==='families'"> {{ 'STATS_BY_FAMILY' | translate }} </h2>
            <h2 ng-show="mode==='tags'"> {{ 'STATS_BY_TAG' | translate }} </h2>
            <h2 ng-show="mode===''">
              <span ng-show="currentItem.icon" class="glyphicon glyphicon-{{ currentItem.icon }}"></span>
              <span ng-hide="currentItem.icon" class="glyphicon glyphicon-tag"></span>
              {{ currentItem.name }}
            </h2>
          </div>
        </div>
        <div class="col-md-2">
        <select ng-disabled="loading" class="form-control" ng-model="selectedYear" ng-options="year for year in years" ng-change="yearChanged()">
        </select>
        </div>
        <div class="col-md-5">
          <div class="btn-group pull-right" role="group" aria-label="...">
            <button ng-disabled="loading" type="button" class="btn" ng-class="{'btn-primary': isTotal(), 'btn-default': !isTotal()}"
              ng-click="loadTotalSalesStatistics()"
            >
              {{ 'TOTAL' | translate }}
            </button>
            <button ng-disabled="loading" type="button" class="btn" ng-class="{'btn-primary': isFamilies(), 'btn-default': !isFamilies()}"
              ng-click="loadFamiliesStatistics()"
            >
              {{ 'BY_FAMILY' | translate }}
            </button>
            <button ng-disabled="loading" type="button" class="btn" ng-class="{'btn-primary': isCategories(), 'btn-default': !isCategories()}"
              ng-click="loadCategoriesStatistics()"
            >
              {{ 'BY_CATEGORY' | translate }}
            </button>
            <button ng-disabled="loading" type="button" class="btn" ng-class="{'btn-primary': isTags(), 'btn-default': !isTags()}"
              ng-click="loadTagsStatistics()"
            >
              {{ 'BY_TAG' | translate }}
            </button>
          </div>
        </div>
      </div>

      <div class="alert alert-info" ng-show="loading">
        {{ 'LOADING' | translate }}
      </div>
      <table class="table table-striped table-bordered" ng-show="statistics.length && !loading">
        <tr>
          <th>&nbsp;</th>
          <th ng-repeat="month_date in months">{{ month_date.date | date : 'MMM' }}</th>
          <th>{{ 'TOTAL' | translate }}</th>
        </tr>
        <tr ng-repeat="statistic in statistics | orderBy:'-total_amount' ">
          <td>
            <span ng-show="statistic.icon" class="glyphicon glyphicon-{{ statistic.icon }}"></span>
            <span ng-hide="statistic.icon" class="glyphicon glyphicon-tag"></span>
            <a href ng-show="mode && mode!=='total'" ng-click="loadItemStatistics(statistic)">{{ statistic.name }}</a>
            <span ng-show="!mode || mode==='total'">{{ statistic.name }}</span>
          </td>
          <td style="text-align: right" ng-repeat="item in statistic.values">
            <span ng-show="item.value > 0">{{item.value}}</span>
          </td>
          <th style="text-align: right" ><span ng-hide="loading">{{ statistic.total_amount | number:2 }}</span></th>
        </tr>
      </table>

      <div class="alert alert-warning" ng-show="statistics.length === 0 && !loading">
        {{ 'NO_ITEMS' | translate }}
      </div>

    </div>
  </div>
{% endverbatim %}
{% endblock %}
