<!--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>


			<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 class="no-export"> {{@global.LANGUAGE.REPORT_PANEL_MSG104}} </th>
						<th>{{@global.LANGUAGE.REPORT_PANEL_MSG101}}</th>
						<th>{{@global.LANGUAGE.REPORT_PANEL_MSG105}}</th>
						<th>{{@global.LANGUAGE.REPORT_PANEL_MSG106}}</th>
						<th>{{@global.LANGUAGE.REPORT_PANEL_MSG107}}</th>
						<th>Start Date</th>
						<th>End Date</th>
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG201}} </th> <!-- Points(of 100)  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG246}} </th> <!-- CheckList  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG76}} </th> <!-- Details  -->




					</tr>
				</thead>
				<tbody>

					{{#ReportData}}
					<tr data-item-index="{{@index}}" data-task-code="{{TaskCode}}">
						<td><i class="f7-icons icon-name text-color-gray vertical-middle margin-right"></i>
							{{AssetName}}</td>
						<td>{{Imei}}</td>
						<td>{{Stars.template}}</td><!--  -->
						<td class="text-align-left">{{Distance}}</td>
						<td class="text-align-left">{{DurationFormatted}}</td>
						<td class="text-align-left">{{MaxSpeedFormatted}}</td>
						<td class="text-align-left">{{AvgSpeedFormatted}}</td>
						<td class="text-align-left">{{Fuel}}</td>
						<td class="text-align-left">{{StartDateFormat}}</td>
						<td class="text-align-left">{{EndDateFormat}}</td>
						<td class=" bold {{Stars.color}}">{{PointsFormatted}}</td>
						<!--  -->

						<td class="text-align-left">
							<a @click="getModalWithCheckList" href="#"
								class='button button-fill button-small elevation-2 button-table color-green'>
								<i
									class="f7-icons icon-show-assets vertical-middle margin-right"></i>{{@global.LANGUAGE.REPORT_PANEL_MSG64}}
							</a>
						</td>
						<td class="text-align-left">
							<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 splitBy = self.$route.query.splitby;
				//console.log(self);
				//console.log(type);
				var pageTitle = Protocol.Helper.getReportTypeName(type);

				var reportData = self.$app.methods.getFromStorage('reportData');
				var tripsArray = self.$app.methods.getFromStorage('reportDataTrips');
			 
			 
			 
				for (let i = reportData.length - 1; i >= 0; i--) {
					reportData[i].Distance = 0
					let trips = tripsArray.filter(item => item.TaskCode == reportData[i].TaskCode)
					let maxSpeedArray = []
					let sumAvgSpeed = 0
					reportData[i].Fuel = 0
					reportData[i].tripsCount = trips.length
					if(trips.length) {
						if (trips.length == 1) {				 
						console.log('t',trips)
						
						console.log('_',moment.duration(reportData[i].Duration, "milliseconds").format('d[d] h[h] m[m] s[s]'))		
						console.log('_',moment(trips[0].BeginTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('MMMM DD YYYY, HH:mm'))		
						console.log('_', moment(trips[trips.length - 1].EndTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('MMMM DD YYYY, HH:mm'))		
						
						reportData[i].Duration = Protocol.Helper.getDifferenceBTtwoDates(trips[0].BeginTime, trips[0].EndTime);
						reportData[i].DurationFormatted = moment.duration(reportData[i].Duration, "milliseconds").format('d[d] h[h] m[m] s[s]');
						reportData[i].StartDateFormat = moment(trips[0].BeginTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('YYYY-MM-DD HH:mm')
						reportData[i].EndDateFormat = moment(trips[0].EndTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('YYYY-MM-DD HH:mm')
					} else {				
						reportData[i].Duration = Protocol.Helper.getDifferenceBTtwoDates(trips[0].BeginTime, trips[trips.length - 1].EndTime);
						for (let k = trips.length - 1; k >= 0; k--) {
						
							reportData[i].DurationFormatted = moment.duration(reportData[i].Duration, "milliseconds").format('d[d] h[h] m[m] s[s]');
							if(k == 0) reportData[i].StartDateFormat = moment(trips[0].BeginTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('YYYY-MM-DD HH:mm')
							if(k == trips.length - 1) reportData[i].EndDateFormat = moment(trips[trips.length - 1].EndTime, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('YYYY-MM-DD HH:mm')
						}
					}
					for (let k = trips.length - 1; k >= 0; k--) {
						maxSpeedArray.push(trips[k].MaxSpeed)
						sumAvgSpeed += trips[k].AvgSpeed
						reportData[i].Fuel += trips[k].FuelUsed
						reportData[i].Distance += trips[k].Mileage
					}
					reportData[i].AvgSpeedFormatted = sumAvgSpeed / trips.length
					reportData[i].MaxSpeedFormatted = Math.max.apply(null, maxSpeedArray)
					}else{
					}
					 
				}
				if (type && reportData && reportData.length) {
				for (let i = reportData.length - 1; i >= 0; i--) {

					//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(100).toFixed(1);  //reportData[i].Points

					reportData[i].Stars = self.$app.methods.getStars(100) //reportData[i].Points


				}
			}

		 

			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.filter(el => +el.tripsCount > 0),
				AdditionalReportInfo: {
					From: self.$route.query.from,
					To: self.$route.query.to,
					TimePeriodText: moment(self.$route.query.from, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('MMMM DD YYYY, HH:mm') + ' - ' + moment(self.$route.query.to, window.COM_TIMEFORMAT2).add(self.$app.data.UTCOFFSET, 'minutes').format('MMMM DD YYYY, HH:mm'),
				},

				ChartsArr: [],

			};
		 
			 
				
		 
			 
			


		 
	 
		 return ret;


		},
		methods: {
			getModalWithCheckList: function (e) {
				var self = this;
				var wrapper5 = $$(e.target).closest('[role="row"]');
				let code = wrapper5.data('task-code');
				let errFunc = function (err) {
					if (err) {
						self.dialog.alert(LANGUAGE.PROMPT_MSG0127 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}<br>${result.Data}`);
					} else {
						self.dialog.alert(LANGUAGE.PROMPT_MSG0121);
					}
				};
				let tripsArray = self.$app.methods.getFromStorage('reportDataTrips');
				
				let trip = tripsArray.find(item => item.TaskCode == code)

				let addUrlParams = '?TaskCode=' + code

				self.$app.methods.getCheckList(addUrlParams)
					.then(function (checkList) {
						console.log(checkList)
						if (self.DynamicTripCheckList && !self.DynamicTripCheckList.destroyed) {
							self.DynamicTripCheckList.close();
						}
						var tableRows2 = '';
						if (checkList.length > 0) {
							for (var i = 0; i < checkList.length; i++) {
								let questionName = ''
								let questionId = checkList[i].OptionCode

								switch (questionId) {
									case '11':
										questionName = 'Existing Damage'
										break
									case '12':
										questionName = 'New Damage'
										break
									case '13':
										questionName = 'Other Reparations Needed'
										break
									case '14':
										questionName = 'Vehicle Washed & Clean Inside'
										break
									case '21':
										questionName = 'Existing Damage'
										break
									case '22':
										questionName = 'Floor Needs Repairs'
										break
									case '23':
										questionName = 'Floor Dirty or Clean'
										break
									case '31':
										questionName = 'Existing Damage'
										break
									case '32':
										questionName = 'Panel Needs Repairs'
										break
									case '41':
										questionName = 'Visible Tyre Damage'
										break
									case '42':
										questionName = 'Tyre Needs Replacing'
										break
									case '51':
										questionName = 'Take Picture of Load Sheet'
										break
									case '52':
										questionName = 'Take Picture of Seal'
										break
									case '61':
										questionName = 'Oil'
										break
									case '62':
										questionName = 'Water'
										break
								}

								let catId = checkList[i].OptionCode.substr(0, 1)
								
								if (questionId == '11' || questionId == '21' || questionId == '31' || questionId == '41' || questionId == '51' || questionId == '61') {
							 	  tableRows2 += `<tr data-item-index="${i}" role="row" >`

									tableRows2 += `<td  `

									switch (questionId) {
										case '11':
											tableRows2 += `rowspan = "4"`
											break
										case '21':
											tableRows2 += `rowspan = "3"  `
											break
										case '31':
											tableRows2 += `rowspan = "2" `
											break
										case '41':
											tableRows2 += `rowspan = "2"   `
											break
										case '51':
											tableRows2 += `rowspan = "2" `
											break
										case '61':
											tableRows2 += `rowspan = "2"  `
											break
									}

									tableRows2 += `>`
									switch (catId) {
										case '1':
											tableRows2 += `<span  style="position: absolute; top: 15px;"> ${LANGUAGE.REPORT_PANEL_MSG247}</span>	 `
											break
										case '2':
											tableRows2 += `<span  style="position: absolute; top: 15px;">${LANGUAGE.REPORT_PANEL_MSG248}</span>  `
											break
										case '3':
											tableRows2 += `<span  style="position: absolute; top: 15px;">${LANGUAGE.REPORT_PANEL_MSG249}</span>  `
											break
										case '4':
											tableRows2 += `<span  style="position: absolute; top: 15px;">${LANGUAGE.REPORT_PANEL_MSG250}</span>  `
											break
										case '5':
											tableRows2 += `<span  style="position: absolute; top: 15px;">${LANGUAGE.REPORT_PANEL_MSG251}</span>  `
											break
										case '6':
											tableRows2 += `<span  style="position: absolute; top: 15px;">${LANGUAGE.REPORT_PANEL_MSG252}</span>  `
											break
									}

									tableRows2 += ` <td style="padding-left: 24px;">${questionName}</td> 
									<td  >${checkList[i].Result}</td> 
									<td style="padding-left: 24px;">${checkList[i].Message}</td> `
							 
									if(!checkList[i].Photo.length ) {
									tableRows2 += `<td></td>`
								} else {
									tableRows2 += ` 
							    	<td >
									<a class="getModalWithPhoto table-img-container"  href="#"
									class=''>
									<img class="table-img" src="https://upload.quiktrak.co/Attachment/images/${checkList[i].Photo}"/>
									</a>
									</td>`
								}
								
								tableRows2 += `</tr>`;
								} else {
									
								tableRows2 += ` 
								<tr  data-item-index="${i}" role="row">
									<td>${questionName}</td>
									<td>${checkList[i].Result}</td>
									<td>${checkList[i].Message}</td>`
								 
								if(!checkList[i].Photo.length ) {
									tableRows2 += `<td></td>`
								} else {
								
									tableRows2 += ` <td>
									<a class="getModalWithPhoto table-img-container"  href="#"
									class=''>
									<img class="table-img" src="https://upload.quiktrak.co/Attachment/images/${checkList[i].Photo}"/>
									</a>
									</td>`
								}
									
								tableRows2 +=	`</tr>`;
								}

							}
						}
						setTimeout(function () {
							self.DynamicTripCheckList = app.popup.create({
								backdrop: true,
								closeByBackdropClick: false,
								animate: false,
								content: `
							<div class="popup popup-tablet-fullscreen popup-report-trip-checklist" >
					  <div class="view">
						  <div class="page">
							  <div class="navbar">
								  <div class="navbar-inner">
									  <div class="left"></div>
									  <div class="title">Checklist Report</div>
									  <div class="right">
										  <a href="#" class="link popup-close" data-popup=".popup-report-trip-checklist">
											  <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-name text-color-gray vertical-middle margin-right"></i>
												  <span class="text-color-gray">${LANGUAGE.REPORT_PANEL_MSG37}:</span>
												  ${trip.AssetName}
											  </p>
											 
											 
										  </div>
										 
									  </div>

									  
								</div>
								  
								  <table id="table-report-checklist" class="mdl-data-table tableCheckList" style="width:100%">
									  <thead>
										  <tr>
											  <th class=""> Checklist </th>  
								       	<th style="padding-left: 24px;" class="">  Question </th>  
										   <th class=""> Answer  </th>  
										   <th class=""> Notes  </th>  
										   <th style="text-align: center" class=""> Photo  </th>  
									
									</tr>
									</thead>
									<tbody>
									${tableRows2}
									</tbody>
									</table>

								    </div>
									</div>
									</div>
									</div>
							`,
								on: {
									open: function(popup) {
										

								popup.$el.find('.tableCheckList').on('click', '.getModalWithPhoto', function (e) {
									var wrapper6 = $$(e.target).closest('[role="row"]');
									var index6 = wrapper6.data('item-index');
									var parent6 = $$(e.target).closest('td');
									var event = $$(parent6).data('event');
									console.log(checkList[index6])

								 



									self.ReportChecklistPhotoPopup = app.popup.create({
										backdrop: true,
										closeByBackdropClick: false,
										animate: false,
										content: `
														<div class="popup  popup-report-checklist-photo" >
														<div class="view">
															<div class="page">
																<div class="navbar">
																	<div class="navbar-inner">
																		<div class="left"></div>
																		<div class="title"> Photo </div>
																		<div class="right">
																			<a href="#" class="link popup-close" data-popup=".popup-report-checklist-photo">
																				<i class="f7-icons">close</i>
																			</a>
																		</div>
																	</div>
																</div>
																<div class="page-content " >

																	<div class="block">
																		<div  class="top-img-wrapper">
																			<div  class="top-img-content" >
																				<img src="https://upload.quiktrak.co/Attachment/images/${checkList[index6].Photo}" alt="${checkList[index6].Photo}" 
																			></div></div>
																	</div>
																 
																</div>

																</div>
															</div>
														</div>`,
										on: {
											closed: function (popup) {
												popup.$el.remove();
												popup.destroy();
											},
										}
									}).open()

								})
									},
									closed: function (popup) {
										popup.$el.remove();
										popup.destroy();
									},
								}
							}).open();
						}, 200)

					}, errFunc)





			},

			getModalWithTripDetails: function (e) {
				var self = this;
				var wrapper = $$(e.target).closest('[role="row"]');
				var tripsArray = self.$app.methods.getFromStorage('reportDataTrips');



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

				console.log(tripsArray)

				var tableTripDetailsArray = tripsArray.filter(item => item.TaskCode == taskCode)

				//console.log(tableTripDetailsArray)

				var modalTitle = self.PageTitle;


				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++) {
						//tableTripDetailsArray[i].TableRowIndex = i;
						tableRows += `<tr data-item-index="${i}" role="row" >
							  <td>${tableTripDetailsArray[i].BeginTime}</td>
							  <td>${tableTripDetailsArray[i].EndTime}</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>`;
						}

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

						if (tableTripDetailsArray[i].GenralNote) {
							tableRows += ` 

							  <td data-order="${tableTripDetailsArray[i].GenralNote}">
								  ${tableTripDetailsArray[i].GenralNote}  
							  </td>`
						} else {
							tableRows += ` 

<td data-order=" ">
	 
</td>`
						}

						if (tableTripDetailsArray[i].Notes[0]) {
							tableRows += ` 
									<td class="text-align-center"  data-event="delivery" data-order="${tableTripDetailsArray[i].Notes[0].Code}">

										<a class="getModalWithPhoto table-img-container"  href="#"
								class=''>
									 <img class="table-img" src="https://upload.quiktrak.co/Attachment/images/${tableTripDetailsArray[i].Notes[0].PhotoPath}"/>
									</a>
									</td>`} else {
							tableRows += ` 
									<td class="text-align-center"  data-event="delivery" >

									 
									</td>`
						}
						if (tableTripDetailsArray[i].Notes[1]) {
							tableRows += `	<td class="text-align-center"  data-event="stock"  data-order="${tableTripDetailsArray[i].Notes[1].Code}">

<a class="getModalWithPhoto table-img-container" href="#"
class=''>
<img class="table-img" src="https://upload.quiktrak.co/Attachment/images/${tableTripDetailsArray[i].Notes[1].PhotoPath}"/>
</a>
</td>
									`
						} else {
							tableRows += ` 
									<td class="text-align-center"  data-event="stock" >

									 
									</td>`
						}

						tableRows += ` 

							  <td data-order="${tableTripDetailsArray[i].MaxSpeed}">
								  ${tableTripDetailsArray[i].MaxSpeed} ${LANGUAGE.COM_MSG81}
							  </td>
							 
							  <td data-order="${tableTripDetailsArray[i].FuelUsed}">
								  ${tableTripDetailsArray[i].FuelUsed} ${LANGUAGE.COM_MSG80}
							  </td>
							 
								 

						  </tr>`;
					}
				}


				setTimeout(function () {
					self.DynamicTripDetailsPopup = app.popup.create({
						backdrop: true,
						closeByBackdropClick: false,
						animate: false,
						content: `
				  		<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}</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-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-calendar text-color-gray vertical-middle margin-right"></i>
												  <span class="text-color-gray">${LANGUAGE.REPORT_PANEL_MSG110}:</span>
												  ${tableTripDetailsArray[0].BeginTime}
											  </p>
											  <p class="text-color-black">
												  <i class="f7-icons icon-calendar text-color-gray vertical-middle margin-right"></i>
												  <span class="text-color-gray">${LANGUAGE.REPORT_PANEL_MSG111}:</span>
												  ${tableTripDetailsArray[tableTripDetailsArray.length - 1].EndTime}
											  </p>
										  </div>
										 
									  </div>

									  
								</div>
								  <table id="table-report-trip-details" class="mdl-data-table tableReportTripDetails" style="width:100%">
									  <thead>
										  <tr>
											  <th class=""> ${LANGUAGE.REPORT_PANEL_MSG99} </th> <!-- Start Time  -->
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG100} </th> <!-- Stop Time  -->
									
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG102} </th> <!-- Start Address  -->
									
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG103} </th> <!-- Stop Address  -->

									
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG242} </th> <!-- General  Note   -->
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG243} </th> <!-- Delivery  Note   -->
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG244} </th> <!-- Picture of the stock
									-->
									
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG105} </th> <!-- Max Speed  -->
									
									<th class=""> ${LANGUAGE.REPORT_PANEL_MSG107} </th> <!-- Fuel  -->
									
									</tr>
									</thead>
									<tbody>
									${tableRows}
									</tbody>
									</table>

									</div>
									</div>
									</div>
									</div>
									`,
						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_MSG37 + ': ' + positionData.AssetName + ' \n';




								popup.$el.find('.tableReportTripDetails').on('click', '.getModalWithPhoto', function (e) {
									var wrapper4 = $$(e.target).closest('[role="row"]');
									var index4 = wrapper4.data('item-index');
									var parent4 = $$(e.target).closest('td');
									var event = $$(parent4).data('event');
									console.log(tableTripDetailsArray[index4])

									let popupTitle = event == 'delivery' ? LANGUAGE.REPORT_PANEL_MSG243 : LANGUAGE.REPORT_PANEL_MSG244
									let notesItem = event == 'delivery' ? tableTripDetailsArray[index4].Notes[0] : tableTripDetailsArray[index4].Notes[1]



									self.ReportTripMediaPopup = app.popup.create({
										backdrop: true,
										closeByBackdropClick: false,
										animate: false,
										content: `
														<div class="popup  popup-report-trip-media" >
														<div class="view">
															<div class="page">
																<div class="navbar">
																	<div class="navbar-inner">
																		<div class="left"></div>
																		<div class="title"> ${popupTitle} </div>
																		<div class="right">
																			<a href="#" class="link popup-close" data-popup=".popup-report-trip-media">
																				<i class="f7-icons">close</i>
																			</a>
																		</div>
																	</div>
																</div>
																<div class="page-content " >

																	<div class="block">
																		<div  class="top-img-wrapper">
																			<div  class="top-img-content" >
																				<img src="https://upload.quiktrak.co/Attachment/images/${notesItem.PhotoPath}" alt="${notesItem.PhotoPath}" 
																			></div></div>
																	</div>
																	<div class="block">
																		<div class="list no-margin no-hairlines">
																			<ul>
																				<li>
																					<div class="item-content">
																						<div class="item-media text-color-lightgray">
																							<i class="f7-icons icon-admin-support"></i>
																						</div>
																						<div class="item-inner flex-direction-column align-items-flex-start">
																							<div class="item-title item-label">
																								${LANGUAGE.REPORT_PANEL_MSG245}
																							</div>
																							<div class="size-20 margin-top-4">${notesItem.PhotoNote}</div>
																						</div>
																					</div>
																				</li>
																			
																			</ul>
																		</div>
																	</div>
																</div>

																</div>
															</div>
														</div>`,
										on: {
											closed: function (popup) {
												popup.$el.remove();
												popup.destroy();
											},
										}
									}).open()

								})



								popup.$el.find('.tableReportTripDetails').on('click', '.showAddress', function (e) {
									var wrapper3 = $$(e.target).closest('[role="row"]');
									var index3 = wrapper3.data('item-index');
									var parent3 = $$(e.target).closest('td');
									var event = $$(parent3).data('event');



									//console.log(tableTripDetailsArray[index3]);
									if (event == 'start') {

										parent3.html('<p><span class="progressbar-infinite color-red"></span></p>');
										Protocol.Helper.getAddressByGeocoder({ lat: tableTripDetailsArray[index3].StartLat, lng: tableTripDetailsArray[index3].StartLng }, function (address) {
											parent3.html(address);
											tableTripDetailsArray[index3].StartCustomAddress = address;
										});

									} else {

										parent3.html('<p><span class="progressbar-infinite color-red"></span></p>');
										Protocol.Helper.getAddressByGeocoder({ lat: tableTripDetailsArray[index3].EndLat, lng: tableTripDetailsArray[index3].EndLng }, function (address) {
											parent3.html(address);
											tableTripDetailsArray[index3].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 = 'DD/MM/YYYY HH:mm:ss';

									var data = {
										MinorToken: self.UserInfo.MinorToken,
										//MajorToken: userInfo.MajorToken,
										Code: positionData.ID, //POSINFOASSETLIST[]
										From: moment(tableTripDetailsArray[index2].StartTime, reportTimeFormat).format(window.COM_TIMEFORMAT2),
										To: moment(tableTripDetailsArray[index2].EndTime, reportTimeFormat).format(window.COM_TIMEFORMAT2),
									};
									var additioanalData = {
										Name: positionData.Name,
										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);









			},

			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>