<!--suppress JSAnnotator -->
<template>
  <!-- Page, data-name contains page name which can be used in callbacks -->
  <div class="page " data-name="trip-ban">
    <!-- 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"> Trip Ban </div>
        <div class="right">
          <!-- <a href="#" class="link">
            <i class="f7-icons icon-notification"></i>
          </a>-->
        </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="TripBanForm" 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"> Trip Ban</div>
      <div class="block">
        <p class="">In this section, you set the time period during which your assets should not be used. In the event of movement, you will receive notifications, and you can also set the automatic shutdown of the asset.</p>
      </div>

      <div class="list no-hairline-bottom">
        <ul>
						  <li class="item-content">
							<div class="item-inner">
							  <div class="item-title">On / Off</div>
							  <div class="item-after">
								<label class="toggle toggle-fatigue-form">
								  <input type="checkbox" name="ImmobState" {{#if ImmobState}}checked="checked" {{/if}}>
								  <span class="toggle-icon"></span>
								</label>
							  </div>
							</div>
						  </li>
		  
							<li key="assetListTripban-key">
								{{#if selectAllAssets}}
								<a class="item-link smart-select smart-select-init custom-smart-select smartSelectAssets"
									data-open-in="popup" data-searchbar="true"
									data-searchbar-placeholder="{{@global.LANGUAGE.COM_MSG02}}"
									data-append-searchbar-not-found="{{@global.LANGUAGE.PROMPT_MSG008}}"
									data-page-title="{{@global.LANGUAGE.ASSET_GROUPS_MSG08}}">
									<select name="Assets" multiple required validate>
										{{#AssetList}}
										<option value="{{Id}}" selected>{{Name}}</option>
										{{/AssetList}}
									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons icon-name"></i>
										</div>
										<div class="item-inner">
											<div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG09}}</div>
										</div>
									</div>
								</a>
								{{else}}

								<a class="item-link smart-select smart-select-init custom-smart-select smartSelectAssets"
									data-open-in="popup" data-searchbar="true"
									data-searchbar-placeholder="{{@global.LANGUAGE.COM_MSG02}}"
									data-append-searchbar-not-found="{{@global.LANGUAGE.PROMPT_MSG008}}"
									data-page-title="{{@global.LANGUAGE.ASSET_GROUPS_MSG08}}">
									<select name="Assets" multiple >
										{{#AssetList}}
										<option value="{{Id}}" {{#if Selected}} selected {{/if}}>{{Name}}</option>
										{{/AssetList}}
									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons icon-name"></i>
										</div>
										<div class="item-inner">
											<div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG09}}</div>
										</div>
										
									</div>
								</a>

							{{/if}}
							</li>
							<li>
								<label class="item-checkbox item-content">
									<input type="checkbox" name="selectAllAssets" id="selectAllAssets" {{#if selectAllAssets}}
										checked {{/if}} />
									<div class="item-media text-color-lightgray">
									</div>
									<div class="item-inner">
										<div class="item-title">Select all by default</div>
										<div class="item-after">
											<i class="icon icon-checkbox"></i>
										</div>
									</div>
								</label>
							</li>
			  
			    			<li>
								<div class="item-content item-input ">
									<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" />
												</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" />
												</div>
											</div>
										</div>
									</div>
								</div>
							</li>
							<li>
								<a class="item-link smart-select custom-smart-select smart-select-days-of-week " 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">Days</div>
										</div>
									</div>
								</a>
							</li>
							
							<li class="item-content">
							<div class="item-inner">
							  <div class="item-title">Auto Immobilise</div>
							  <div class="item-after">
								<label class="toggle toggle-fatigue-form">
								  <input type="checkbox" name="AutoImmobState" {{#if AutoImmobState}}checked="checked" {{/if}}>
								  <span class="toggle-icon"></span>
								</label>
							  </div>
							</div>
						  </li>
						   
        </ul>
      </div>



    </form>






  </div>
</template>


<script>
  // script must return component object
  return {
    data: function () {
      var self = this;
      var ret = {}
	  
	
	  let assetList = Object.values(self.$app.methods.getFromStorage('assetList'));
		
        ret.TimeHoursPer = false
        ret.TimeMandatoryStop = false
        ret.TimeHoursСontinuous = false
        ret.ImmobState = false
		ret.AutoImmobState = false
		ret.AssetList = assetList
		
		ret.selectAllAssets = false
		
		let Assets =  []
		if (self.$route.query.assetlist) {
			Assets = self.$route.query.assetlist.split(',')
		}
						
						if (Assets.length) {
							for (let i = 0; i < Assets.length; i++) {
								if(assetList.findIndex(el => el.Id === Assets[i]) != -1){
								
									assetList[assetList.findIndex(el => el.Id === Assets[i])].Selected = true; 
								}
							}
						}
				
				return ret
		
		
    },
    methods: {	    
      initTripBanForm: function (params = {}) {
        let self = this;
				
		
		  self.$app.request.get(API_URL.GET_RULES_TRIPBAN, { MajorToken: self.$app.data.MajorToken, MinorToken: self.$app.data.MinorToken }, function (result, xhr, status) {
          self.$app.preloader.hide();
		  
			let p = {}
			  p.BeginTime =  '00:00';
			  p.EndTime =  '23:00';
			  p.Weeks = '';
			  
          if (result && result.MajorCode == '000') {
		   
		    self.$setState({
				AutoImmobState: result?.Data?.IsAutoImmobilize,
				ImmobState: result?.Data?.IsImmobilize,
            });
			
			p.BeginTime =  result?.Data?.TimeFrom;
			  p.EndTime =  result?.Data?.TimeTo;
			  p.Weeks = result?.Data?.Days;
			
			 }
			  
				self.$app.utils.nextFrame(() => {
				   self.initIgnoreBetweenBlock(p);
				})
        },
          function (xhr, status) {
            self.$app.preloader.hide();
            self.$app.dialog.alert('Error occured at Get Rule ');
			
      return ret
          },
          'json');
		
		
        let ImmobStateEl = self.$el.find('[name="ImmobState"]');
        ImmobStateEl.on('change', function () {
          self.$setState({
            ImmobState: this.checked
          });
        });
		
		let AutoImmobStateEl = self.$el.find('[name="AutoImmobState"]');
        AutoImmobStateEl.on('change', function () {
          self.$setState({
            AutoImmobState: this.checked
          });
        });
      },
	  
			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 AutoImmobStateEl = self.$el.find('[name="AutoImmobState"]');
                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'];
                }

                AutoImmobStateEl.on('change', function(){
                    self.$setState({
                        AutoImmobState: 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'
                    });
                });

            },
    },

    on: {
      pageInit: function (e, page) {
        var self = this;

        self.initTripBanForm()
		
		var userInfo = self.$app.methods.getFromStorage('userInfo');
		var form = page.$el.find('[name = "TripBanForm"]');
		form.on('submit', function (e) {
			e.preventDefault();
			var data = {
				isImmob: self.ImmobState,
				MajorToken: userInfo.MajorToken,
				MinorToken: userInfo.MinorToken,
				Assets: page.$el.find('[name = "Assets"]')?.val().join(','), //['3135343132','35303A363B']
                Days: self.DaysOfWeekSelect.$selectEl.val().toString(),
				TimeFrom: moment(page.$el.find('[name="PickerStart"]').val(), 'HH:mm').utc().format('HH:mm'),
				TimeTo: moment(page.$el.find('[name="PickerEnd"]').val(), 'HH:mm').utc().format('HH:mm'),
				isAutoImmob: self.AutoImmobState
			};
			//console.log(self.$app.utils.serializeObject(data))
		
			
			var url = API_URL.SET_RULES_TRIPBAN;
			self.$app.request.post(url + '?MajorToken='+data.MajorToken+'&Assets='+data.Assets+'&TimeFrom='+data.TimeFrom+'&TimeTo='+data.TimeTo+'&Days='+data.Days+'&IsAutoImmobilize='+data.isAutoImmob+'&IsImmobilize='+data.isImmob+'&MinorToken='+data.MinorToken, data, function (result, xhr, status) {
				self.$app.preloader.hide();
				if (result) {
					self.$app.dialog.alert('Rule saved');
				}
			},function(e){
				self.$app.dialog.alert('Something wrong');
			})
		})
		
		
				$$(page.$el).on('change', '[name = "selectAllAssets"]', function (el) {
                    self.$setState({
                        selectAllAssets: document.getElementById("selectAllAssets").checked,
                    });
                })

      },
      pageAfterOut: function () {
      },
      pageBeforeIn: function (e, page) {
        var self = this;
      },
	  
			pageBeforeRemove: function () {
				let self = this;


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

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

				if (self.TimePickerEnd) {
					self.TimePickerEnd.destroy();
				}
			},
    }
  };
</script>