
<!--suppress JSAnnotator -->
<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
		<div class="page " data-name="asset-alarm"> <!-- page-with-subnavbar -->
		<!-- Top Navbar -->
			<div class="navbar">
				<div class="navbar-inner">
					<div class="left">
						<a href="#" class="link back">
							<i class="icon icon-back"></i>
						</a>
					</div>
					<div class="title sliding">{{@global.LANGUAGE.ASSET_LIST_MSG03}}</div>
					<div class="right">
					
					</div>

				</div>
			</div>

			<div class="bottom-section-wrapper bottom-section-button-wrapper bg-color-white">
				<div class="row">
					<label for="submit-form" class="col button button-fill color-green elevation-2" tabindex="0" >{{@global.LANGUAGE.COM_MSG06}}</label>
				</div>
			</div>

			<!-- Scrollable page content-->
			<form name="AssetAlarmForm" class="page-content">
				<input type="hidden" name="IMEI" value="{{IMEI}}">
				<input type="submit" id="submit-form" class="display-none" />
				<div class="block-title text-color-darkgray">{{@global.LANGUAGE.ASSET_LIST_MSG03}}</div>
				<div class="block">
					<p>{{@global.LANGUAGE.PROMPT_MSG000}}</p>
				</div>

				{{#if ShowAdditionalBlocks}}
					<div key="IgnoreBetween" class="list no-hairline-bottom">
						<ul>
							<li class="item-content">
								<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.COM_MSG71}}</div>
									<div class="item-after">
										<label class="toggle toggle-ignore-between">
											<input type="checkbox" name="IgnoreBetweenState" {{#if IgnoreBetweenState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
										</label>
									</div>
								</div>
							</li>
							<li>
								<div class="item-content item-input {{#unless IgnoreBetweenState}} disabled {{/unless}}">
									<div class="item-media text-color-lightgray">
										<i class="f7-icons icon-time-period"></i>
									</div>
									<div class="item-inner">
										<div class="row">
											<div class="col">
												<div class="item-title item-label ">{{@global.LANGUAGE.COM_MSG69}}</div>
												<div class="item-input-wrap">
													<input type="text" name="PickerStart" readonly="readonly" />
												</div>
											</div>
											<div class="col">
												<div class="item-title item-label ">{{@global.LANGUAGE.COM_MSG70}}</div>
												<div class="item-input-wrap">
													<input type="text" name="PickerEnd" readonly="readonly" />
												</div>
											</div>
										</div>
									</div>
								</div>
							</li>
							<li>
								<a class="item-link smart-select custom-smart-select smart-select-days-of-week {{#unless IgnoreBetweenState}} disabled {{/unless}}" data-open-in="popover">
									<select name="IgnoreDays" multiple>
										{{#each DaysOfWeek}}
											<option value="{{val}}" data-display-as="{{displayAs}}" {{#if selected}} selected {{/if}}>{{name}}</option>
										{{/each}}
									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons icon-calendar"></i>
										</div>
										<div class="item-inner">
											<div class="item-title item-label">{{@global.LANGUAGE.COM_MSG72}}</div>
										</div>
									</div>
								</a>
							</li>
						</ul>
					</div>
				{{/if}}

				{{#if ShowAlarmList}}
					<div key="AlarmList" class="list no-hairline-bottom">
						<ul>
							
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title text-transform-uppercase">{{TurnOnAll.title}}</div>
									<div class="item-after">
								  		<label class="toggle toggle-all-alarm">
											<input type="checkbox" name="checkbox-alarm-all" {{#if TurnOnAll.state}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>

							{{#each Alarms}}
								<li>
									<label class="item-checkbox item-content">
										<input type="checkbox" class="checkbox-alarm-push" name="checkbox-alarm" value="{{this.val}}" {{#if this.state}}checked="checked"{{/if}}/>
										<i class="icon icon-checkbox"></i>
										<div class="item-inner">
											<div class="item-title">{{this.title}}</div>
										</div>
									</label>
								</li>
							{{/each}}
						</ul>
					</div>
					
					
					<div key="AlarmEmailList" class="list no-hairline-bottom no-margin-top">
						<ul>
							<li class="item-content">
								<div class="item-inner">
									<div class="item-title text-transform-uppercase">{{TurnOnAllEmail.title}}</div>
									<div class="item-after">
										<label class="toggle toggle-email-all-alarm ">
											<input type="checkbox" name="checkbox-email-alarm-all"
												{{#if TurnOnAllEmail.state}}checked="checked" {{/if}}>
											<span class="toggle-icon"></span>
										</label>
									</div>
								</div>
							</li>

							{{#each AlarmsEmail}}
							<li>
								<label class="item-checkbox item-content ">
									<input type="checkbox" name="checkbox-alarm-email"   class="checkbox-alarm-email" value="{{this.val}}"
										{{#if this.state}}checked="checked" {{/if}} />
									<i class="icon icon-checkbox"></i>
									<div class="item-inner">
										<div class="item-title">{{this.title}}</div>
									</div>
								</label>
							</li>
							{{/each}}
						</ul>
					</div>
					
			
					<div class="block-title  no-margin-top">Email</div>
					<div class="list no-hairline-bottom">
						<ul>
							<li class="{{#if NoContacts}} tooltip-init {{/if}}" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG128}}<br>{{@global.LANGUAGE.PROMPT_MSG129}}">
								<a class="item-link smart-select smart-select-init custom-smart-select {{#if NoContacts}} disabled  {{/if}}" data-open-in="popup" data-searchbar="true" data-close-on-select="true" data-form-color-theme="green" >
									<select name="EmailsToSend" multiple>
										{{#ContactList}}
										<option
										  value="{{EMail}}"
										  data-display-as="{{FirstName}} {{SubName}}"
										  {{#if Selected}} selected {{/if}}
										>{{FirstName}} {{SubName}}{{#if EMail}} - {{EMail}}{{/if}}</option>
										{{/ContactList}}

									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons size-16 icon-email asset_list_icon text-color-lightgray vertical-middle"></i>
                                        </div>
										<div class="item-inner">
											<div class="item-title item-label">Contact</div>

										</div>
									</div>
								</a>
							</li>					
							<!--<li>
								<div class="item-content item-input">
									<div class="item-media text-color-lightgray">
										 
									</div>
									<div class="item-inner">
										<div class="item-title item-floating-label item-label"></div>
										<div class="item-input-wrap">
											<input type="text" name="EmailsToSend" placeholder="You can add additional emails" value="{{EmailsToSend}}">
										</div>
										
                                        <div class="divider"></div>
										
									</div>
								</div>
							</li>-->
						</ul>
					</div>
					
					
					{{#if isWatch}}
					
					<div class="divider"></div>
					<div class="block-title">Phone</div>
					<div class="list no-hairline-bottom">
						<ul>
							<li class="{{#if NoContacts}} tooltip-init {{/if}}" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG128}}<br>{{@global.LANGUAGE.PROMPT_MSG129}}">
								<a class="item-link smart-select smart-select-init custom-smart-select {{#if NoContacts}} disabled  {{/if}}" data-open-in="popup" data-searchbar="true" data-close-on-select="true" data-form-color-theme="green" >
									<select name="PhonesToSend" multiple>
										{{#ContactPhoneList}}
										<option
										  value="{{Mobile}}"
										  data-display-as="{{FirstName}} {{SubName}}"
										  {{#if Selected}} selected {{/if}}
										>{{FirstName}} {{SubName}}{{#if Mobile}} - {{Mobile}}{{/if}}</option>
										{{/ContactPhoneList}}

									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons size-16 icon-email asset_list_icon text-color-lightgray vertical-middle"></i>
                                        </div>
										<div class="item-inner">
											<div class="item-title item-label">Contact</div>

										</div>
									</div>
								</a>
							</li>	
						</ul>
					</div>
					{{/if}}


					{{#if ShowOfflineBlock}}

					<div key="Offline" class="list no-hairline-bottom  ">
						<ul>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG32}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG0100}}"></i></div>
									<div class="item-after">
								  		<label class="toggle">
											<input type="checkbox" name="checkbox-alarm" class="disablingController" value="67108864" {{#if OfflineState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							{{#OfflineOptions}}
								<li>
									<label class="item-checkbox item-content {{#unless ../OfflineState}}disabled{{/unless}}">
										<input type="checkbox" name="offline-option" value="{{Value}}" {{#if State}}checked="checked"{{/if}}/>
										<i class="icon icon-checkbox"></i>
										<div class="item-inner">
											<div class="item-title">{{Name}}</div>
										</div>
									</label>
								</li>
							{{/OfflineOptions}}
						</ul>
					</div>
                {{/if}}

                {{#if ShowAdditionalBlocks}}
				{{#if ShowOverspeedBlock}}
					<div key="Overspeed" class="list no-hairline-bottom">
						<ul>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG23}}</div>
									<div class="item-after">
								  		<label class="toggle">
											<input type="checkbox" name="checkbox-alarm" class="disablingController" value="32" {{#if OverspeedState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							<li>
							    <label class="item-radio item-content disablingObj {{#unless OverspeedState}}disabled{{/unless}}">
							        <input type="radio" name="overspeed-type" value="1" {{#js_if ' !this.SpeedingMode || this.SpeedingMode == 1 '}} checked{{/js_if}}/>
							        <i class="icon icon-radio"></i>
							        <div class="item-inner">
							          	<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG31}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG098}}"></i></div>
							        </div>
							    </label>
							</li>

							<li>
							    <label class="item-radio item-content disablingObj {{#unless OverspeedState}}disabled{{/unless}}">
							        <input type="radio" name="overspeed-type" value="2" {{#js_if ' this.SpeedingMode == 2 '}} checked{{/js_if}} />
							        <i class="icon icon-radio"></i>
							        <div class="item-inner">
							          	<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG30}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG099}}"></i></div>
							        </div>
							    </label>
							</li>
						</ul>
					</div>
					{{/if}}

					{{/if}}
				{{else}}
					<div key="AlarmListPreloader" class="block block-strong text-align-center">
						<div class="preloader color-red"></div>
					</div>
				{{/if}}

			</form>
		</div>
</template>


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

			let assetList = self.$app.methods.getFromStorage('assetList');
			let IMEI = decodeURIComponent(self.$route.params.imei);
			let index = IMEI.indexOf(',');
			
			
			let contactList = self.$app.methods.getFromStorage('contactList');
            contactList = self.$app.methods.sortContactList(contactList);
			//console.log('contactList',contactList)

			let maxSpeedUnit = index === -1 ? assetList[IMEI].Unit : assetList[IMEI.split(',')[0]].Unit;
			let maxSpeed = index === -1 ? assetList[IMEI].MaxSpeed : 80; 

			let ret = {
				isWatch: false,
				AlarmListType: 3,
				ShowAlarmList: false,
				Alarms: [],
				AlarmsEmail: [],
				ToggleAllAlarms: false,
				ALL_JUST_CUSTOM_PUSH_ALARMS_OFF: 0,
				ALL_JUST_CUSTOM_EMAIL_ALARMS_OFF: 0,
				TurnOnAll: {
					state: false,
					title: LANGUAGE.ASSET_ALARM_MSG45, 
				},
				TurnOnAllEmail: {
					state: false,
					title: LANGUAGE.ASSET_ALARM_MSG46,
				},
				toggleEmailEl: false,
				togglePushEl: false,
				IMEI: IMEI,
				
				Name: index === -1 ? assetList[IMEI].Name : LANGUAGE.ASSET_ALARM_MSG00,
                
				MaxSpeedUnit: maxSpeedUnit,
				MaxSpeed: Protocol.Helper.getSpeedValue(maxSpeedUnit, maxSpeed),

				EmailNotificationsState: true,
				PushNotificationsState: true,
				ShowAdditionalBlocks: false,
				IgnoreBetweenState: false,
				TimePickerStart: false,
				TimePickerEnd: false,
				DaysOfWeek: [],
				DaysOfWeekSelect: false,
                ContactList: contactList,
                ContactPhoneList: [],
                NoContacts: contactList.length < 1,
				
                ReadOnly:  true,
                AllPermissions: false,
                ShowOverspeedBlock: false,
                ShowOfflineBlock: false,
				EmailsToSend: '',
				PhonesToSend: ''
			};
 			
			return ret;
		},
		methods: {
			getAlarmOptions: function(){
				let self = this;

				if (!self.$route.params || !self.$route.params.imei ) {
					console.log('There is no params or imei param');
				}else{

					let imeiArr = self.IMEI.split(',');
					let assetList = self.$app.methods.getFromStorage('assetList');

					if (imeiArr.length > 1) {
						
						if ( self.$route.query.solution && self.$route.query.solution.toLowerCase().indexOf('track') !== -1 ||
							self.$route.query.solution && self.$route.query.solution.toLowerCase().indexOf('watch') !== -1||
							self.$route.query.solution && self.$route.query.solution.toLowerCase().indexOf('life') !== -1
						){
							
							self.AlarmListType = 2;
						}else if(self.$route.query.solution && self.$route.query.solution.toLowerCase().indexOf('protect') !== -1){
							
							self.AlarmListType = 1;
						}
						self.AlarmListType = 2;//~~added

						self.loadAlarmList({
							AlarmListType: self.AlarmListType,
							AssetType: assetList[imeiArr[0]] ? assetList[imeiArr[0]].AssetType : '',
							AlarmOptions: 2147483647,
							AlarmEmailOptions: 2147483647,
							
						});
					}else{

						let asset = assetList[self.$route.params.imei];
						
						if (asset) {
							if (
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('track') !== -1 ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('watch') !== -1 ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('life') !== -1)
							{ 
								self.AlarmListType = 2

							}else if(asset.SolutionType && asset.SolutionType.toLowerCase() === 'loc8' ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('loc8') !== -1
							){ 
								
								
								self.AlarmListType = 3
							}else{ 
								
								
								self.AlarmListType = 1
							}
							
							self.AlarmListType = 2;//~~added
							
							let userInfo = self.$app.methods.getFromStorage('userInfo');
								let data = {
									MajorToken: userInfo.MajorToken,
									MinorToken: userInfo.MinorToken,
									IMEI: self.$route.params.imei
								};
								app.request.post(API_URL.GET_ALERT_CONFIG, data, function (result, xhr, status) {
								if (result && typeof result != 'object') {
									result = JSON.parse(result)
									
                                    if (result && result.MajorCode === '000') {
                                        self.loadAlarmList({
                                            AlarmListType: self.AlarmListType, //live
                                            AssetType: asset.AssetType,
                                            AlarmOptions: result.Data.AlertTypes,
											AlarmEmailOptions: result.Data.EmailAlertTypes,

                                            LiveAssetSettings: result.Data,
                                        });
                                    } else {
                                        self.loadAlarmList({
                                            AlarmListType: self.AlarmListType,    //live
                                            AssetType: asset.AssetType,
                                            AlarmOptions: asset.AlarmOptions,
											AlarmEmailOptions: asset.AlarmOptions,
                                        });
                                    }
									}
								});
						}
					}
				}

			},
			loadAlarmList: function(data){
				let self = this;
				let imeiArr = self.IMEI.split(',');
				let assetList = self.$app.methods.getFromStorage('assetList');
					
				if (data && data.AlarmListType) {

					let userAlarmSettings = self.$app.methods.getFromStorage('userAlarmSettings');
					
					let AlarmSolution = assetList[imeiArr[0]] ? assetList[imeiArr[0]].SolutionType : ''
					let AlarmProduct = assetList[imeiArr[0]] ? assetList[imeiArr[0]].PRDTName : ''
					let ActualAlarmNames = assetList[imeiArr[0]]?.ActualAlarmNames ? assetList[imeiArr[0]]?.ActualAlarmNames : []

					self.$setState({
						isWatch: AlarmSolution == 'Watch' ? true : false
					})
					
					let urlAlOp = 'https://testapi.quiktrak.co/QuikTrak/V1/User/GetAlarmOptionsBySolution?SolutionCode='+AlarmSolution+'&ProductName='+AlarmProduct
					app.request.get(urlAlOp, function (result, xhr, status) {
							let alarmList = []
							let alarmEmailList = []
					
							console.log(result)
							if (result && typeof result != 'object') {
								result = JSON.parse(result)
								if (result?.MajorCode == '000') {
								
								if(parsedDealer != "lite"  && parsedDealer != "ridersadvantage"){
									self.$setState({
										EmailOptions:  result?.Data?.Email,
										PushOptions:  result?.Data?.Push,
									})
								}else{
									self.$setState({
										EmailOptions:  ["4","8","16","32","1024","32768","65536","67108864"], //result?.Data?.Email,
										PushOptions:  ["4","8","16","32","1024","32768","65536","67108864"] //result?.Data?.Push,
									})
								}
								console.log(!self.PushOptions?.length && !self.EmailOptions?.length)

								if (!self.PushOptions?.length && !self.EmailOptions?.length) {
                                    self.$app.dialog.alert('Alarm settings not supported');
                                    return
                                }
								
								for(let i = 0;i < self.PushOptions?.length;i++){
									if(ActualAlarmNames?.findIndex(el => el.AlertId == self.PushOptions[i]) != -1) { 
                                        alarmList.push({
                                            state: true,
                                            val: +self.PushOptions[i],
                                            title: ActualAlarmNames?.find(el => el.AlertId == self.PushOptions[i])?.AlertName,
									    }) 

                                    } else {
                                        alarmList.push({
                                            state: true,
                                            val: +self.PushOptions[i],
                                            title: AlarmSolution.toLowerCase().indexOf('witi') !== -1 && self.PushOptions[i] == 131072 ? 'Witi Alarm' : Protocol.Helper.getAletTypeName(self.PushOptions[i]),
									    })
                                    }
								}
								for(let i = 0;i < self.EmailOptions?.length;i++){
									if(ActualAlarmNames?.findIndex(el => el.AlertId == self.EmailOptions[i]) != -1) { 
                                        alarmEmailList.push({
                                            state: true,
                                            val: +self.EmailOptions[i],
                                            title: ActualAlarmNames?.find(el => el.AlertId == self.EmailOptions[i])?.AlertName,
									    }) 

                                    } else {
										alarmEmailList.push({
											state: true,
											val: +self.EmailOptions[i],
											title: AlarmSolution.toLowerCase().indexOf('witi') !== -1 && self.EmailOptions[i] == 131072 ? 'Witi Alarm' : Protocol.Helper.getAletTypeName(self.EmailOptions[i]),
										})
									}
								}
								
								
								let redPush = 0;
								let redEmail = 0;
								var offlineOptions = {};
								
								if(self.PushOptions.indexOf('67108864') !== -1){
                                    redPush += 67108864;
                                    self.$setState({
                                        ShowOfflineBlock: true,
                                    });

                                    if (data && data.LiveAssetSettings && data.LiveAssetSettings?.OfflineHours) {
                                        offlineOptions = Protocol.Helper.getOfflineAlarmOptions(data.LiveAssetSettings?.OfflineHours);
                                    }else{
                                        offlineOptions = Protocol.Helper.getOfflineAlarmOptions();
                                    }
                                    
                                    if (data.AlarmOptions & 67108864) {
                                        self.$setState({
                                            OfflineState: false,
                                        });
                                    }else{
                                        self.$setState({
                                            OfflineState: true,
                                        });
                                    }
                                }

                                self.$setState({
                                    ShowAdditionalBlocks: !data.AssetType || data.AssetType && data.AssetType.toLowerCase() !== 'boat' && data.AssetType.toLowerCase() !== 'jetski',
                                });

							 
								if (data.AlarmListType == 2) {
									
									self.$setState({
										ShowIgnoreBetweenBlock: true,
									});

                                    if(self.PushOptions.indexOf('32') !== -1){
                                        redPush += 32;
                                        self.$setState({
                                            ShowOverspeedBlock: true,
                                        });

                                        if (data.AlarmOptions & 32) {
                                            self.$setState({
                                                OverspeedState: false,
                                            });
                                        }else{
                                            self.$setState({
                                                OverspeedState: true,
                                            });
                                        }
                                    }
								}else{
                                    offlineOptions = offlineOptions?.filter(el => +el.Value > 24)
                                }

								alarmList = alarmList.filter(el => el.val != 32 && el.val != 67108864 )
								alarmEmailList = alarmEmailList.filter(el => el.val != 32 && el.val != 67108864 )
								
								//if(AlarmSolution.toLowerCase().indexOf('witi') !== -1){
								//	alarmList = alarmList.map(el => el).filter(el => el.val == 8 || el.val == 1024 || el.val == 16 || el.val == 512 || el.val == 4 || el.val == 131072 );
								//	alarmEmailList = alarmEmailList.map(el => el).filter(el => el.val == 8 || el.val == 1024 || el.val == 16 || el.val == 512 || el.val == 4 || el.val == 131072 );
								//}else{
								//	alarmList = alarmList.map(el => el).filter(el => el.val == 65536 || el.val == 32768 || el.val == 1048576 || el.val == 131072 || el.val == 1024 || el.val == 8 || el.val == 16 || el.val == 128 || el.val == 512 || el.val == 4 || el.val == 2 || el.val == 256 || el.val == 33554432 || el.val == 2097152 || el.val == 16777216)
								//	alarmEmailList = alarmEmailList.map(el => el).filter(el => el.val == 8 || el.val == 1024 || el.val == 16 || el.val == 512 || el.val == 4 || el.val == 131072 || el.val == 1048576 )
								//}
								
							
								for (var i = alarmList.length - 1; i >= 0; i--) {
									redPush += alarmList[i].val;
									if (data.AlarmOptions & alarmList[i].val) {
										alarmList[i].state = false;
									}
								}
								for (let i = alarmEmailList.length - 1; i >= 0; i--) { 
									redEmail += alarmEmailList[i].val;
									if (data.AlarmEmailOptions & alarmEmailList[i].val) { 
										alarmEmailList[i].state = false;
									}
								}
								
								self.$setState({
									ALL_JUST_CUSTOM_PUSH_ALARMS_OFF: redPush,
									ALL_JUST_CUSTOM_EMAIL_ALARMS_OFF: redEmail,
									AlarmListType: data.AlarmListType,
									ShowAlarmList: true,
									Alarms: alarmList,
									AlarmsEmail: alarmEmailList,
									IgnoreBetweenState: !!(data && data.LiveAssetSettings && data.LiveAssetSettings.IsIgnore == 1),
									SpeedingMode: data && data.LiveAssetSettings && data.LiveAssetSettings.SpeedingMode ? data.LiveAssetSettings.SpeedingMode : 1
								});

								// if(data.LiveAssetSettings?.HolderContact){
								// 	let index = self.ContactList.findIndex((item) =>  item.Code === data.LiveAssetSettings?.HolderContact)
								// 	self.ContactList[ index === -1 ? 0 : index ].Selected = true
								// }
                                
								self.ContactPhoneList = self.ContactList.map(el => Object.assign({}, el, {Selected: false}))
								
                                let arrEmails = data.LiveAssetSettings?.CustomEmails?.split(',')
								let arrPhones = data.LiveAssetSettings?.CustomPhones ? data.LiveAssetSettings?.CustomPhones?.split(',') : ''
								/*let phoneList = []
								
								self.ContactList.forEach(function(el){
									phoneList.push(el) 
								})
								
								self.ContactPhoneList = phoneList*/
								
                                if(data.LiveAssetSettings?.CustomEmails){
                                    for (let i = arrEmails.length - 1; i >= 0; i--) {
                                        let index = self.ContactList.findIndex((item) =>  item.EMail === arrEmails[i])   
                                        self.ContactList[ index === -1 ? 0 : index ].Selected = true
                                    }
                                }
								
								//console.log('arrPhones', self.ContactPhoneList)
								
                                if(data.LiveAssetSettings?.CustomPhones){
                                    for (let i = arrPhones.length - 1; i >= 0; i--) {
                                        let index = self.ContactPhoneList.findIndex((item) =>  item.Mobile === arrPhones[i])             
                                        self.ContactPhoneList[ index === -1 ? 0 : index ].Selected = true
                                    }
                                }
								
								

                                self.$setState({
                                    OfflineOptions: offlineOptions,
                                    EmailsToSend: arrEmails,
                                    PhonesToSend: arrPhones
                                });

                                if (data.AlarmListType == 2) {
									self.$app.utils.nextFrame(() => {
                                        self.initIgnoreBetweenBlock(data.LiveAssetSettings);
									})
								}
								self.$app.utils.nextFrame(() => {
                                    self.initToggleAllAlarms(data.AlarmOptions);
                                });
								
								
							}else{
								self.$app.dialog.alert('Alarm settings not supported');
							}
						}
					});
					

				}
			},
			initIgnoreBetweenBlock: function(params = {}){
                let self = this;

                if (params.BeginTime) {
                    params.BeginTime = moment(params.BeginTime,'HH:mm').add(self.$app.data.UTCOFFSET,'minutes').format('HH:mm');
                }
                if (params.EndTime) {
                    params.EndTime = moment(params.EndTime,'HH:mm').add(self.$app.data.UTCOFFSET,'minutes').format('HH:mm');
                }

                let StartTimeValArray = params.BeginTime ? params.BeginTime.split(':') : [];
                let EndTimeInputArray = params.EndTime ? params.EndTime.split(':') : [];
                let ignoreBetweenStateEl = self.$el.find('[name="IgnoreBetweenState"]');
                let daysOfWeekEl = self.$el.find('.smart-select-days-of-week');
                let daysOfWeekArray = [
					{
						val: 0,
						name: LANGUAGE.COM_MSG38,
						displayAs: LANGUAGE.COM_MSG45,
						selected: false,
					},
					{
						val: 1,
						name: LANGUAGE.COM_MSG39,
						displayAs: LANGUAGE.COM_MSG46,
						selected: false,
					},
					{
						val: 2,
						name: LANGUAGE.COM_MSG40,
						displayAs: LANGUAGE.COM_MSG47,
						selected: false,
					},
					{
						val: 3,
						name: LANGUAGE.COM_MSG41,
						displayAs: LANGUAGE.COM_MSG48,
						selected: false,
					},
					{
						val: 4,
						name: LANGUAGE.COM_MSG42,
						displayAs: LANGUAGE.COM_MSG49,
						selected: false,
					},
					{
						val: 5,
						name: LANGUAGE.COM_MSG43,
						displayAs: LANGUAGE.COM_MSG50,
						selected: false,
					},
					{
						val: 6,
						name: LANGUAGE.COM_MSG44,
						displayAs: LANGUAGE.COM_MSG51,
						selected: false,
					},
				];

                if (!StartTimeValArray || !StartTimeValArray.length) {
                    StartTimeValArray = ['07', '00'];
                }
                if (!EndTimeInputArray || !EndTimeInputArray.length) {
                    EndTimeInputArray = ['18', '00'];
                }

                ignoreBetweenStateEl.on('change', function(){
                    self.$setState({
                        IgnoreBetweenState: this.checked
                    });
                });

                self.TimePickerStart = self.$app.picker.create({
                    inputEl: self.$el.find('[name="PickerStart"]'),
                    rotateEffect: true,
                    sheetPush: true,
                    value: StartTimeValArray,
                    cols: [
                        {
                            textAlign: 'center',
                            values: (function() {
                                let arr = [];
                                for (let i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
                                return arr;
                            })(),
                        },
                        // Divider
                        {
                            divider: true,
                            content: ':'
                        },
                        // Minutes
                        {
                            textAlign: 'center',
                            values: (function() {
                                let arr = [];
                                for (let i = 0; i <= 59; i++) { arr.push(i < 10 ? '0' + i : i); }
                                return arr;
                            })(),
                        }
                    ],
                    formatValue: function(values, displayValues) {
                        return values[0] + ':' + values[1];
                    },
                });

                self.TimePickerEnd = self.$app.picker.create({
                    inputEl: self.$el.find('[name="PickerEnd"]'),
                    rotateEffect: true,
                    sheetPush: true,
                    value: EndTimeInputArray,
                    cols: [
                        {
                            textAlign: 'center',
                            values: (function() {
                                let arr = [];
                                for (let i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
                                return arr;
                            })(),
                        },
                        // Divider
                        {
                            divider: true,
                            content: ':'
                        },
                        // Minutes
                        {
                            textAlign: 'center',
                            values: (function() {
                                let arr = [];
                                for (let i = 0; i <= 59; i++) { arr.push(i < 10 ? '0' + i : i); }
                                return arr;
                            })(),
                        }
                    ],
                    formatValue: function(values, displayValues) {
                        return values[0] + ':' + values[1];
                    },
                });

                if (params.Weeks) {
                    let selectedDays = params.Weeks.split(',');
                    if (selectedDays && selectedDays.length) {
                        for (let i = selectedDays.length - 1; i >= 0; i--) {
                            let dayIndex = daysOfWeekArray.findIndex(x => x.val === parseInt(selectedDays[i],10));
                            if (dayIndex !== -1) {
                                daysOfWeekArray[dayIndex].selected = true;
                            }
                        }
                    }
                }

                self.$setState({
                    DaysOfWeek: daysOfWeekArray,
                });

                self.$app.utils.nextFrame(()=>{
                    self.DaysOfWeekSelect = self.$app.smartSelect.create({
                        el: daysOfWeekEl,
                        openIn: 'sheet',
                        formColorTheme: 'green',
                        sheetPush: 'true'
                    });
                });

            },
			initToggleAllAlarms: function(alarmOptions = 0){
                let self = this;
                let checkboxes = self.$el.find('.checkbox-alarm-push');
                
                self.ToggleAllAlarms = self.$app.toggle.create({
                    el: self.$el.find('.toggle-all-alarm'),
                    on: {
                        change: function () {
                            for (let i = checkboxes.length - 1; i >= 0; i--) {
                                checkboxes[i].checked = this.checked;
                             
                            }

                        }
                    }
                });
				
				let checkboxesEmail = self.$el.find('.checkbox-alarm-email');

				self.ToggleEmailAllAlarms = self.$app.toggle.create({
					el: self.$el.find('.toggle-email-all-alarm'),
					on: {
						change: function () {
							for (let i = checkboxesEmail.length - 1; i >= 0; i--) {
								checkboxesEmail[i].checked = this.checked;
								
							}

						}
					}
				});
				
            },
			saveAlarmOptions: function(data, url){
				var self = this;

				self.$app.dialog.progress();
				self.$app.request.post(url, data, function (result, xhr, status) {
					
					if (result.MajorCode == '000') {
						if (result.MinorCode == '1006') {
							self.$app.methods.customDialogNoCredit();
						}else{
						
                            self.$app.methods.customNotification({title: 'Success!', text: 'Alarm data changed successfully.'});
							self.updateAlarmOptions(data);
							self.$app.methods.checkBalance();

							if (leftView.router.history && leftView.router.history.length && leftView.router.history[leftView.router.history.length-2].indexOf('/asset-select/multiple/asset-alarm/') != -1) {
								leftView.router.back('/panel-left/', {force:true});
							}else{
								leftView.router.back();
							}
						}
					}else if(result.MajorCode == '100' && result.MinorCode == '1006'){
						self.$app.methods.customDialogNoCredit();
					}else if(result.MajorCode == '100' && result.MinorCode == '1003'){
						app.methods.customDialog({title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051});
					}else{
						self.$app.methods.customNotification({
							hold: 5000,
							title: LANGUAGE.COM_MSG16
						});
						self.$app.methods.checkBalance();
					}
					self.$app.utils.nextFrame(() => {
						self.$app.dialog.close();
					});

				},
				function (xhr, status) {
					self.$app.utils.nextFrame(() => {
						self.$app.dialog.close();
					});

					self.$app.dialog.alert('Error occured at Save AlarmOpitons');
				},
				'json');
			},
			updateAlarmOptions: function(params){
				var self = this;
				var IMEIList = params.imeis.split(',');
				var assetList = self.$app.methods.getFromStorage('assetList');

				if (IMEIList.length) {
					$.each(IMEIList, function(index, value){
						assetList[value].AlarmOptions = params.alarmOptions;
						if (params.SpeedingMode == 2) {
							assetList[value].MaxSpeed = params.MaxSpeed;
						}
					});
				}

				self.$app.methods.setAssetList({objects: assetList});
			},
			showPromptSetOverspeedVal: function(OverspeedTypesEl){
				let self = this;

				var text = `
					<div class="custom-modal-text">${ LANGUAGE.PROMPT_MSG096 }(${Protocol.Helper.getSpeedUnit(self.MaxSpeedUnit)}):</div>
					<div class="dialog-input-field item-input">
						<div class="item-input-wrap">
							<input type="text" class="dialog-input" name="MaxSpeed" value="${ self.MaxSpeed }">
						</div>
					</div>
				`;

				app.dialog.create({
				    title: '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="'+ app.data.AppDetails.logoModal +'" alt=""/></div>',
				    text: text,
				    buttons: [
				    	{
				    		text: LANGUAGE.COM_MSG01,
				    		cssClass: 'color-black',
                            onClick: function(dialog){
                            	if (OverspeedTypesEl) {
                            		for (var i = OverspeedTypesEl.length - 1; i >= 0; i--) {
                            			if (OverspeedTypesEl[i].value == '1') {
		                                    OverspeedTypesEl[i].checked = true;
		                                    break;
		                                }
                            		}
                            	}
                            }
				    	},
				      	{
                            text: LANGUAGE.COM_MSG12,
                            cssClass: 'color-red',
                            onClick: function(dialog){
                            	let MaxSpeed = dialog.$el.find('input[name="MaxSpeed"]').val();

                                self.$setState({
                                	MaxSpeed: MaxSpeed ? MaxSpeed : 1
                                })

                            }
                        },
				    ],
				}).open();
			}

		},

		on: {
			pageInit: function (e, page) {
				var self = this;
				var form = page.$el.find('[name = "AssetAlarmForm"]');
				
				let ALL_ALARMS_OFF = 2147483647;
				console.log(self.OverspeedState)
				self.getAlarmOptions();
				
				form.on('change', '.disablingController',function(e){
					var parent = this.closest('.list');
					var elements = $$(parent).find('.disablingObj');

					for (var i = elements.length - 1; i >= 0; i--) {
						if(this.checked){
							$$(elements[i]).removeClass('disabled');
						}else{
							$$(elements[i]).addClass('disabled');
						}
					}
				});

				form.on('change', 'input[name="overspeed-type"]', function(e){
					if (e.target.value == 2) {
						self.showPromptSetOverspeedVal(form.find('input[name="overspeed-type"]'));
					}
				});

				form.on('change', 'input[name="checkbox-alarm"][value="67108864"]', function(e){
					var offlineOptionsEl = page.$el.find('input[name="offline-option"]');
					for (var i = offlineOptionsEl.length - 1; i >= 0; i--) {
						offlineOptionsEl[i].checked = this.checked;
					}
					self.$setState({
						OfflineState: this.checked
					})
				});

				form.on('change', 'input[name="offline-option"]', function(e){
					var offlineOptionsEl = page.$el.find('input[name="offline-option"]');
					var oneSelected = false;
					for (var i = offlineOptionsEl.length - 1; i >= 0; i--) {
						if (offlineOptionsEl[i].checked) {
							oneSelected = true;
						}
					}
					if (!oneSelected) {
						this.checked = true;
						self.$app.methods.customNotification({title: LANGUAGE.ASSET_ALARM_MSG32, text: LANGUAGE.PROMPT_MSG097});
					}
				});
				
                form.on('submit', function(e){
                    e.preventDefault();
				 
					
					let ALL_EXPT_CUSTOM_PUSH_ALARMS_OFF = ALL_ALARMS_OFF - self.ALL_JUST_CUSTOM_PUSH_ALARMS_OFF;
					let ALL_EXPT_CUSTOM_EMAIL_ALARMS_OFF = ALL_ALARMS_OFF - self.ALL_JUST_CUSTOM_EMAIL_ALARMS_OFF;
				 
                    let checkboxes = page.$el.find('[name = "checkbox-alarm"]');
                    let offlineOptions = page.$el.find('[name = "offline-option"]');
					
					let checkboxesEmail = page.$el.find('[name = "checkbox-alarm-email"]');
					let checkedHolderContact = page.$el.find('[name="HolderContact"]').val();
					//let choosenEmailsToSend = page.$el.find('[name = "EmailsToSend"]');
					//let choosenPhonesToSend = page.$el.find('[name = "PhonesToSend"]');
					let choosenEmailsArr = page.$el.find('[name = "EmailsToSend"]').val();  
					let emailsToSend  = choosenEmailsArr.join(',')
					let choosenPhonesArr = page.$el.find('[name = "PhonesToSend"]').val();  
					let phonesToSend  = choosenPhonesArr != 'undefined' ? choosenPhonesArr?.join(',') : ''
					
					
                    let url = API_URL.SET_ALERT_CONFIG;
                    let data = {
                        MinorToken: self.$app.data.MinorToken,
                        MajorToken: self.$app.data.MajorToken,
                        imeis: self.IMEI,
						IsEmailNotification: self.EmailNotificationsState,
						IsPushNotification: self.PushNotificationsState,
						HolderContact: self.$app.data.MinorToken,   //checkedHolderContact,
						//CustomEmails: choosenEmailsToSend.val(),
						CustomEmails: emailsToSend,
						CustomPhones: phonesToSend,
                        alarmOptions: ALL_EXPT_CUSTOM_PUSH_ALARMS_OFF,
						alarmEmailOptions: ALL_EXPT_CUSTOM_EMAIL_ALARMS_OFF,
						AlertTypes: ALL_EXPT_CUSTOM_PUSH_ALARMS_OFF,
						EmailAlertTypes: ALL_EXPT_CUSTOM_EMAIL_ALARMS_OFF,
						IsIgnore: 0,
						Weeks: '',
						DateFrom: '00:00',
                        DateTo: '23:00',
						MaxSpeed: self.MaxSpeed
                    };

			 
                    for (let i = checkboxes.length - 1; i >= 0; i--) {
                        if (!checkboxes[i].checked) {
						 
                            data.alarmOptions += parseInt(checkboxes[i].value, 10);
                        }
                    }

					 
					for (let i = checkboxesEmail.length - 1; i >= 0; i--) {
						if (!checkboxesEmail[i].checked) {
							data.alarmEmailOptions += parseInt(checkboxesEmail[i].value, 10);
						}
					}
					
					data.AlertTypes = data.alarmOptions;
					data.EmailAlertTypes = data.alarmEmailOptions;
				 
					
					if (!(data.AlertTypes & 67108864)) {
                        data.OfflineHours = '';
                        for (let i = offlineOptions.length - 1; i >= 0; i--) {
                            if (offlineOptions[i].checked) {
                                data.OfflineHours += offlineOptions[i].value + ',';
                            }
                        }
                        if (data.OfflineHours) {
                            data.OfflineHours = data.OfflineHours.slice(0,-1);
                        }
                    }

                    self.AlarmListType = parseInt(self.AlarmListType,10);
				 
		 
                    switch (self.AlarmListType){
                        case 2:
                            data.AlertTypes = data.alarmOptions;
                            data.IsIgnore = self.IgnoreBetweenState ? 1 : 0;
                            data.Weeks = self.DaysOfWeekSelect.$selectEl?.val().toString();
                            data.DateFrom = moment(page.$el.find('[name="PickerStart"]').val(), 'HH:mm').utc().format('HH:mm');
                            data.DateTo = moment(page.$el.find('[name="PickerEnd"]').val(), 'HH:mm').utc().format('HH:mm');
							
							if (!(data.AlertTypes & 32) && page.$el.find('input[name="overspeed-type"]:checked').val()) {
                                data.SpeedingMode = parseInt(page.$el.find('input[name="overspeed-type"]:checked').val(),10);
								
                                    data.MaxSpeed = Protocol.Helper.getSpeedValueInKM(self.MaxSpeedUnit, self.MaxSpeed);// self.MaxSpeed;
                                
                            }
                        break;
                    }
				 
                    self.saveAlarmOptions(data, url);

                    return false;
                })
			
			},
			pageBeforeRemove: function () {
				let self = this;

				if (self.ToggleAllAlarms) {
					app.toggle.destroy(self.ToggleAllAlarms);
				}

				if (self.DaysOfWeekSelect) {
					self.DaysOfWeekSelect.destroy();
				}

				if (self.TimePickerStart) {
					self.TimePickerStart.destroy();
				}

				if (self.TimePickerEnd) {
					self.TimePickerEnd.destroy();
				}
			},

		}
	};
</script>