
<!--suppress JSAnnotator -->
<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
		<div class="page " data-name="asset-activations"> <!-- 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">Activation</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="AssetActivationForm" class="page-content">
                <input type="hidden" name="DeviceTypeCode" value="">
				<input type="submit" id="submit-form" class="display-none" />
				<div class="block-title text-color-darkgray">Multiple asset activation</div>
				<div class="block">
					<p>In this list you can change the name of each asset</p>
				</div>
				
				{{#if isLoaded}}
				<div class="list ">
                    <ul>
                        <li>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-admin-users"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">Customer Login</div>
                                    <div class="item-input-wrap">
                                        <input type="text" name="LoginName" placeholder="Customer Login" value="{{LoginName}}" maxlength="200" required validate>
                                    </div>
                                </div>
                            </div>
                        </li>
						<li>
                            <a class="item-link smart-select smart-select-init custom-smart-select {{#unless SolutionTypes}}disabled{{/unless}}" data-open-in="popover" data-close-on-select="true" >
                                <select name="SolutionType" required>
                                    {{#SolutionTypes}}
                                        {{#js_if "this.Code != 'Boat_watch'"}}
                                        <option value="{{Code}}" >{{Name}}</option>   <!-- {{#js_if '@root.SolutionTypeDefault == this.Code '}} selected {{/js_if}} -->
                                        {{/js_if}}
                                    {{/SolutionTypes}}
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <!-- <i class="f7-icons icon-service-plan"></i>   -->
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.ASSET_ACTIVATION_MSG01}}</div>
                                    </div>
                                </div>
                            </a>
                        </li>
                        <li>
                            <a class="item-link smart-select smart-select-init custom-smart-select {{#unless ServicePlans}}disabled{{/unless}}" data-open-in="popover" data-close-on-select="true">
                                <select name="ServicePlan" required>
                                    {{#ServicePlans}}
                                    <option value="{{Code}}" >{{Name}}</option>
                                    {{/ServicePlans}}
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <i class="f7-icons icon-service-plan"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.ASSET_ACTIVATION_MSG00}}</div>
                                    </div>
                                </div>
                            </a>
                        </li>
					</ul>
				</div>
				{{else}}
				<div key="ActivationListPreloader" 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 = {
				solutionTypeEl: {},
				AssetsForActivation: [],
				isLoaded: false,
				
				isWatch: false,
				activationListType: 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: 'Select all Push notifications / Unselect all', 
				},
				TurnOnAllEmail: {
					state: false,
					title: 'Select all Email notifications / Unselect all',
				},
				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: {
			getDeviceTypeCode: function(data){
                var self = this;
				
                app.preloader.show();
                self.$app.request.post(API_URL.GET_ACTIVATION_VERIFY, data, function (result, xhr, status) {
                    app.preloader.hide();
                    if (result && result.Data && result.Data.DEVICETYPE) {
                        $$('input[name="DeviceTypeCode"]').val(result.Data.DEVICETYPE);
                        self.getActivationAdditionalData({ProductCode: result.Data.DEVICETYPE, DealerToken: self.$app.data.MajorToken});//IMEI: data.IMEI, 
                    }else{
                        self.$app.dialog.alert('Something wrong');
                    }
                },
                function (xhr, status) {
                    app.preloader.hide();
                    self.$app.dialog.alert('Error occured');
                },
                'json');
            },
			getActivationAdditionalData: function(params){
                var self = this;
                app.preloader.show();
                self.$app.request.post(API_URL.GET_ACTIVATION_SSP, params, function (result, xhr, status) {
                    app.preloader.hide();

                    if (result.MajorCode == '000') {
                        if (result.Data && result.Data.ServiceProfiles && result.Data.ServiceProfiles.length && result.Data.Solutions && result.Data.Solutions.length) {
                            if (params.ProductCode && params.SolutionCode) {
                                self.$setState({
                                    ServicePlans: result.Data.ServiceProfiles,
                                });
                                $$('[name="ServicePlan"]').change();
                            }else if(params.ProductCode){
                                 self.$setState({
                                    SolutionTypes: result.Data.Solutions,
                                });
								$$('[name="SolutionType"]').on('change', function(){
									self.getActivationAdditionalData({
										SolutionCode: this.value,
										ProductCode: $$('input[name="DeviceTypeCode"]').val(),
										DealerToken: self.$app.data.MajorToken,
									});
								});
                                $$('[name="SolutionType"]').change();
                            }
                        }else{
                            self.$app.dialog.alert('There is no Service Plans for this product type');
                        }
                    }else{
                        self.$app.dialog.alert('Something wrong');
                    }
                },
                function (xhr, status) {
                    self.$app.preloader.hide();
                    self.$app.dialog.alert('Error occured');
                },
                'json');
            },
			getActivationOptions: function(){
				let self = this;

				if (!self.$route.params || !self.$route.params.imei ) {
					console.log('There is no params or imei param');
				}else{
					self.loadActivationList();
				}
			},
			loadActivationList: function(data){
				let self = this;
				let imeiArr = self.IMEI.split(',');
				let assetList = self.$app.methods.getFromStorage('assetList');
				let activationList = []
				
				for(a in assetList){
					if(imeiArr.includes(a)){
						console.log(assetList[a])
						activationList.push(assetList[a])
					}
				}
				
				self.getDeviceTypeCode({IMEI: activationList[0].IMEI, DealerToken: self.$app.data.MajorToken}); 
				
				$$(self.solutionTypeEl).on('change', function(){
                    self.getActivationAdditionalData({
                        SolutionCode: this.value,
                        ProductCode: $$('input[name="DeviceTypeCode"]').val(),
                        IMEI: activationList[0].IMEI,
                        DealerToken: self.$app.data.MajorToken,
                    });
                });
				
				self.$setState({
					isLoaded: true,
					AssetsForActivation: activationList
				})
				
			},
			saveActivationOptions: 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.updateActivationOptions(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-activation/') != -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');
			},
			updateActivationOptions: 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});
			},
		},

		on: {
			pageInit: function (e, page) {
				var self = this;
				var form = page.$el.find('[name = "AssetActivationForm"]');
                var servicePlanEl = page.$el.find('select[name = "ServicePlan"]');
                self.solutionTypeEl = page.$el.find('select[name = "SolutionType"]');
					
				self.getActivationOptions();
				
				form.on('submit', function(e){
                    e.preventDefault();
					
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: "https://newapi.quiktrak.co/Quiktrak/V2/Customer/GetList?MajorToken=00000000-0000-0000-0000-000000000000&MinorToken=00000000-0000-0000-0000-000000000000&rows=1&page=1&sort=Name&order=asc&LoginName="+ page.$el.find('input[name="LoginName"]').val(),
						success: function (result) {
							console.log(JSON.parse(result).rows[0])
							if(JSON.parse(result).rows.length){
								for (let i = self.AssetsForActivation.length - 1; i >= 0; i--) {
									var Data = {
									  "IMEI": self.AssetsForActivation[0].IMEI,
									  "Name": self.AssetsForActivation[0].IMEI,
									  "Describe7": null,
									  "ServiceProfile":  page.$el.find('select[name = "ServicePlan"]').val(),
									  "CustomerToken": JSON.parse(result).rows[0].Code,
									  "DealerToken": self.$app.data.MajorToken,
									  "UserToken": JSON.parse(result).rows[0].UserCode,
									  "CustomVal5": null,
									  "CustomVal7": null,
									  "CustomField1": null,
									  "CustomField4": null,
									  //"AutoSuspend": "1",
									  "Solution": page.$el.find('select[name = "SolutionType"]').val(),
									  "Features": 0,
									  "AssetType": null,
									  "DeviceInstalled": "yes",
									  "Phone": null
									}
									
									console.log(Data);
									
									$.ajax({
										type: "POST",
										url: "https://newapi.quiktrak.co/Common/v1/Activation/Activation",
										dataType: 'json',
										data: Data,
										async: true,
										cache: false,
										beforeSend: function() {
										
										},
										success: function(data) {
											
										},
										error: function(XMLHttpRequest, textStatus, errorThrown) {
											console.log(XMLHttpRequest);
											console.log(textStatus);
											console.log(errorThrown);
										}
									});
									
									self.$app.methods.customNotification({title: 'Success!', text: 'Activation done.'});
					
									if (leftView.router.history && leftView.router.history.length && leftView.router.history[leftView.router.history.length-2].indexOf('/asset-select/multiple/asset-activation/') != -1) {
										leftView.router.back('/panel-left/', {force:true});
									}else{
										leftView.router.back();
									}
								}
							}
						},
						complete: function() {
						},
						dataType: "html"
					});
                    //let checkboxes = page.$el.find('[name = "asset-activations"]');
                 	/*
					{
					  "IMEI": "0000019175353631",
					  "Name": "0000019175353631",
					  "Describe1": null,
					  "Describe2": null,
					  "Describe3": null,
					  "Describe4": null,
					  "Describe7": "Rf3yak057kt072739",
					  "ServiceProfile": "5f87b4fc-d25b-4",
					  "CustomerToken": "4c11c1c8-b5db-4edc-a161-d7a26369f610",
					  "DealerToken": "2087d174-71cf-43a5-922f-5f6e8fdaa8be",
					  "UserToken": "d4902783-d2ca-4de4-876d-c3e5f016124e",
					  "Description": null,
					  "CustomVal1": null,
					  "CustomVal2": null,
					  "CustomVal3": null,
					  "CustomVal4": null,
					  "CustomVal5": "Annual",
					  "CustomVal6": null,
					  "CustomVal7": "al3rtgps.co",
					  "AddressState": null,
					  "AccountName": null,
					  "PaymentType": null,
					  "CustomField1": "AL3RT GPS",
					  "CustomField2": null,
					  "CustomField3": null,
					  "CustomField4": "tonyt@al3rtgps.com",
					  "CustomField5": null,
					  "AutoSuspend": "1",
					  "Registration": null,
					  "Solution": "LongLifePortable",
					  "Features": 0,
					  "AssetType": "Bike",
					  "Notes": null,
					  "ActionType": null,
					  "GroupCode": null,
					  "InstallLocation": null,
					  "InitMileage": null,
					  "DeviceInstalled": "yes",
					  "InitAccHours": null,
					  "ServiceIntervalCode": null,
					  "Input1Type": null,
					  "Input2Type": null,
					  "Input1Name": null,
					  "Input2Name": null,
					  "Input1Mask": 0,
					  "Input2Mask": 0,
					  "LowerPower": null,
					  "DisconnectPower": null,
					  "IgnitionPower": null,
					  "Vin": null,
					  "Phone": "3524081135"
					}*/
					
					//let assetList = self.$app.methods.getFromStorage('assetList');
					console.log(self.AssetsForActivation)
					
					
					
						
					
                    /*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
                    };

                    self.saveActivationOptions(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>