<!--suppress JSAnnotator -->
<template>
  <div class="page" data-name="report-show-driver-behaviour">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left"></div>
        <div class="title">{{PageTitle}}</div>
        <div class="right">
          <a href="#" class="link popup-close" data-popup=".popup-fullscreen-report">
            <i class="f7-icons">close</i>
          </a>
        </div>
      </div>
    </div>
    <div class="page-content bg-color-lightgray ">
      <div class="display-flex justify-content-space-between">
        <div class="block">
          <p class="text-color-black">
            <i class="f7-icons icon-calendar text-color-gray vertical-middle margin-right"></i>
            <span class="text-color-gray">{{ @global.LANGUAGE.COM_MSG97 }}:</span>
            {{AdditionalReportInfo.TimePeriodText}}
          </p>
        </div>
      </div>

      <div class="row no-gap">
        <div class="col-100 tablet-25  ">
          <div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
            <div class="card-header bg-color-darkgray text-color-white">
              {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG23}}
            </div>
            <div class="card-content">
              <div id="chart-GHarshBracking"></div>
            </div>
          </div>
        </div>
        <div class="col-100 tablet-25  ">
          <div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
            <div class="card-header bg-color-darkgray text-color-white">
              {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG27}}
            </div>
            <div class="card-content">
              <div id="chart-GHarshAcceleration"></div>
            </div>
          </div>
        </div>
        <div class="col-100 tablet-25  ">
          <div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
            <div class="card-header bg-color-darkgray text-color-white">
              {{@global.LANGUAGE.REPORT_PANEL_MSG199}}
            </div>
            <div class="card-content">
              <div id="chart-GExcesiveIdling"></div>
            </div>
          </div>
        </div>
        <div class="col-100 tablet-25  ">
          <div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
            <div class="card-header bg-color-darkgray text-color-white">
              {{@global.LANGUAGE.REPORT_PANEL_MSG200}}
            </div>
            <div class="card-content">
              <div id="chart-GSpeeding"></div>
            </div>
          </div>
        </div>
      </div>

      <table id="table-report" class="mdl-data-table " style="width:100%">
        <thead>
        <tr>
       <!--   -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG37}} </th> <!-- Asset Name  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG38}} </th> <!-- IMEI  -->
          <th class="no-export"> {{@global.LANGUAGE.REPORT_PANEL_MSG202}} </th> <!-- Driver Rating  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG101}} </th> <!-- Duration  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG122}} </th> <!-- Mileage  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG107}} </th> <!-- Fuel  -->
          <th> {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG23}} </th> <!-- Harsh Bracking  -->
          <th> {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG27}} </th> <!-- Harsh Accelerate  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG199}} </th> <!-- Excessive Idling  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG200}} </th> <!-- Speeding  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG201}} </th> <!-- Points(of 100)  -->


        </tr>
        </thead>
        <tbody>

        {{#ReportData}}
          <tr data-item-index="{{@index}}" >
            <td><i class="f7-icons icon-name text-color-gray vertical-middle margin-right"></i> {{Name}}</td>
            <td>{{IMEI}}</td>
            <td>{{Stars.template}}</td>
            <td>{{DurationFormatted}}</td>
            <td>{{#if Mileage}}{{MileageFormatted}}{{else}}{{@global.LANGUAGE.COM_MSG103}}{{/if}}</td>
            <td>{{#if FuelUsed}}{{FuelUsedFormatted}} ({{@global.LANGUAGE.COM_MSG80}}){{else}}{{@global.LANGUAGE.COM_MSG103}}{{/if}}</td>
            <td class="text-align-center">{{HarshBracking}}</td>
            <td class="text-align-center">{{HarshAcceleration}}</td>
            <td class="text-align-center">{{ExcessiveIdling}}</td>
            <td class="text-align-center">{{Speeding}}</td>
            <td class="text-align-center bold {{Stars.color}}">{{PointsFormatted}}</td>

          </tr>
        {{/ReportData}}

        </tbody>
      </table>
    </div>
  </div>

</template>

<script>
  // script must return component object
  return {
    data: function () {
      var self = this;

      var ret = {};

      var type = self.$route.query.type;
      var splitBy = self.$route.query.splitby;
      //console.log(self);
      //console.log(type);
      var pageTitle = Protocol.Helper.getReportTypeName(type);

      var reportData = self.$app.methods.getFromStorage('reportData');

      if (type && reportData && reportData.length) {
        for (let i = reportData.length - 1; i >= 0; i--) {
          if (reportData[i].Duration) {
            reportData[i].DurationFormatted = TimeSpan(parseFloat(reportData[i].Duration) * 60000 * 60).format("^hh:mm:ss");
          }
          if (reportData[i].Mileage) {
            reportData[i].MileageFormatted = Protocol.Helper.getMileageValue(POSINFOASSETLIST[reportData[i].IMEI].Unit, reportData[i].Mileage) + '&nbsp;' + Protocol.Helper.getMileageUnit(POSINFOASSETLIST[reportData[i].IMEI].Unit) // parseFloat(reportData[i].Mileage).toFixed(2);
          }
          if (reportData[i].FuelUsed) {
            reportData[i].FuelUsedFormatted = parseFloat(reportData[i].FuelUsed).toFixed(2);
          }

          reportData[i].PointsFormatted = parseFloat(reportData[i].Points).toFixed(1);

          reportData[i].Stars = self.$app.methods.getStars(reportData[i].Points)
        }
      }
      console.log(reportData);
      if (!pageTitle) {
        pageTitle = LANGUAGE.REPORT_PANEL_MSG35;
      }

      ret = {
        Type: type,
        TypeDealer: self.$app.data.CustomerType === 2 || self.$app.data.CustomerType === 6,
        DataTable: false,
        PageTitle: pageTitle,
        ReportData: reportData,
        AdditionalReportInfo: {
          From: self.$route.query.from,
          To: self.$route.query.to,
          TimePeriodText: moment(self.$route.query.from, window.COM_TIMEFORMAT).add(self.$app.data.UTCOFFSET,'minutes').format('MMMM DD YYYY, HH:mm') + ' - ' + moment(self.$route.query.to, window.COM_TIMEFORMAT).add(self.$app.data.UTCOFFSET,'minutes').format('MMMM DD YYYY, HH:mm'),
        },

        ChartsArr: [],

      };

      return ret;
    },
    methods: {

      buildGraphics: function(graphicSlist = []){
        var self = this;

        if (graphicSlist.length) {
          for (var i = graphicSlist.length - 1; i >= 0; i--) {

            self.ChartsArr.push( c3.generate({
              bindto: graphicSlist[i].bindto,
              color: {
                pattern: self.$app.data.ChartCustomization.colors
              },
              data: {
                columns: graphicSlist[i].columns,
                type : 'bar',
                labels: true
              },
              bar: {
                width: {
                  ratio: 1 // this makes bar width 50% of length between ticks
                },
                space: 0.25
              },
              axis: {
                x: {
                  show: false,
                  type: 'category',
                  categories: [graphicSlist[i].name],
                },
                y: { show: false }
              },
              legend: {
                show: false
              }
            }) );
          }
        }
      },
      getDTExportColumnsIndx: function(table){
        let allColumns = table.find('thead th');
        let indexes = [];
        for (var i = 0 ; i < allColumns.length; i++) {
          if (!$$(allColumns[i]).hasClass('no-export')) {
            indexes.push(i);
          }
        }
        return indexes;
      },
    },

    on: {
      pageInit: function (e, page) {
        var self = this;
        if (self.Type) {
          var columnDefs = [
            //{ targets: [ 0 ], orderable: false,  }
          ];
          var order = [[0, 'asc']]; //order by timestamp

          let dtExportColumnIndxs = self.getDTExportColumnsIndx(page.$el.find('table'));
          DATATABLEReport = $('#table-report').DataTable({
            columnDefs: columnDefs,
            order: order,
            dom: '<"mdl-grid"<"mdl-cell mdl-cell--12-col margin-top-0 margin-bottom-0"B>><"mdl-grid"<"mdl-cell mdl-cell--6-col"l><"mdl-cell mdl-cell--6-col"f>><"mdl-grid dt-table"<"mdl-cell mdl-cell--12-col"rt>><"mdl-grid"<"mdl-cell mdl-cell--4-col"i><"mdl-cell mdl-cell--8-col"p>>',
            buttons: {
              dom: {
                container: {
                  className: 'datatable-additional-buttons '
                }
              },
              buttons: [
                {
                  extend: 'excelHtml5',
                  text: '<i class="f7-icons icon-export-excel vertical-middle margin-right"></i>Excel',
                  className: 'mdl-button mdl-button--raised bg-color-1 text-color-white',
                  title: self.PageTitle + ' ' + self.AdditionalReportInfo.TimePeriodText,
                  exportOptions: {
                    columns: dtExportColumnIndxs
                  }
                },
                {
                  extend: 'pdfHtml5',
                  text: '<i class="f7-icons icon-export-pdf vertical-middle margin-right"></i>PDF',
                  className: 'mdl-button mdl-button--raised bg-color-2 text-color-white',
                  title: self.PageTitle + ' ' + self.AdditionalReportInfo.TimePeriodText,
                  exportOptions: {
                    columns: dtExportColumnIndxs
                  },
                  //orientation: 'landscape',
                  customize: function (doc) {
                    var now = new Date();
                    //var jsDate = now.getDate()+'/'+(now.getMonth()+1)+'/'+now.getFullYear();
                    var jsDate = ('0' + now.getDate()).slice(-2) + '/' + ('0' + (now.getMonth()+1)).slice(-2) + '/' + now.getFullYear();

                    doc.pageMargins = [20,60,20,30];
                    // Set the font size fot the entire document
                    doc.defaultStyle.fontSize = 7;
                    // Set the fontsize for the table header
                    doc.styles.tableHeader.fontSize = 7;
                    // Create a header object with 3 columns
                    // Left side: Logo
                    // Middle: brandname
                    // Right side: A document title

                    doc['header']=(function() {
                      return {
                        columns: [

                          /*{
                            alignment: 'left',
                            italics: true,
                            text: messageTopLeft,
                            fontSize: 9,
                            margin: [10,0]
                          },*/
                          // {
                          //   image: self.$app.data.AppDetails.logoBase64,
                          //   alignment: 'center',
                          //   width: 120
                          // },
                          /*{
                            alignment: 'right',
                            fontSize: 9,
                            text: messageTopRight
                          }*/
                        ],
                        margin: 20
                      }
                    });
                    // Create a footer object with 2 columns
                    // Left side: report creation date
                    // Right side: current page and total pages
                    doc['footer']=(function(page, pages) {
                      return {
                        columns: [
                          {
                            alignment: 'left',
                            text: [LANGUAGE.COM_MSG106+': ', { text: jsDate.toString() }]
                          },
                          {
                            alignment: 'right',
                            text: [LANGUAGE.COM_MSG107+' ', { text: page.toString() },  ' '+LANGUAGE.COM_MSG108+' ', { text: pages.toString() }]
                          }
                        ],
                        margin: 20
                      }
                    });
                  }
                },
                {
                  extend: 'csvHtml5',
                  text: '<i class="f7-icons icon-export-csv vertical-middle margin-right"></i>CSV',
                  className: 'mdl-button mdl-button--raised bg-color-4 text-color-white',
                  title: self.PageTitle + ' ' + self.AdditionalReportInfo.TimePeriodText,
                  exportOptions: {
                    columns: dtExportColumnIndxs
                  }
                },
                /*{
                  extend: 'print',
                  text: '<i class="f7-icons icon-export-print vertical-middle margin-right"></i>Print',
                  className: 'mdl-button mdl-button--raised bg-color-3 text-color-white',
                  title: self.PageTitle,
                  orientation: 'landscape',
                  exportOptions: {
                    columns: dtExportColumnIndxs
                  }
                }*/
              ]
            },
          });

          let graphicsColumns = {
            HarshBracking: [],
            HarshAcceleration: [],
            ExcesiveIdling: [],
            Speeding: [],
          };
          for (var i = self.ReportData.length - 1; i >= 0; i--) {
            graphicsColumns.HarshBracking.push( [ self.ReportData[i].Name, self.ReportData[i].HarshBracking ] );
            graphicsColumns.HarshAcceleration.push( [ self.ReportData[i].Name, self.ReportData[i].HarshAcceleration ] );
            graphicsColumns.ExcesiveIdling.push( [ self.ReportData[i].Name, self.ReportData[i].ExcessiveIdling ] );
            graphicsColumns.Speeding.push( [ self.ReportData[i].Name, self.ReportData[i].Speeding ] );
          }

          self.buildGraphics([
            {
              name: LANGUAGE.REPORT_ALERT_LIST_MSG23,
              bindto: '#chart-GHarshBracking',
              columns: graphicsColumns.HarshBracking
            },
            {
              name: LANGUAGE.REPORT_ALERT_LIST_MSG27,
              bindto: '#chart-GHarshAcceleration',
              columns: graphicsColumns.HarshAcceleration
            },
            {
              name: LANGUAGE.REPORT_PANEL_MSG199,
              bindto: '#chart-GExcesiveIdling',
              columns: graphicsColumns.ExcesiveIdling
            },
            {
              name: LANGUAGE.REPORT_PANEL_MSG200,
              bindto: '#chart-GSpeeding',
              columns: graphicsColumns.Speeding
            }
          ]);
        }



      },
      pageAfterIn:function(){
        //var self = this;
        //console.log('page in');


      },
      pageAfterOut: function () {
        // page has left the view
        console.log('here');
      },
      pageBeforeRemove: function(e, page){
        let self = this;
        if (self.ChartsArr && self.ChartsArr.length) {
          for (var i = self.ChartsArr.length - 1; i >= 0; i--) {
            self.ChartsArr[i].destroy();
          }
        }
        //console.log('removed');
      },
    }
  };
</script>