<!--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-bg"></div>
            <div class="navbar-inner">
                <div class="left">
                    {{#if Tabs}}
                    <a href="/" class="link icon-only " >
                        <i class="if-not-ios f7-icons icon-header-arrow-back"></i>
                        <i class="if-ios icon icon-back"></i>
                    </a>
                    {{else}}
                    <a href="#" class="link icon-only back">
                        <i class="if-not-ios f7-icons icon-header-arrow-back"></i>
                        <i class="if-ios icon icon-back"></i>
                    </a>
                    {{/if}}
                </div>
                <div class="title sliding">{{Name}}</div>
                <div class="right">
                    {{#if ShowAlarmList}}
					
                    {{#if AllPermissions}} 
                    <label for="submit-form-alarm" class="link icon-only">
                        <i class="f7-icons icon-header-apply"></i>
                    </label>
                    {{/if}}
					{{/if}}
                </div>

            </div>
        </div>
        {{#if Tabs}}
        <div class="toolbar tabbar toolbar-top">
            <div class="toolbar-inner">
                <a href="/asset-status/?imei={{IMEI}}&tabs=true" class="tab-link ">{{@global.LANGUAGE.ASSET_STATUS_LIVE_MSG00}}</a>
                <a href="#" class="tab-link tab-link-active">{{@global.LANGUAGE.ASSET_ALARM_MSG00}}</a>
                <a href="/asset-playback/?imei={{IMEI}}" class="tab-link">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG00}}</a>
                <a href="/asset-track/?imei={{IMEI}}&tabs=true" class="tab-link">{{@global.LANGUAGE.ASSET_TRACK_MSG00}}</a>
            </div>
        </div>
        {{/if}}

        <!-- Scrollable page content-->
        <form name="AssetAlarmForm" class="page-content">
            <input type="submit" id="submit-form-alarm" class="display-none" />
            {{#if ProtectAsset}}
            <div class="block-title tooltip-init text-transform-uppercase text-color-red" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG108}}">{{@global.LANGUAGE.PROMPT_MSG109}} <span class="badge color-lightblue">?</span></div>
            {{/if}}

            {{#if ShowIgnoreBetweenBlock}}
            <div key="IgnoreBetween" class="list no-hairline-bottom no-hairline-top no-margin-top">
                <ul>
                    <li class="item-content">
                        <div class="item-inner">
                            <div class="item-title text-transform-uppercase tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG036}}">{{@global.LANGUAGE.COM_MSG051}} <span class="badge color-lightblue">?</span></div>
                            <div class="item-after">
                                <label class="toggle toggle-ignore-between {{#if ReadOnly}} disabled{{/if}} color-green">
                                    <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}}{{#if ReadOnly}} disabled{{/if}}">
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-live-engine-hours"></i>
                            </div>
                            <div class="item-inner">
                                <div class="row width-100">
                                    <div class="col">
                                        <div class="item-title item-label ">{{@global.LANGUAGE.COM_MSG053}}</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_MSG054}}</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 smart-select-days-of-week {{#if ReadOnly}} disabled {{/if}} {{#unless IgnoreBetweenState}} disabled {{/unless}}" >
                            <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">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-live-date"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">{{@global.LANGUAGE.COM_MSG052}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                </ul>
            </div>
            {{/if}}


            {{#if ShowAlarmList}}
                <div key="AlarmList" class="list no-hairline-bottom no-margin-top">
                    <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 {{#if ReadOnly}} disabled {{/if}} color-green">
                                        <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 {{#if ReadOnly}} disabled {{/if}} color-green">
                                <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 {{#if ReadOnly}} disabled {{/if}} color-green">
                                        <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 {{#if ReadOnly}} disabled {{/if}} item-content color-green">
                                <input type="checkbox" class="checkbox-alarm-email"  name="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">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="HolderContact" >
                                    {{#ContactList}}
                                    <option
                                    value="{{Code}}"
                                    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 icon-live-email"></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" class="{{#if ReadOnly}} disabled {{/if}}" placeholder="You can add additional emails" value="{{EmailsToSend}}">
                                    </div>
                                    
                                    
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>

                {{#if ShowOfflineBlock}}
				<div key="Offline" class="list no-hairline-bottom ">
                    <ul>
                        <li class="item-content">
                            <div class="item-inner">
                                <div class="item-title text-transform-uppercase tooltip-init"
                                    data-tooltip="{{@global.LANGUAGE.PROMPT_MSG033}}">{{@global.LANGUAGE.ASSET_ALARM_MSG32}}
                                    <span class="badge color-lightblue">?</span></div>
                                <div class="item-after">
                                    <label class="toggle {{#if ReadOnly}} disabled {{/if}} color-green">
                                        <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 {{#if ReadOnly}} disabled {{/if}} item-content color-green {{#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}}
                
                <div key="Overspeed" class="list no-hairline-bottom">
                    <ul>
                        <li class="item-content">
                            <div class="item-inner">
                                <div class="item-title text-transform-uppercase tooltip-init " data-tooltip="{{@global.LANGUAGE.PROMPT_MSG034}}<br>{{@global.LANGUAGE.PROMPT_MSG035}}">{{@global.LANGUAGE.ASSET_ALARM_MSG23}} <span class="badge color-lightblue">?</span></div>
                                <div class="item-after">
                                    <label class="toggle {{#if ReadOnly}} disabled {{/if}} color-green">
                                        <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 {{#if ReadOnly}} disabled {{/if}} item-content color-green 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}}</div>
                                </div>
                            </label>
                        </li>

                        <li>
                            <label class="item-radio {{#if ReadOnly}} disabled {{/if}} item-content color-green 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}}</div>
                                </div>
                            </label>
                        </li>
                    </ul>
                </div>
                {{/if}}
            {{else}}
            <!--<div key="AlarmListPreloader" class="block block-strong text-align-center">
                <div class="preloader color-red"></div>
            </div>-->
            <div key="skeleton-ignore-between" class="list no-hairline-bottom no-hairline-top no-margin-top">
                <ul>
                    <li class="item-content skeleton-text skeleton-effect-blink">
                        <div class="item-inner">
                            <div class="item-title text-transform-uppercase ">title ignore between</div>
                            <div class="item-after">
                                toggle
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content item-input skeleton-text skeleton-effect-blink">
                            <div class="item-media text-color-lightgray">
                                <div class="skeleton-block" style="width: 32px; height: 32px;"></div>
                            </div>
                            <div class="item-inner">
                                <div class="row width-100">
                                    <div class="col">
                                        <div class="item-title item-label ">from</div>
                                        <div class="item-input-wrap">
                                            item input
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="item-title item-label ">from</div>
                                        <div class="item-input-wrap">
                                            item input
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-link skeleton-text skeleton-effect-blink" >
                            <div class="item-content">
                                <div class="item-media text-color-lightgray">
                                    <div class="skeleton-block" style="width: 32px; height: 32px;"></div>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">selected days</div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
            <div key="skeleton-alarm-list" class="list no-hairline-bottom no-margin-top">
                <ul>
                    <li class="item-content skeleton-text skeleton-effect-blink">
                        <div class="item-inner">
                            <div class="item-title text-transform-uppercase">turn all title here</div>
                            <div class="item-after">
                                toggle
                            </div>
                        </div>
                    </li>
                    {{#each '12345'}}
                    <li class="item-content skeleton-text skeleton-effect-blink">
                        <div class="item-media text-color-lightgray">
                            <div class="skeleton-block" style="width: 32px; height: 32px;"></div>
                        </div>
                        <div class="item-inner">
                            <div class="item-title">alarm name</div>
                        </div>
                    </li>
                    {{/each}}
                </ul>
            </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.query.imei);
            let index = IMEI.indexOf(',');
            let tabsFlag = self.$route.query.tabs;
			
			let contactList = self.$app.methods.getFromStorage('contactList');
            contactList = self.$app.methods.sortContactList(contactList);
			
            let ret = {
                Tabs: !!tabsFlag,
                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: 'Select all Push notifications / Unselect all', //LANGUAGE.ASSET_ALARM_MSG26,
				},
				TurnOnAllEmail: {
					state: false,
					title: 'Select all Email notifications / Unselect all',
				},
                IMEI: IMEI,
                Name: index === -1 ? assetList[IMEI].Name : LANGUAGE.ASSET_ALARM_MSG00,
                MaxSpeed: index === -1 ? assetList[IMEI].MaxSpeed : 80,
                isPositiveInputSupported: index === -1 ? (parseInt(assetList[IMEI]._FIELD_INT2) & Protocol.FeaturesEnum.PositiveInput) > 0 : (parseInt(assetList[IMEI.split(',')[0]]._FIELD_INT2) & Protocol.FeaturesEnum.PositiveInput) > 0,

                ShowAdditionalBlocks: false,
                IgnoreBetweenState: false,
                TimePickerStart: false,
                TimePickerEnd: false,
                DaysOfWeek: [],
                DaysOfWeekSelect: false,
				EmailNotificationsState: true,
				PushNotificationsState: true,
                ContactList: contactList,
                NoContacts: contactList.length <= 1,
                ReadOnly:  ReadOnly,
                AllPermissions: AllPermissions,
                ShowOverspeedBlock: false,
                ShowOfflineBlock: false
            };

            return ret;
        },
        methods: {
            getAlarmOptions: function(){
                let self = this;

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

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

                if (imeiArr.length > 1) {
                    //let AlarmListType = 3;
						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.loadAlarmList({
                        AlarmListType: self.AlarmListType,
                        AssetType: assetList[imeiArr[0]] ? assetList[imeiArr[0]].AssetType : '',
						AlarmEmailOptions: 2147483647,
                        AlarmOptions: 2147483647,
                    });
                }else{

                    let asset = assetList[self.$route.query.imei];
					//let AlarmListType = 3;
                    if (asset) { 
                        if (/*asset.SolutionType && asset.SolutionType.toLowerCase() === 'track' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'watch' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'boat_watch' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'wititrack' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'witiqprotect' ||*/
								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
							}
                    
						let data = {
                                MajorToken: self.$app.data.MajorToken,
                                MinorToken: self.$app.data.MinorToken,
                                IMEI: self.$route.query.imei
                            };
                            self.$app.request.promise.post(API_URL.GET_ALERT_CONFIG, data, 'json')
                                .then(function (result) {
                                    if (result.data && result.data.MajorCode === '000') {
                                        self.loadAlarmList({
                                            AlarmListType: self.AlarmListType, //live
                                            AssetType: asset.AssetType,
                                            AlarmOptions: result.data.Data.AlertTypes,
											AlarmEmailOptions: result.data.Data.EmailAlertTypes,

                                            LiveAssetSettings: result.data.Data,
                                        });
                                    } else {
                                        self.loadAlarmList({
                                            AlarmListType: self.AlarmListType,    //live
                                            AssetType: asset.AssetType,
                                            AlarmOptions: asset.AlarmOptions,
											AlarmEmailOptions: asset.AlarmOptions,
                                        });
                                    }
                                })
                                .catch(function (err) {
                                    console.log(err);
                                    if (err && err.status === 404){
                                        self.$app.dialog.alert(LANGUAGE.PROMPT_MSG002);
                                    }else{
                                        self.$app.dialog.alert(LANGUAGE.PROMPT_MSG003);
                                    }
                                });
					
					}
                }


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

					let AlarmSolution = assetList[imeiArr[0]] ? assetList[imeiArr[0]].SolutionType : ''
					let AlarmProduct = assetList[imeiArr[0]] ? assetList[imeiArr[0]].PRDTName : ''
					console.log(AlarmSolution, ' ',AlarmProduct)
					
					
					let dataAlOp = {
                        SolutionCode: AlarmSolution,
                        ProductName: AlarmProduct,
                    };
					
					let urlAlOp = 'https://testapi.quiktrak.co/QuikTrak/V1/User/GetAlarmOptionsBySolution'; //?SolutionCode='+AlarmSolution+'&ProductName='+AlarmProduct
					self.$app.request.promise.get(urlAlOp, dataAlOp, 'json')
                    .then(function (result) {
							let alarmList = []
							let alarmEmailList = []

								result = result.data
								if (result?.MajorCode == '000') {
								self.$setState({
									EmailOptions:  result?.Data?.Email,
									PushOptions:  result?.Data?.Push,
								})

								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++){
									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++){
									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)
                                }
								
								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.$setState({
                                    OfflineOptions: offlineOptions,
                                });

                                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');
							}
					 })
                    .catch(function (err) {
                        console.log(err);
                        self.$app.utils.nextFrame(() => {
                            self.$app.dialog.close();
                            if (err && err.status === 404){
                                self.$app.dialog.alert(LANGUAGE.PROMPT_MSG002);
                            }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 = Protocol.Helper.getDaysOffWeekArray();

                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;
                            })(),
                        }
                    ],
                    /*renderToolbar: function () {
                        return '';
                    },*/
                    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;
                            })(),
                        }
                    ],
                    /*renderToolbar: function () {
                        return '';
                    },*/
                    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;
                                /*if (checkboxes[i].value === '32' || checkboxes[i].value === '67108864') {
                                    $$(checkboxes[i]).change();
                                }*/
                            }

                        }
                    }
                });
                /*alarmOptions = parseInt(alarmOptions,10);
                if (alarmOptions === 0) {
                    if (!self.ToggleAllAlarms.checked) {
                        self.ToggleAllAlarms.toggle();
                    }
                }*/
				
				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;
								/*if (checkboxesEmail[i].value === '32' || checkboxesEmail[i].value === '67108864') {
									$$(checkboxesEmail[i]).change();
								}*/
							}

						}
					}
				});
				/*alarmEmailOptions = parseInt(alarmEmailOptions, 10);
				if (alarmEmailOptions === 0) {
					if (!self.ToggleEmailAllAlarms.checked) {
						self.ToggleEmailAllAlarms.toggle();
					}
				}*/
				
            },

            saveAlarmOptions: function(data, url){
                let self = this;
                console.log(data)
                self.$app.dialog.progress(LANGUAGE.COM_MSG004,'red');
                self.$app.request.promise.post(url, data, 'json')
                    .then(function (result) {
                        if (result.data && result.data.MajorCode === '000') {

                            if (result.data.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 (mainView.router.history && mainView.router.history.length && mainView.router.history[mainView.router.history.length-2].indexOf('asset-select/?type=multiple&nextPage=asset-alarm') !== -1) {
                                    mainView.router.back('/', {force:true});
                                }else{
                                    mainView.router.back();
                                }
                            }

                        }else if(result.data.MajorCode === '100' && result.data.MinorCode === '1006'){
                            self.$app.methods.customDialogNoCredit();
                        }else if(result.data.MajorCode === '100' && result.data.MinorCode === '1003'){
                            self.$app.methods.customDialog({title: LANGUAGE.PROMPT_MSG039, text: LANGUAGE.PROMPT_MSG040});
                        }else{
                            self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.data.MajorCode}<br>MinorCode: ${result.data.MinorCode}<br>${result.data.Data}`);
                            self.$app.methods.checkBalance();
                        }
                        self.$app.utils.nextFrame(() => {
                            self.$app.dialog.close();
                        });
                    })
                    .catch(function (err) {
                        console.log(err);
                        self.$app.utils.nextFrame(() => {
                            self.$app.dialog.close();
                            if (err && err.status === 404){
                                self.$app.dialog.alert(LANGUAGE.PROMPT_MSG002);
                            }else{
                                self.$app.dialog.alert(LANGUAGE.PROMPT_MSG003);
                            }
                        });
                    });
            },
            updateAlarmOptions: function(params){
                let self = this;
                let IMEIList = params.imeis.split(',');
                let 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;

                let text = `
					<div class="custom-modal-text">${ LANGUAGE.PROMPT_MSG032 }:</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>
				`;

                self.$app.dialog.create({
                    title: '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="'+ self.$app.data.logoBlack +'" alt=""/></div>',
                    text: text,
                    buttons: [
                        {
                            text: LANGUAGE.COM_MSG001,
                            cssClass: 'color-black',
                            onClick: function(dialog){
                                if (OverspeedTypesEl) {
                                    for (let i = OverspeedTypesEl.length - 1; i >= 0; i--) {
                                        if (OverspeedTypesEl[i].value === '1') {
                                            OverspeedTypesEl[i].checked = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        },
                        {
                            text: LANGUAGE.COM_MSG055,
                            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) {
                let self = this;
                let form = page.$el.find('[name = "AssetAlarmForm"]');

				let ALL_ALARMS_OFF = 2147483647;
				
                self.getAlarmOptions();

                form.on('change', '.disablingController',function(e){
                    let parent = this.closest('.list');
                    let elements = $$(parent).find('.disablingObj');

                    for (let 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){
                    let offlineOptionsEl = page.$el.find('input[name="offline-option"]');
                    for (let 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){
                    let offlineOptionsEl = page.$el.find('input[name="offline-option"]');
                    let oneSelected = false;
                    for (let 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_MSG031});
                    }
                });

                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 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: checkedHolderContact,
						CustomEmails: choosenEmailsToSend.val(),
                        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',
                    };
					
                    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);
                                if (data.SpeedingMode === 2) {
                                    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) {
                    self.$app.toggle.destroy(self.ToggleAllAlarms);
                }

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

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

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

            },

        }
    };
</script>