<template>
  <div class="page" data-name="report-show-driver-ids">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left"></div>
        <div class="title">{{PageTitle}} - {{AdditionalReportInfo.TimePeriodText}}</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="row no-gap overflow-hidden">
        <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-GHarshAcc"></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.ASSET_RATING_MSG04}}
            </div>
            <div class="card-content">
              <div id="chart-GExcesiveIDLE"></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.ASSET_RATING_MSG05}}
            </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.HOME_MSG001}} </th> <!-- Asset Name  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG212}} </th> <!-- Driver Tag Number  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG181}} </th> <!-- Driver Name  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG162}} </th> <!-- Total Mileage  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG161}} </th> <!-- Total Duration  -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG165}} </th> <!-- Total Fuel  -->

          {{#if AdditionalReportInfo.Options.MaxSpeed}}
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG160}} </th> <!-- Max Speed -->
          {{/if}}
          {{#if AdditionalReportInfo.Options.AvgSpeed}}
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG159}} </th> <!-- Average Speed -->
          {{/if}}

          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG213}} </th> <!-- Number of Trips  -->
          <th> {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG23}} </th> <!-- Harsh Bracking -->
          <th> {{@global.LANGUAGE.REPORT_ALERT_LIST_MSG27}} </th> <!-- Harsh Acc -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG199}} </th> <!-- Excessive Idling -->
          <th> {{@global.LANGUAGE.REPORT_PANEL_MSG200}} </th> <!-- Speeding -->
          <th class="no-export"> {{@global.LANGUAGE.REPORT_PANEL_MSG76}} </th> <!-- Details  -->


        </tr>
        </thead>
        <tbody>
        {{#ReportData}}
        <tr data-item-index="{{@index}}" >
          <td><i class="f7-icons icon-name text-color-gray vertical-middle margin-right"></i> {{AssetName}}</td>
          <td>{{DriverID}}</td>
          <td>{{Driver}}</td>
          <td data-order="{{TotalMileage}}">{{TotalMileage}} {{@global.LANGUAGE.COM_MSG79}}</td>
          <td>{{TotalDuration}}</td>
          <td data-order="{{TotalFuel}}">{{TotalFuel}} {{@global.LANGUAGE.COM_MSG80}}</td>
          {{#if ../AdditionalReportInfo.Options.MaxSpeed}}
          <td>{{MaxSpeed}} {{ @global.LANGUAGE.COM_MSG81 }}</td>
          {{/if}}
          {{#if ../AdditionalReportInfo.Options.AvgSpeed}}
          <td>{{AverageSpeed}} {{ @global.LANGUAGE.COM_MSG81 }}</td>
          {{/if}}
          <td class="text-align-center">{{TripsCount}}</td>
          <td class="text-align-center">{{HarshBracking}}</td>
          <td class="text-align-center">{{HarshAccelerate}}</td>
          <td class="text-align-center">{{ExcessiveIdling}}</td>
          <td class="text-align-center" >{{Speeding}}</td>
          <td>
            <a @click="getModalWithTripDetails" href="#" class='button button-fill button-small elevation-2 button-table color-red'>
              <i class="f7-icons icon-show-assets vertical-middle margin-right"></i>{{@global.LANGUAGE.REPORT_PANEL_MSG64}}
            </a>
          </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 userInfo = self.$app.methods.getFromStorage('userInfo');

      //console.log(self);
      var pageTitle = Protocol.Helper.getReportTypeName(type);

      var rawData = self.$app.methods.getFromStorage('reportData');
      const map1 = new Map();

      //console.log(rawData);

      for (var i = rawData.length - 1; i >= 0; i--) {
        //converting time into local UTC
        if (rawData[i].BeginTime) {
          rawData[i].BeginTimeLocal = moment(rawData[i].BeginTime, 'YYYY/MM/DDTHH:mm:ss').add(userInfo.UserInfo.TimeZone, 'hours').add(self.$app.data.UTCOFFSET,'minutes').format('YYYY-MM-DD HH:mm:ss');
          rawData[i].BeginTimeUnix =  moment(rawData[i].BeginTime, 'YYYY/MM/DDTHH:mm:ss').unix();

        }
        if (rawData[i].EndTime) {
          rawData[i].EndTimeLocal = moment(rawData[i].EndTime, 'YYYY/MM/DDTHH:mm:ss').add(userInfo.UserInfo.TimeZone, 'hours').add(self.$app.data.UTCOFFSET,'minutes').format('YYYY-MM-DD HH:mm:ss');
          rawData[i].EndTimeUnix =  moment(rawData[i].EndTime, 'YYYY/MM/DDTHH:mm:ss').unix();
        }
        let durationsInHours = moment.duration(rawData[i].TimeSpan).asHours()
        let mileage = parseFloat(rawData[i].Mileage)
        rawData[i].AverageSpeed = mileage > 0 && durationsInHours > 0 ? (mileage / durationsInHours).toFixed(1) : 0

        if(!map1.has(rawData[i].IMEI)){
          map1.set(rawData[i].IMEI, {
            AssetID: rawData[i].AssetID,
            AssetName: rawData[i].AssetName,
            IMEI: rawData[i].IMEI,
            DriverID: rawData[i].DriverID,
            Driver: rawData[i].Driver,
            TotalMileage: mileage,
            TotalDurationInHours: durationsInHours,
            TotalFuel: 0,
            TripsCount: 1,
            MaxSpeed: +rawData[i].MaxSpeed,
            Speeding: parseInt(rawData[i].SpeedingEvents),
            HarshBracking: parseInt(rawData[i].HarshBracking),
            HarshAccelerate: parseInt(rawData[i].HarshAccelerate),
            ExcessiveIdling: parseInt(rawData[i].ExcessiveIdling),

            //Get asset details
            Registration: POSINFOASSETLIST[rawData[i].IMEI]?.Registration ? POSINFOASSETLIST[rawData[i].IMEI].Registration : LANGUAGE.COM_MSG103,
            Make: POSINFOASSETLIST[rawData[i].IMEI]?.Describe1 ? POSINFOASSETLIST[rawData[i].IMEI].Describe1 : LANGUAGE.COM_MSG103,
            Model: POSINFOASSETLIST[rawData[i].IMEI]?.Describe2 ? POSINFOASSETLIST[rawData[i].IMEI].Describe2 : LANGUAGE.COM_MSG103,
            Color: POSINFOASSETLIST[rawData[i].IMEI]?.Describe3 ? POSINFOASSETLIST[rawData[i].IMEI].Describe3 : LANGUAGE.COM_MSG103,
            Year: POSINFOASSETLIST[rawData[i].IMEI]?.Describe4 ? POSINFOASSETLIST[rawData[i].IMEI].Describe4 : LANGUAGE.COM_MSG103,

            Trips: [
              rawData[i]
            ]
          })
        }else{
          let record = map1.get(rawData[i].IMEI)
          record.Trips.push(rawData[i])
          record.TotalMileage += mileage
          record.TotalDurationInHours += durationsInHours
          record.MaxSpeed = +rawData[i].MaxSpeed > record.MaxSpeed ? +rawData[i].MaxSpeed : record.MaxSpeed
          record.Speeding += parseInt(rawData[i].SpeedingEvents)
          record.HarshBracking += parseInt(rawData[i].HarshBracking)
          record.HarshAccelerate += parseInt(rawData[i].HarshAccelerate)
          record.ExcessiveIdling += parseInt(rawData[i].ExcessiveIdling)
          record.TripsCount++
        }
      }

      let reportData = []
      for (const driverStat of map1.values()) {
        driverStat.TotalDuration = moment.duration(driverStat.TotalDurationInHours, "hours").format("HH:mm:ss");
        driverStat.AverageSpeed = driverStat.TotalMileage > 0 && driverStat.TotalDurationInHours > 0 ? (driverStat.TotalMileage / driverStat.TotalDurationInHours).toFixed() : 0
        reportData.push(driverStat)
      }

      console.log(reportData)

      if (!pageTitle) {
        pageTitle = LANGUAGE.REPORT_PANEL_MSG35;
      }

      ret = {
        Type: type,
        //DataTable: false,
        PageTitle: pageTitle,
        ReportData: reportData,
        UserInfo: userInfo,

        AdditionalReportInfo: {
          TimePeriodText: self.$route.query.timePeriodText,
          Options: Protocol.Helper.getDriverIdOptionsSelected(self.$route.query.reportOptionsEnum),
        },

        DynamicTripDetailsPopup: false,
        DynamicMapPopup: false,
        DATATABLEReportTripDetails: false,

        ChartsArr: [],

        HistoryArray: [],
        EventsArray: [],
        PlaybackData: {},
        MapTrackReport: false,
        ReportMarker: false,

        OptimizedRouteState: true,
        CantBeOptimised: false,
        RangeSliderPlayback: false,
        SmartSelectPlaybackSpeed: false,
        PlaybackTimer: false,
        PlaybackRouteLayerGroup: false,
        PlaybackRouteLayerGroupOptimized: false,
        PlaybackMarkerGroup: false,
        PlaybackMarker: false,
        PlaybackEventsLayerGroup: false,
        PointsCount: 0,

      };

      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
              }
            }) );
          }
        }

      },
      getModalWithTripDetails: function(e){
        var self = this;
        var wrapper = $$(e.target).closest('[role="row"]');

        var index = wrapper.data('item-index');
        var positionData = self.ReportData[index];

        var tableTripDetailsArray = positionData.Trips;
        var modalTitle = positionData.Driver;

        if (self.DynamicTripDetailsPopup && !self.DynamicTripDetailsPopup.destroyed) {
          self.DynamicTripDetailsPopup.close();
        }

        var tableRows = '';

        if (tableTripDetailsArray.length > 0) {
          //for (var i = tableTripDetailsArray.length - 1; i >= 0; i--) {
          for (var i = 0; i < tableTripDetailsArray.length; i++) {
            tableRows +=    `<tr data-item-index="${ i }" >
                                   <td data-order="${ tableTripDetailsArray[i].BeginTimeUnix }">${ tableTripDetailsArray[i].BeginTimeLocal }</td>`
            if (tableTripDetailsArray[i].StartCustomAddress) {
              tableRows +=        `<td class="white-space-normall min-width-300 max-width-400">${ tableTripDetailsArray[i].StartCustomAddress }</td>`;
            }else{
              tableRows +=        `<td class="white-space-normall min-width-300 max-width-400" data-event="start">
                                      <a href="#" class="link showAddress">${ LANGUAGE.REPORT_PANEL_MSG63 }</a>
                                  </td>`;
            }
            tableRows +=          `<td data-order="${ tableTripDetailsArray[i].EndTimeUnix }">${ tableTripDetailsArray[i].EndTimeLocal }</td>`
            if (tableTripDetailsArray[i].EndCustomAddress) {
              tableRows +=        `<td class="white-space-normall min-width-300 max-width-400">${ tableTripDetailsArray[i].EndCustomAddress }</td>`;
            }else{
              tableRows +=        `<td class="white-space-normall min-width-300 max-width-400" data-event="stop">
                                      <a href="#" class="link showAddress">${ LANGUAGE.REPORT_PANEL_MSG63 }</a>
                                  </td>`;
            }
            tableRows +=          `<td>${ tableTripDetailsArray[i].TimeSpan }</td>
                                   <td data-order="${ tableTripDetailsArray[i].Mileage }">
                                      ${ tableTripDetailsArray[i].Mileage } ${ LANGUAGE.COM_MSG79 }
                                   </td>
                                   <td data-order="${ tableTripDetailsArray[i].Fuel }">
                                      ${ tableTripDetailsArray[i]?.Fuel ? tableTripDetailsArray[i].Fuel + ' ' + LANGUAGE.COM_MSG80 : LANGUAGE.COM_MSG103 }
                                   </td>`

            if(self.AdditionalReportInfo.Options.MaxSpeed){
              tableRows +=         `<td data-order="${ tableTripDetailsArray[i].MaxSpeed }">
                                      ${ tableTripDetailsArray[i].MaxSpeed } ${ LANGUAGE.COM_MSG81 }
                                   </td>`
            }
            if(self.AdditionalReportInfo.Options.AvgSpeed){
              tableRows +=         `<td data-order="${ tableTripDetailsArray[i].AverageSpeed }">
                                      ${ tableTripDetailsArray[i].AverageSpeed } ${ LANGUAGE.COM_MSG81 }
                                   </td>`
            }

            tableRows +=           `<td>${ tableTripDetailsArray[i].SpeedingEvents }</td>
                                   <td>
                                      <a href="#" class='button button-fill button-small elevation-2 button-table color-red getPlayback'>
                                          ${ LANGUAGE.REPORT_PANEL_MSG64 }
                                      </a>
                                   </td>
                              </tr>`;
          }
        }

        let popupContent = `
        <div class="popup popup-tablet-fullscreen popup-report-trip-details-table" >
          <div class="view">
            <div class="page">
              <div class="navbar">
                  <div class="navbar-inner">
                      <div class="left"></div>
                      <div class="title">${ modalTitle } - ${ self.AdditionalReportInfo.TimePeriodText }</div>
                      <div class="right">
                          <a href="#" class="link popup-close" data-popup=".popup-report-trip-details-table">
                              <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 display-flex">
                    <div class="block no-margin">
                        <p class="text-color-black">
                            <i class="f7-icons icon-driver text-color-gray vertical-middle margin-right"></i>
                            <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG212 }:</span>
                            ${ positionData.DriverID }
                        </p>
                        <p class="text-color-black">
                            <i class="f7-icons icon-driver text-color-gray vertical-middle margin-right"></i>
                            <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG181 }:</span>
                            ${ positionData.Driver }
                        </p>
                        <p class="text-color-black">
                            <i class="f7-icons icon-name text-color-gray vertical-middle margin-right"></i>
                            <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG37 }:</span>
                            ${ positionData.AssetName }
                        </p>
                        <p class="text-color-black">
                            <i class="f7-icons icon-header-reports text-color-gray vertical-middle margin-right"></i>
                            <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG139 }:</span>
                            ${ positionData.Registration }
                        </p>
                    </div>
                    <div class="block no-margin">
                          <p class="text-color-black">
                              <i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
                              <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG140 }:</span>
                              ${ positionData.Make }
                          </p>
                          <p class="text-color-black">
                              <i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
                              <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG141 }:</span>
                              ${ positionData.Model }
                          </p>
                          <p class="text-color-black">
                              <i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
                              <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG142 }:</span>
                              ${ positionData.Color }
                          </p>
                          <p class="text-color-black">
                              <i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
                              <span class="text-color-gray">${ LANGUAGE.REPORT_PANEL_MSG143 }:</span>
                              ${ positionData.Year }
                          </p>
                    </div>
                  </div>

                  <div class="card display-flex align-items-center">
                    <div class="card-content">
                      <div class="list no-hairlines ">
                        <ul>
                          <li>
                            <div class="item-content">
                              <div class="item-media">
                                <i class="f7-icons icon-report-duration text-color-gray"></i>
                              </div>
                                <div class="item-inner">
                                  <div class="item-title">
                                     ${ LANGUAGE.REPORT_PANEL_MSG96 }
                                  </div>
                                  <div class="item-after">
                                    ${ positionData.TotalDuration }
                                  </div>
                                </div>
                              </div>
                            </li>
                            <li>
                              <div class="item-content">
                                <div class="item-media">
                                  <i class="f7-icons icon-report-distance text-color-gray"></i>
                                </div>
                                <div class="item-inner">
                                  <div class="item-title">
                                      ${ LANGUAGE.REPORT_PANEL_MSG97 }
                                  </div>
                                  <div class="item-after">
                                      ${ positionData.TotalMileage } ${ LANGUAGE.COM_MSG79 }
                                  </div>
                                </div>
                              </div>
                            </li>
                            <li>
                              <div class="item-content">
                                <div class="item-media">
                                  <i class="f7-icons icon-report-fuel text-color-gray"></i>
                                </div>
                                <div class="item-inner">
                                  <div class="item-title">
                                      ${ LANGUAGE.REPORT_PANEL_MSG98 }
                                  </div>
                                  <div class="item-after">
                                      ${ positionData.TotalFuel } ${ LANGUAGE.COM_MSG80 }
                                  </div>
                                </div>
                              </div>
                            </li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                      <table id="table-report-trip-details" class="mdl-data-table tableReportTripDetails" style="width:100%">
                          <thead>
                              <tr>
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG214} </th> <!-- Time Tagged On  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG102} </th> <!-- Start Address  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG215} </th> <!-- Time Tagged Off  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG103} </th> <!-- Stop Address  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG101} </th> <!-- Duration  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG104} </th> <!-- Distance  -->
                                  <th class=""> ${ LANGUAGE.REPORT_PANEL_MSG107} </th> <!-- Fuel  -->`
        if(self.AdditionalReportInfo.Options.MaxSpeed) {
          popupContent +=         `<th class=""> ${LANGUAGE.REPORT_PANEL_MSG105} </th> <!-- Max Speed  -->`
        }
        if(self.AdditionalReportInfo.Options.AvgSpeed) {
          popupContent +=         `<th class=""> ${LANGUAGE.REPORT_PANEL_MSG159} </th> <!-- Max Speed  -->`
        }
        popupContent +=           `<th class=""> ${ LANGUAGE.REPORT_PANEL_MSG200} </th> <!-- Speeding  -->

                                  <th class="no-export"> ${ LANGUAGE.REPORT_PANEL_MSG109} </th> <!-- Playback  -->
                              </tr>
                         </thead>
                      <tbody>
                          ${ tableRows }
                      </tbody>
                  </table>
              </div>
            </div>
          </div>
        </div>
        `
        setTimeout(function(){
          self.DynamicTripDetailsPopup = self.$app.popup.create({
            backdrop: true,
            closeByBackdropClick: false,
            animate: false,
            content: popupContent,
              on: {
                  open: function (popup) {
                      //$('#table-report-trip-details').append('<caption style="caption-side: top">A fictional company\'s staff table.</caption>');
                      let messageTopLeft =    LANGUAGE.REPORT_PANEL_MSG212+': '+positionData.DriverID+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG181+': '+positionData.Driver+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG37+': '+positionData.AssetName+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG139+': '+positionData.Registration+' \n';

                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG140+': '+positionData.Make+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG141+': '+positionData.Model+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG142+': '+positionData.Color+' \n';
                      messageTopLeft +=       LANGUAGE.REPORT_PANEL_MSG143+': '+positionData.Year+' \n';

                      let messageTopRight =    LANGUAGE.REPORT_PANEL_MSG96+': '+positionData.TotalDuration+' \n';
                      messageTopRight +=       LANGUAGE.REPORT_PANEL_MSG97+': '+positionData.TotalMileage+' '+LANGUAGE.COM_MSG79+' \n';
                      messageTopRight +=       LANGUAGE.REPORT_PANEL_MSG98+': '+positionData.TotalFuel+' '+LANGUAGE.COM_MSG80+' \n';

                      let dtExportColumnIndxs = self.getDTExportColumnsIndx(popup.$el.find('table'));
                      self.DATATABLEReportTripDetails = $('#table-report-trip-details').DataTable({
                          //dom: 'Blfrtip',
                          dom: '<"mdl-grid"<"mdl-cell mdl-cell--12-col"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: [
                                  /*{
                                      text: LANGUAGE.COM_MSG105,
                                      className: 'mdl-button mdl-button--raised bg-color-darkgray text-color-white',
                                      action: function ( e, dt, node, config ) {
                                          this.disable();
                                          getAllAddresses()
                                      }
                                  },*/
                                  {
                                      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,
                                      title: '',
                                      filename: modalTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
                                      //messageTop: messageTopLeft,
                                      exportOptions: {
                                          columns: dtExportColumnIndxs,
                                      },
                                      customize: function (xlsx) {
                                          //console.log(xlsx);
                                          var sheet = xlsx.xl.worksheets['sheet1.xml'];

                                          //clear title
                                         // $('c[r=A1] t', sheet).text( '' );

                                           //clear default created header
                                          $('row:first c', sheet).text( '' );

                                          //select created header and make it bold
                                          var headerRow = $('row', sheet);
                                          $(headerRow[10]).find('c').attr( 's', '2' );

                                          //make asset details caption cells bold
                                          for (var i = 2; i <= 9; i++) {
                                              $('c[r=A'+i+']', sheet).attr( 's', '2' );
                                          }
                                          //make total caption cells bold
                                          for (var i = 2; i <= 4; i++) {
                                              $('c[r=D'+i+']', sheet).attr( 's', '2' );
                                          }
                                      },
                                      customizeData: function(data){
                                          //console.log(data);
                                          //We want the first line so we disabled the header above. Let's add in our descriptions. Then we're going to add them to the top of the body and do the bolding ourselves with the customize function.
                                          var desc = [
                                              [LANGUAGE.REPORT_PANEL_MSG212, positionData.DriverID, '', LANGUAGE.REPORT_PANEL_MSG96, positionData.TotalDuration ],
                                              [LANGUAGE.REPORT_PANEL_MSG181, positionData.Driver, '', LANGUAGE.REPORT_PANEL_MSG97, positionData.TotalMileage +' '+LANGUAGE.COM_MSG79 ],
                                              [LANGUAGE.REPORT_PANEL_MSG37, positionData.AssetName, '', LANGUAGE.REPORT_PANEL_MSG98, positionData.TotalFuel +' '+LANGUAGE.COM_MSG80 ],
                                              [LANGUAGE.REPORT_PANEL_MSG139, positionData.Registration],
                                              [LANGUAGE.REPORT_PANEL_MSG140, positionData.Make ],
                                              [LANGUAGE.REPORT_PANEL_MSG141, positionData.Model ],
                                              [LANGUAGE.REPORT_PANEL_MSG142, positionData.Color ],
                                              [LANGUAGE.REPORT_PANEL_MSG143, positionData.Year ],
                                              [''],
                                          ];

                                          data.body.unshift(data.header);
                                          for (var i = desc.length - 1; i >= 0; i--) {
                                              data.body.unshift(desc[i]);
                                          }
                                          //data.header.length = 0;
                                      }
                                  },
                                  {
                                      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
                                      },
                                      //messageTop: messageTop,
                                      orientation: 'landscape',
                                      customize: function (doc) {
                                          //console.log(doc);
                                          //Remove the title created by datatTables
                                          //doc.content.splice(0,1);
                                          //Create a date string that we use in the footer. Format is dd-mm-yyyy
                                          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();
                                          // Logo converted to base64
                                          //var logo = self.$app.methods.getBase64FromImageUrl(self.$app.data.AppDetails.loginUrl+self.$app.data.AppDetails.logoLetterSrc);
                                          //console.log(logo);
                                          //console.log(self.$app.data.AppDetails.loginUrl+self.$app.data.AppDetails.logoLetterSrc);
                                          // The above call should work, but not when called from codepen.io
                                          // So we use a online converter and paste the string in.
                                          // Done on http://codebeautify.org/image-to-base64-converter
                                          // It's a LONG string scroll down to see the rest of the code !!!
                                          //var logo = 'data:image/jpeg;base64,/9j/4AA';
                                          // A documentation reference can be found at
                                          // https://github.com/bpampuch/pdfmake#getting-started
                                          // Set page margins [left,top,right,bottom] or [horizontal,vertical]
                                          // or one number for equal spread
                                          // It's important to create enough space at the top for a header !!!
                                          doc.pageMargins = [20,120,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
                                              }
                                          });
                                          // Change dataTable layout (Table styling)
                                          // To use predefined layouts uncomment the line below and comment the custom lines below
                                         // doc.content[0].layout = 'lightHorizontalLines'; // noBorders , headerLineOnly
                                          /*var objLayout = {};
                                          objLayout['hLineWidth'] = function(i) { return .5; };
                                          objLayout['vLineWidth'] = function(i) { return .5; };
                                          objLayout['hLineColor'] = function(i) { return '#aaa'; };
                                          objLayout['vLineColor'] = function(i) { return '#aaa'; };
                                          objLayout['paddingLeft'] = function(i) { return 4; };
                                          objLayout['paddingRight'] = function(i) { return 4; };
                                          doc.content[0].layout = objLayout;*/
                                    }
                                  },
                                  {
                                      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: modalTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
                                      messageTop: messageTopLeft,
                                      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: modalTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
                                      messageTop: messageTopLeft,
                                      exportOptions: {
                                          columns: dtExportColumnIndxs
                                      },
                                      orientation: 'landscape',
                                  }
                              ]
                          },

                          order: [[0, 'desc']],
                          columnDefs: [{ targets: [ 1, 3, popup.$el.find('table thead th').length - 1 ], orderable: false,  }],
                          lengthMenu: [5, 10, 25, 50, 100],
                          pageLength: 10,
                          fixedColumns: {
                            left: 0,
                            right: 1,
                          },
                      });


                      function getAllAddresses(){
                        self.$app.progressbar.show();

                        let latlngArrStart = [];
                        let latlngArrEnd = [];
                        for (var i = 0; i < tableTripDetailsArray.length; i++) {
                          latlngArrStart.push([tableTripDetailsArray[i].BeginLat, tableTripDetailsArray[i].BeginLng]);
                          latlngArrEnd.push([tableTripDetailsArray[i].EndLat, tableTripDetailsArray[i].EndLng]);
                        }
                           const promisesStart = [];
													const promisesEnd = [];
       
													for (var i = 0; i < latlngArrStart.length; i++) {
														promisesStart.push(self.getAllAddresses(latlngArrStart[i][0], latlngArrStart[i][1]));
													}
													for (var i = 0; i < latlngArrEnd.length; i++) {
														promisesEnd.push(self.getAllAddresses(latlngArrEnd[i][0], latlngArrEnd[i][1]));
													}

                        Promise.all(promisesStart)
                          .then(values => {
                        
                           // self.$app.progressbar.hide();
                            if (values) {
                              self.DATATABLEReportTripDetails.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
                                if (values[rowIdx])
                                {
                                  var data = this.data();
                                  data[1] = values[rowIdx];
                                  this.data(data);
                                  tableTripDetailsArray[rowIdx].StartCustomAddress = values[rowIdx];
                                }
                              } );
                            }
                        
                          })
                          .catch((error) => {
															return error
														})
                        Promise.all(promisesEnd)
                          .then(values => {
                        
                            self.$app.progressbar.hide();
                        
                            if (values) {
                              self.DATATABLEReportTripDetails.rows().every( function ( rowIdx, tableLoop, rowLoop )
                              {
                                if (values[rowIdx])
                                {
                                  var data = this.data();

                                  data[3] = values[rowIdx];

                                  this.data(data);
                                  tableTripDetailsArray[rowIdx].EndCustomAddress = values[rowIdx];
                                }
                              } );
                            }
                          })
                          .catch((error) => {
															return error
														})
                      }

                      //if addresses not loaded yet
                      if(!tableTripDetailsArray[0].StartCustomAddress){
                        getAllAddresses()
                      }




                      popup.$el.find('.tableReportTripDetails').on('click', '.showAddress', function(e){
                          var wrapper2 = $$(e.target).closest('[role="row"]');
                          var index2 = wrapper2.data('item-index');
                          var parent2 = $$(e.target).closest('td');
                          var event = $$(parent2).data('event');
                          //console.log(tableTripDetailsArray[index2]);
                          if (event == 'start') {
                            if (tableTripDetailsArray[index2].StartCustomAddress) {
                              parent2.html(tableTripDetailsArray[index2].StartCustomAddress);
                            }else{
                              parent2.html('<p><span class="progressbar-infinite color-red"></span></p>');
                              Protocol.Helper.getAddressByGeocoder({lat: tableTripDetailsArray[index2].BeginLat, lng: tableTripDetailsArray[index2].BeginLng},function(address){
                              parent2.html(address);
                              tableTripDetailsArray[index2].StartCustomAddress = address;
                              });
                            }
                          }else{
                            if (tableTripDetailsArray[index2].EndCustomAddress) {
                              parent2.html(tableTripDetailsArray[index2].EndCustomAddress);
                            }else{
                              parent2.html('<p><span class="progressbar-infinite color-red"></span></p>');
                              Protocol.Helper.getAddressByGeocoder({lat: tableTripDetailsArray[index2].EndLat, lng: tableTripDetailsArray[index2].EndLng},function(address){
                                  parent2.html(address);
                                  tableTripDetailsArray[index2].EndCustomAddress = address;
                              });
                            }
                          }
                      });


                      popup.$el.find('.tableReportTripDetails').on('click', '.getPlayback', function(e){
                          var wrapper2 = $$(e.target).closest('[role="row"]');
                          var index2 = wrapper2.data('item-index');
                          var reportTimeFormat =  'YYYY/MM/DDTHH:mm:ss';

                          var data = {
                              MinorToken: self.UserInfo.MinorToken,
                              //MajorToken: userInfo.MajorToken,
                              Code: POSINFOASSETLIST[positionData.IMEI].Id, //POSINFOASSETLIST[]
                              From: moment(tableTripDetailsArray[index2].BeginTime, reportTimeFormat).format(window.COM_TIMEFORMAT2),
                              To: moment(tableTripDetailsArray[index2].EndTime, reportTimeFormat).format(window.COM_TIMEFORMAT2),
                          };
                          var additioanalData = {
                              Name: positionData.AssetName,
                              IMEI: positionData.IMEI,
                          }
                          self.getPlaybackData(data, additioanalData);
                      });

                  },
                  close: function(popup){
                      if (self.DATATABLEReportAssets ) {
                          self.DATATABLEReportAssets.destroy();
                      }
                  },
                  closed: function(popup){


                      popup.$el.remove();
                      popup.destroy();
                  },
              }
            }).open();
        }, 200);
      },
            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;
            },
            getPlaybackData: function(data, additioanalData){
                var self = this;
                //console.log(data);
                self.$app.dialog.progress();
                self.$app.request.get(API_URL.GET_PLAYBACK_ARR, data, function(result, xhr, status) {
                        //console.log(result);
                        self.$app.dialog.close();
                        if (result.MajorCode == '000' && result.Data) {
                            if (!result.Data.HisArry.length) {
                                app.dialog.alert(LANGUAGE.COM_MSG35, LANGUAGE.ASSET_PLAYBACK_MSG00, function() { app.dialog.close(); });
                            } else {
                                self.showMapPlayback(result.Data, additioanalData);
                            }
                        } else if (result.MajorCode == '100' && result.MinorCode == '1002') {
                            app.dialog.alert(LANGUAGE.ASSET_PLAYBACK_MSG04, LANGUAGE.ASSET_PLAYBACK_MSG00, function() { app.dialog.close(); });
                        } else {
                            app.dialog.alert(LANGUAGE.ASSET_PLAYBACK_MSG04, LANGUAGE.ASSET_PLAYBACK_MSG00, function() { app.dialog.close(); });
                        }

                    },
                    function(xhr, status) {
                        self.$app.dialog.close();
                        self.$app.dialog.alert('Error occured at get Playback data');
                    },
                    'json');
            },
            showMapPlayback: function(playbackData, additioanalData){
                var self = this;

                //var assetList = self.$app.methods.getFromStorage('assetList');
                var asset = POSINFOASSETLIST[additioanalData.IMEI]; //assetList[additioanalData.IMEI];
                self.HistoryArray = self.$app.methods.parsePlaybackHystoryArr(playbackData.HisArry);
                self.EventsArray = self.$app.methods.parsePlaybackEventsArr(playbackData.HisEvents);
                self.$setState({
                    PointsCount: self.HistoryArray.length-1
                });


                    if (self.DynamicMapPopup && !self.DynamicMapPopup.destroyed) {
                        self.DynamicMapPopup.close();
                    }

                    setTimeout(function(){
                        self.DynamicMapPopup = app.popup.create({
                            backdrop: true,
                            closeByBackdropClick: false,
                            animate: false,
                            content: `
          <div class="popup popup-report-map" >
          <div class="view">
          <div class="page">
          <div class="navbar">
          <div class="navbar-inner">
          <div class="left"></div>
          <div class="title">${ additioanalData.Name }</div>
          <div class="right">
          <a href="#" class="link popup-close" data-popup=".popup-report-map">
          <i class="f7-icons">close</i>
          </a>
          </div>
          </div>
          </div>
          <div class="page-content bg-color-lightgray padding-bottom-120 " >
          <div id="mapReport" class="mapReport"></div>
          <div class="modal-playback-controls">
          <div class="list no-hairlines margin-bottom-8">
          <ul>
          <div class="row">
          <div class="col-50 desktop-33">
          <li>
          <a class="item-link smart-select smartSelectPlaybackSpeed" data-open-in="popover" data-close-on-select="true">
          <select name="PlaybackSpeed" >
          <option value="1000">x1</option>
          <option value="500">x2</option>
          <option value="250">x4</option>
          <option value="125">x8</option>
          <option value="62">x16</option>
          </select>
          <div class="item-content">
          <div class="item-inner">
          <div class="item-title "> ${ LANGUAGE.ASSET_PLAYBACK_MSG07 }</div>
          </div>
          </div>
          </a>
          </li>
          </div>
          <div class="col-50 desktop-33">
          <li class="item-content">
          <div class="item-inner">
          <div class="item-title">${ LANGUAGE.ASSET_PLAYBACK_MSG01 }</div>
          <div class="item-after">
          <label class="toggle">
          <input type="checkbox" name="checkbox-optimized" ${ self.OptimizedRouteState ? 'checked="checked"' : '' }  >
          <span class="toggle-icon"></span>
          </label>
          </div>
          </div>
          </li>
          </div>
          </div>
          </ul>
          </div>
          <div class="list simple-list card card-playback-range-slider elevation-6 elevation-hover-9 elevation-transition no-margin-top no-hairlines">
          <ul class="card-content bg-color-red text-color-white">
          <li>
          <div class="item-cell width-auto flex-shrink-0 link padding-top-4 playback-controll-button playbackControllButton cursor-pointer">
          <i class="f7-icons icon-play size-15"></i>
          </div>
          <div class="item-cell flex-shrink-3">
          <div class="range-slider range-slider-playback rangeSliderPlayback color-white " >
          <input type="range" min="0" max="${ self.PointsCount }" step="1" value="0">
          </div>
          </div>
          </li>
          </ul>
          </div>
          </div>
          </div>
          </div>
          </div>
          </div>
          `,
                                    on: {
                                        open: function (popup) {
                                            var rangeSliderEl = popup.$el.find('.rangeSliderPlayback');
                                            var optimizedSwitcher = popup.$el.find('input[name="checkbox-optimized"]');
                                            var playbackControllButton = popup.$el.find('.playbackControllButton');
                                            var playbackControllButtonIcon = popup.$el.find('.playbackControllButton i');
                                            var playbackSmartSelectEl = popup.$el.find('.smartSelectPlaybackSpeed')
                                            var playbackSpeed = popup.$el.find('[name="PlaybackSpeed"]');
                                            var lastQueryPosinfo = {};//save last  query  position

                                            self.MapTrackReport = Protocol.Helper.createMap({ target: 'mapReport', latLng: [self.HistoryArray[0].lat, self.HistoryArray[0].lng], zoom: 14 });
                                            self.showPlaybackRoute();
                                            self.getOptimizedRoute(self.HistoryArray);

                                            /*MARKER ADDING*/
                                            var PlaybackMarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[0]);
                                            self.PlaybackMarkerGroup = L.markerClusterGroup({'maxClusterRadius':35,});
                                            self.PlaybackMarker = L.marker([self.HistoryArray[0].lat, self.HistoryArray[0].lng], {icon: Protocol.MarkerIcon[2]});
                                            self.PlaybackMarker.bindPopup(PlaybackMarkerData,{maxWidth:self.$app.data.MaxMapPopupWidth, closeButton: false});

                                            self.PlaybackMarker.addTo(self.PlaybackMarkerGroup);
                                            self.PlaybackMarkerGroup.addTo(self.MapTrackReport);

                                            Protocol.Helper.getAddressByGeocoder({ lat: self.HistoryArray[0].lat, lng: self.HistoryArray[0].lng },function(address){
                                                self.HistoryArray[0].customAddress = address;
                                                var newMarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[0]);
                                                self.PlaybackMarker.setPopupContent(newMarkerData);
                                            });


                                            self.RangeSliderPlayback = app.range.create({
                                                el: rangeSliderEl,
                                                on: {
                                                    change: function (e, val) {
                                                        //console.log('changed');
                                                        var MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);

                                                        self.PlaybackMarker.setLatLng([self.HistoryArray[val].lat, self.HistoryArray[val].lng]).setPopupContent(MarkerData);
                                                        self.MapTrackReport.setView([self.HistoryArray[val].lat, self.HistoryArray[val].lng]);

                                                        if(lastQueryPosinfo && Math.floor(self.HistoryArray[val].lat * 10000) / 10000 === lastQueryPosinfo.lat && Math.floor(self.HistoryArray[val].lng * 10000) / 10000 === lastQueryPosinfo.lng ){

                                                            self.HistoryArray[val].customAddress = lastQueryPosinfo.address;
                                                            MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);
                                                            self.PlaybackMarker.setPopupContent(MarkerData);
                                                        }else{
                                                            var latlng = {
                                                                lat: self.HistoryArray[val].lat,
                                                                lng: self.HistoryArray[val].lng
                                                            };

                                                            Protocol.Helper.getAddressByGeocoder(latlng,function(address){
                                                                lastQueryPosinfo = {lat : Math.floor(latlng.lat * 10000) / 10000, lng : Math.floor(latlng.lng * 10000) / 10000, address: address };

                                                                self.HistoryArray[val].customAddress = address;
                                                                if (self.HistoryArray[val+1]) {
                                                                    self.HistoryArray[val+1].customAddress = address;
                                                                }

                                                                MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);
                                                                self.PlaybackMarker.setPopupContent(MarkerData);
                                                            });
                                                        }


                                                    }
                                                }
                                            });

                                            self.SmartSelectPlaybackSpeed = app.smartSelect.create({
                                                el: playbackSmartSelectEl,
                                                view: reportView,
                                                openIn: 'popover',
                                                closeOnSelect: true,
                                            })

                                            optimizedSwitcher.on('change', function(){
                                                if (!self.CantBeOptimised) {
                                                    self.$setState({
                                                        OptimizedRouteState: this.checked
                                                    });
                                                    if (this.checked) {
                                                        if (self.PlaybackRouteLayerGroupOptimized) {
                                                            self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroup);
                                                            self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroupOptimized);
                                                        }
                                                    }else{
                                                        if (self.PlaybackRouteLayerGroup) {
                                                            self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroupOptimized);
                                                            self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroup);
                                                        }
                                                    }
                                                }else{
                                                    self.$app.methods.customNotification({
                                                        title: LANGUAGE.ASSET_PLAYBACK_MSG00,
                                                        text: LANGUAGE.PROMPT_MSG041
                                                    });
                                                    this.checked = false;

                                                    self.$setState({
                                                        OptimizedRouteState: false
                                                    });
                                                }
                                            });

                                            playbackControllButton.on('click', function(){
                                            if (self.PlaybackTimer) {
                                                self.stopPlaybackPlayer(playbackControllButtonIcon);

                                            }else{
                                                playbackControllButtonIcon.removeClass('icon-play').addClass('icon-stop');

                                                var interval = parseInt(playbackSpeed.val());
                                                self.PlaybackTimer = setInterval(playbackIntrvalFunc, interval);
                                            }
                                        });

                                        function playbackIntrvalFunc(){
                                            clearInterval(self.PlaybackTimer);
                                            var interval = parseInt(playbackSpeed.val());
                                            self.PlaybackTimer = setInterval(playbackIntrvalFunc, interval);

                                            var value = self.RangeSliderPlayback.getValue();
                                            if (value != self.PointsCount) {
                                                value++;
                                                self.RangeSliderPlayback.setValue(value);
                                            }else{
                                                self.RangeSliderPlayback.setValue(0);
                                                value = 0;
                                                self.stopPlaybackPlayer(playbackControllButtonIcon);
                                            }
                                        }

                                        },
                                        closed: function(popup){
                                            //self.MapTrackReport.removeLayer(self.ReportMarker);
                                            if (self.PlaybackRouteLayerGroup) {
                                                MapTrack.removeLayer(self.PlaybackRouteLayerGroup);
                                            }
                                            if (self.PlaybackRouteLayerGroupOptimized) {
                                                MapTrack.removeLayer(self.PlaybackRouteLayerGroupOptimized);
                                            }
                                            if (self.PlaybackMarkerGroup) {
                                                MapTrack.removeLayer(self.PlaybackMarkerGroup);
                                            }
                                            if (self.PlaybackEventsLayerGroup) {
                                                MapTrack.removeLayer(self.PlaybackEventsLayerGroup);
                                            }
                                            if (self.RangeSliderPlayback) {
                                                self.RangeSliderPlayback.destroy();
                                            }
                                            if (self.SmartSelectPlaybackSpeed) {
                                                self.SmartSelectPlaybackSpeed.destroy();
                                            }

                                            self.stopPlaybackPlayer();
                                            self.$setState({
                                                PlaybackRouteLayerGroup: false,
                                                PlaybackRouteLayerGroupOptimized: false,
                                                PlaybackMarkerGroup: false,
                                                PlaybackEventsLayerGroup: false,
                                            })
                                            self.MapTrackReport.remove();
                                            popup.$el.remove();
                                            popup.destroy();
                                        },
                                    }
                        }).open();

                    }, 200);

            },
            stopPlaybackPlayer: function($icon){
                var self = this;
                if ($icon) {
                    $icon.removeClass('icon-stop').addClass('icon-play');
                }
                clearInterval(self.PlaybackTimer);
                self.PlaybackTimer = false;
            },
            showPlaybackRoute: function(){
                var self = this;

                if (self.PlaybackRouteLayerGroup && self.PlaybackMarkerGroup) {
                    if (self.OptimizedRouteState && self.PlaybackRouteLayerGroupOptimized) {
                        self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroupOptimized);
                        self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroupOptimized.getBounds());
                    }else{
                        self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroup);
                        self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroup.getBounds());
                    }
                    self.MapTrackReport.addLayer(self.PlaybackMarkerGroup);
                    self.MapTrackReport.addLayer(self.PlaybackEventsLayerGroup);


                }else{

                    /*PLAYBACK ROUTE ADDING*/
                    var polylinePoints = [];

                    for (var i = self.HistoryArray.length - 1; i >= 0; i--) {
                        var point = new L.LatLng(self.HistoryArray[i].lat, self.HistoryArray[i].lng);
                        polylinePoints.push(point);
                    }

                    var polylineBG = new L.Polyline(polylinePoints, self.$app.data.PolylineCustomization.mainBg);
                    var polyline = new L.Polyline(polylinePoints, self.$app.data.PolylineCustomization.main);
                    self.PlaybackRouteLayerGroup = L.featureGroup([polylineBG, polyline]);
                    self.PlaybackRouteLayerGroup.addTo(self.MapTrackReport);

                    self.MapTrackReport.fitBounds(polyline.getBounds());     // zoom the map to the polyline

                    /*EVENTS POINTS ADDING*/
                    if (self.EventsArray && self.EventsArray.length) {
                        self.PlaybackEventsLayerGroup = L.markerClusterGroup({'maxClusterRadius':35,});
                        var markerData = '';
                        var point = '';
                        var popupAddresses = {};

                        $.each( self.EventsArray, function(index,value){
                            if (parseFloat(value.lat) !== 0 && parseFloat(value.lng) !== 0) {
                                if (value.eventClass == 1 ||  value.eventClass == 4 && value.eventType == 0) {  //filtering to display only   1-Alert(alarms) , 2-ACC , 4 - static  events
                                    value.index = index;
                                    markerData = self.$app.methods.getPlaybackMarkerDataTableInfoPin(value); //, {GeofenceList: self.GeofenceList}
                                    point = L.marker([value.lat, value.lng], {icon: Protocol.MarkerIcon[3]});
                                    point.bindPopup(markerData,{ maxWidth:self.$app.data.MaxMapPopupWidth, closeButton: false})
                                        .on('popupopen', function (marker) {
                                            if (popupAddresses[index]) {
                                                $$('body #mapReport').find('[data-popupIdAddress="'+index+'"]').html(popupAddresses[index]);
                                            }else{
                                                Protocol.Helper.getAddressByGeocoder(this.getLatLng(),function(address){
                                                    $$('body #mapReport').find('[data-popupIdAddress="'+index+'"]').html(address);
                                                    popupAddresses[index] = address;
                                                });
                                            }
                                        });
                                    self.PlaybackEventsLayerGroup.addLayer(point);
                                }
                            }
                        });

                        self.MapTrackReport.addLayer(self.PlaybackEventsLayerGroup);
                    }


                }


            },
            getOptimizedRoute: function(historyArray){
                var self = this;

                var rawArray = [];
                $.each( historyArray, function(index,value){
                    rawArray.push([
                        null,
                        null,
                        null,
                        new Date(value.positionTime * 1000),
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        value.lat,   //lat
                        value.lng,   // lng
                        null,
                        value.direct,   //direct
                        value.speed,   //speed
                        value.mileage    //mileage
                    ]);
                });

                app.progressbar.show();

                $.ajax({
                    type: "POST",
                    url: API_URL.GET_PLAYBACK_ARR_OPTIMISED,
                    dataType: "json",
                    data: JSON.stringify(rawArray),
                    contentType: 'application/json',
                    async: true,
                    cache: false,
                    timeout: 10000,
                    success: function (result) {
                        //console.log(result);
                        var polylineOptBg = new L.Polyline(result.polylines, self.$app.data.PolylineCustomization.mainBg);
                        var polylineOpt = new L.Polyline(result.polylines, self.$app.data.PolylineCustomization.main);
                        self.PlaybackRouteLayerGroupOptimized = L.featureGroup([polylineOptBg,polylineOpt]);

                        if (result.dropped) {
                            var polylineOptDroppedBg = new L.Polyline(result.dropped, self.$app.data.PolylineCustomization.droppedBg);
                            var polylineOptDropped = new L.Polyline(result.dropped, self.$app.data.PolylineCustomization.dropped);
                            self.PlaybackRouteLayerGroupOptimized.addLayer(polylineOptDroppedBg).addLayer(polylineOptDropped);
                        }
                        if (result.boundaries) {
                            var polylineOptBoundariesBg = new L.Polyline(result.boundaries, self.$app.data.PolylineCustomization.boundariesBg);
                            var polylineOptBoundaries = new L.Polyline(result.boundaries, self.$app.data.PolylineCustomization.boundaries);
                            self.PlaybackRouteLayerGroupOptimized.addLayer(polylineOptBoundariesBg).addLayer(polylineOptBoundaries);
                        }
                        if (self.OptimizedRouteState) {
                            if (self.MapTrackReport.hasLayer(self.PlaybackRouteLayerGroup)) {
                                self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroup);
                            }
                            self.PlaybackRouteLayerGroupOptimized.addTo(self.MapTrackReport);
                            self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroupOptimized.getBounds());     // zoom the map to the polyline
                        }

                        app.progressbar.hide();
                    },
                    error: function (textStatus) {
                        app.progressbar.hide();
                        setTimeout(function(){
                            app.progressbar.hide();
                        }, 500);

                        console.log(textStatus);
                        if (self.OptimizedRouteState) {
                            self.$app.methods.customNotification({
                                title: LANGUAGE.ASSET_PLAYBACK_MSG00,
                                text: LANGUAGE.PROMPT_MSG041
                            });
                        }

                        self.$setState({OptimizedRouteState: false, CantBeOptimised: true});
                        self.showPlaybackRoute();
                    }
                });

            },
          	getAllAddresses: function (lat, lng) {
              return new Promise((resolve) => {
                Protocol.Helper.getAddressByGeocoder({ lat: lat, lng: lng }, function (address) {
                  resolve(address);
                });			 
              });

           },
        },

        on: {
            pageInit: function (e, page) {
              var self = this;
              if (!self.Type) {
                return
              }


              var columnDefs = [
                  { targets: [ page.$el.find('table thead th').length - 1 ], orderable: false,  }
              ];
              var order = [[0, 'asc']];

              let dtExportColumnIndxs = self.getDTExportColumnsIndx(page.$el.find('table'));

              DATATABLEReport = $('#table-report').DataTable({
                dom: '<"mdl-grid"<"mdl-cell mdl-cell--12-col"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>>',
                columnDefs: columnDefs,
                order: order,
                lengthMenu: [5, 10, 25, 50, 100],
                pageLength: 5,

                fixedColumns: {
                  left: 0,
                  right: 1,
                },

                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,
                      title: self.PageTitle,
                      filename: self.PageTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
                      //messageTop: messageTopLeft,
                      exportOptions: {
                        columns: dtExportColumnIndxs,
                      },
                      customize: function (xlsx) {

                      },
                      customizeData: function(data){

                      }
                    },
                    {
                      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
                      },
                      //messageTop: messageTop,
                      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,120,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;


                        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
                          }
                        });

                        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,
                      //messageTop: messageTopLeft,
                      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  + ' - ' + self.AdditionalReportInfo.TimePeriodText,
                      //messageTop: messageTopLeft,
                      exportOptions: {
                        columns: dtExportColumnIndxs
                      },
                      orientation: 'landscape',
                    }
                  ]
                },
              });

                let graphicsColumns = {
                  HarshBracking: [],
                  HarshAccelerate: [],
                  ExcessiveIdling: [],
                  Speeding: [],
                };
                for (var i = self.ReportData.length - 1; i >= 0; i--) {
                    graphicsColumns.HarshBracking.push( [ self.ReportData[i].Driver, self.ReportData[i].HarshBracking ] );
                    graphicsColumns.HarshAccelerate.push( [ self.ReportData[i].Driver, self.ReportData[i].HarshAccelerate ] );
                    graphicsColumns.ExcessiveIdling.push( [ self.ReportData[i].Driver, self.ReportData[i].ExcessiveIdling ] );
                    graphicsColumns.Speeding.push( [ self.ReportData[i].Driver, 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-GHarshAcc',
                    columns: graphicsColumns.HarshAccelerate
                  },
                  {
                    name: LANGUAGE.REPORT_PANEL_MSG199,
                    bindto: '#chart-GExcesiveIDLE',
                    columns: graphicsColumns.ExcessiveIdling
                  },
                  {
                    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>