<!--suppress JSAnnotator -->
<template>
  <!-- Page, data-name contains page name which can be used in callbacks -->
  <div class="page " data-name="contact-list">
    <!-- 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.DRIVER_FATIGUE_MSG00}} </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="DriverFatigueForm" 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.DRIVER_FATIGUE_MSG00}}</div>
      <div class="block">
        <p class=""> {{@global.LANGUAGE.DRIVER_FATIGUE_MSG01}}</p>
      </div>

      <div class="list no-hairline-bottom">
        <ul>
          <li class="item-content">
            <div class="item-inner">
              <div class="item-title">{{@global.LANGUAGE.DRIVER_FATIGUE_MSG02}}</div>
              <div class="item-after">
                <label class="toggle toggle-fatigue-form">
                  <input type="checkbox" name="FatigueFormState" {{#if FatigueFormState}}checked="checked" {{/if}}>
                  <span class="toggle-icon"></span>
                </label>
              </div>
            </div>
          </li>
		  <li class="item-content">
            <div class="item-inner">
              <div class="item-title">{{@global.LANGUAGE.DRIVER_FATIGUE_MSG07}}</div>
              <div class="item-after">
                <label class="toggle toggle-fatigue-form">
                  <input type="checkbox" name="IgnoreIdleState" {{#if IgnoreIdleState}}checked="checked" {{/if}}>
                  <span class="toggle-icon"></span>
                </label>
              </div>
            </div>
          </li>
          <li>
            <div class="item-content item-input {{#unless FatigueFormState}} 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.DRIVER_FATIGUE_MSG03}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="HoursPer" value="{{HoursPer}}" readonly="readonly" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
          <li>
            <div class="item-content item-input {{#unless FatigueFormState}} 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.DRIVER_FATIGUE_MSG04}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="HoursСontinuous" value="{{HoursCon}}" readonly="readonly" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
          <li>
            <div class="item-content item-input {{#unless FatigueFormState}} 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.DRIVER_FATIGUE_MSG05}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="MandatoryStop" value="{{HoursMan}}" readonly="readonly" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </li>
		  <li>
			<a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-type {{#unless FatigueFormState}} disabled {{/unless}}"
				data-open-in="popover" data-close-on-select="true">
				<select name="SetBy">
					<option value="driver">Driver</option>
					<option value="asset" selected>Asset</option><!-- {{#if selected}} selected {{/if}}-->
				</select>
				<div class="item-content item-input">
					<div class="item-media text-color-lightgray">
						<i class="f7-icons icon-header-reports"></i>
					</div>
					<div class="item-inner">
						<div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG28}}</div>
					</div>
				</div>
			</a>
          </li>		  
        </ul>
      </div>



    </form>






  </div>
</template>


<script>
  // script must return component object
  return {
    data: function () {
      var self = this;
      var ret = {}
        ret.RulesId = 0
        ret.HoursPer = 0
        ret.HoursCon = 0
        ret.HoursMan = 0
		
        ret.TimeHoursPer = false
        ret.TimeMandatoryStop = false
        ret.TimeHoursСontinuous = false
        ret.FatigueFormState = false
		ret.IgnoreIdleState = false
      

      return ret
    },
    methods: {	    
      initDriverFatigueForm: function (params = {}) {
        let self = this;
				
		self.$app.request.get(API_URL.GET_RULES, { MajorToken: self.$app.data.MajorToken, MinorToken: self.$app.data.MinorToken }, function (result, xhr, status) {
          self.$app.preloader.hide();

          if (result && result.MajorCode == '000') {
           console.log('Fatigue: ',result)
		   
		    self.$setState({
				RulesId: result.Data.RulesId,
				HoursPer: result?.Data?.DayHours.toString().replace('.', ':'),
				HoursCon: result?.Data?.ContinueWorkHours.toString().replace('.', ':'),
				HoursMan: result?.Data?.MandatoryStop.toString().replace('.', ':'),
				FatigueFormState: result?.Data?.IsActive,
				IgnoreIdleState:  result?.Data?.IgnoreIdle
            });
			}
        },
          function (xhr, status) {
            self.$app.preloader.hide();
            self.$app.dialog.alert('Error occured at Get Rule ');
          },
          'json');			
		
		
        let ignoreBetweenStateEl = self.$el.find('[name="FatigueFormState"]');
        ignoreBetweenStateEl.on('change', function () {
          self.$setState({
            FatigueFormState: this.checked
          });
        });
		
		let ignoreIdleStateEl = self.$el.find('[name="IgnoreIdleState"]');
        ignoreIdleStateEl.on('change', function () {
          self.$setState({
            IgnoreIdleState: this.checked
          });
        });


        if (params.HoursPer) {
          params.HoursPer = moment(params.HoursPer, 'HH:mm').add(app.data.UTCOFFSET, 'minutes').format('HH:mm');
        }
        if (params.HoursСontinuous) {
          params.HoursСontinuous = moment(params.HoursСontinuous, 'HH:mm').add(app.data.UTCOFFSET, 'minutes').format('HH:mm');
        }
        if (params.MandatoryStop) {
          params.MandatoryStop = moment(params.MandatoryStop, 'HH:mm').add(app.data.UTCOFFSET, 'minutes').format('HH:mm');
        }

        let HoursPerValArray = params.HoursPer ? params.HoursPer.split(':') : [];
        let HoursСontinuousValArray = params.HoursСontinuous ? params.HoursСontinuous.split(':') : [];
        let MandatoryStopValArray = params.MandatoryStop ? params.MandatoryStop.split(':') : [];

        if (!HoursPerValArray || !HoursPerValArray.length) {
          HoursPerValArray = ['07', '00'];
        }
        if (!HoursСontinuousValArray || !HoursСontinuousValArray.length) {
          HoursСontinuousValArray = ['18', '00'];
        }
        if (!MandatoryStopValArray || !MandatoryStopValArray.length) {
          MandatoryStopValArray = ['22', '00'];
        }


        self.TimeHoursPer = app.picker.create({
          inputEl: self.$el.find('[name="HoursPer"]'),
          rotateEffect: true,
          value: HoursPerValArray,
          cols: [
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
                return arr;
              })(),
            },
            // Divider
            {
              divider: true,
              content: ':'
            },
            // Minutes
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var 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.TimeHoursСontinuous = app.picker.create({
          inputEl: self.$el.find('[name="HoursСontinuous"]'),
          rotateEffect: true,
          value: HoursСontinuousValArray,
          cols: [
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
                return arr;
              })(),
            },
            // Divider
            {
              divider: true,
              content: ':'
            },
            // Minutes
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var 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.TimeMandatoryStop = app.picker.create({
          inputEl: self.$el.find('[name="MandatoryStop"]'),
          rotateEffect: true,
          value: MandatoryStopValArray,
          cols: [
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
                return arr;
              })(),
            },
            // Divider
            {
              divider: true,
              content: ':'
            },
            // Minutes
            {
              textAlign: 'center',
              values: (function () {
                var arr = [];
                for (var 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];
          },
        });
      },
    },

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

        self.initDriverFatigueForm()
		
		var userInfo = self.$app.methods.getFromStorage('userInfo');
		var form = page.$el.find('[name = "DriverFatigueForm"]');
		form.on('submit', function (e) {
			e.preventDefault();
			var data = {
				DayHours: page.$el.find('[name="HoursPer"]').val().replace(':', '.'),
				ContinueWorkHours: page.$el.find('[name="HoursСontinuous"]').val().replace(':', '.'),
				MandatoryStop:  page.$el.find('[name="MandatoryStop"]').val().replace(':', '.'),
				Type: "ASSET",
				IsActive: self.FatigueFormState,
				IgnoreIdle: self.IgnoreIdleState,
				CustomerCode: userInfo.MajorToken,
			};
			
			if(self.RulesId) {
				data.RulesId = self.RulesId;
			}
			
			var url = API_URL.SET_RULES;
			self.$app.request.post(url, 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');
			})
			//self.getReportData(data, url);
		})

      },
      pageAfterOut: function () {
        /*var toggleAll = self.$app.toggle.get('.toggle-all-alarm');
        console.log(toggleAll);*/
      },
      pageBeforeIn: function (e, page) {
        var self = this;
      },
    }
  };
</script>