<!--suppress JSAnnotator -->
<template>
  <div class="page" data-name="create-order">
    {{#unless isHideCloseBtn}}
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left"></div>
        <div class="title">
             {{PageTitle}}  
        </div>
        <div class="right">

          {{#unless isHideCloseBtn}}
          <a href="#" class="link popup-close" data-popup=".popup-fullscreen-createorder">
            <i class="f7-icons">close</i>
          </a>
          {{/unless}}
        </div>
      </div>
    </div>
    {{/unless}}


    <div style=" width: 310px;" class="bottom-section-wrapper toolbar-bottom  bg-color-white {{#if DeleteButton}} toolbar-size-2 {{/if}}">
      <div class="display-flex flex-direction-column  bottom-section-button-wrapper    justify-content-space-evenly">
        <div class="row">
          <label for="submit-form-new-order" class="col button button-fill color-green elevation-2"
            tabindex="0">{{@global.LANGUAGE.COM_MSG06}}</label>
        </div>
        {{#if DeleteButton}}
        <div class="row">
          <a href="#" class="col button button-fill color-red elevation-2 deleteOrder"
            tabindex="0">{{@global.LANGUAGE.COM_MSG30}}</a>
        </div>
        {{/if}}
      </div>
    
    </div>

    
    <div class="page-content bg-color-lightgray  ">



      <div class="content-wrapper with-sidebar  sidebar-opened ">


        <form name="NewOrderForm"  {{#if DeleteButton}} style="padding-bottom: 80px;" {{/if}} class="page-content no-padding-top    content-sidebar left">
          

          <input type="submit" id="submit-form-new-order" class="display-none" />
       
          <div class="list padding-bottom no-margin no-hairlines ">
            <ul>

              <li class="item-content">
                <div class="item-inner size-16"><b>{{@global.LANGUAGE.JOB_DESPATCH_MSG11}}</b> </div>

              </li>
              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"><i class="f7-icons icon-all "></i></div>
                <div class="item-inner">
                  <div class="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG33 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="{{@global.LANGUAGE.TASK_PANEL_MSG01 }}" name="OrderName"
                      value="{{OrderName}}" maxlength="200" required validate>
                  </div>
                </div>
              </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-label"></div>
                    <a class="item-link smart-select smart-select-init smart-select-template custom-smart-select" data-open-in="popover"
                      data-close-on-select="true">
                      <select name="TemplateInput">
                        <option value="0">None selected</option>

                        {{#TemplateList}}
                        <option value="{{ID}}" {{#if selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{TemplateName}}
                        </option>
                        {{/TemplateList}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG34 }}
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-notification "></i>

                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label"></div>
                    <a class="item-link smart-select smart-select-init  smart-select-typejob custom-smart-select" data-open-in="popover"
                      data-close-on-select="true">
                      <select name="TypeJobInput">
                        {{#TypeJobList}}

                        <option value="{{Value}}" {{#if Selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{Name}}
                        </option>
                        {{/TypeJobList}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG09 }}
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>
              <li 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="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG35 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="" name="JobDuration" value="{{JobDuration}}" maxlength="200"
                      required validate>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content item-input plannedArrivalWrapper" data-input-name="PlannedArrival">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-calendar"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG36}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="PlannedArrival" class="PlannedArrival" placeholder=""
                        value="{{PlannedArrival}}" maxlength="200" readonly>
                    </div>
                  </div>
                </div>
              </li>
            <!--  <li class="item-content">
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">

                  </div>

                  <div>
                    <label class="item-checkbox display-flex  align-items-center">

                      <div style="white-space: inherit;" class="item-title">{{@global.LANGUAGE.JOB_DESPATCH_MSG37}}
                      </div>
                      <div class="item-after">
                        <i class="icon icon-checkbox"></i>
                      </div>

                      <input type="checkbox" name="selectAllDay" id="selectAllDay" {{#if isAllDay}} checked {{/if}} />
                      <div class="item-media text-color-lightgray">
                      </div>

                    </label>

                  </div>





                </div>
                 <label class="item-checkbox item-content">
                  <input type="checkbox" name="selectAllDay" id="selectAllDay" />
                  <div class="item-media text-color-lightgray">
                  </div>
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.JOB_DESPATCH_MSG37}}</div>
                    <div class="item-after">
                      <i class="icon icon-checkbox"></i>
                    </div>
                  </div>
                </label> 

              </li>-->
              <li>
                <div class="item-content item-input estimatedArrivalWrapper" data-input-name="EstimatedArrival">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-calendar"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG38}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="EstimatedArrival" class="EstimatedArrival" placeholder=""
                        value="{{EstimatedArrival}}" maxlength="200" readonly>
                    </div>
                  </div>
                </div>
              </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-label"></div>
                    <a class="item-link smart-select smart-select-init custom-smart-select" data-open-in="popover"
                      data-close-on-select="true">
                      <select name="ToleranceInput">
                        {{#ToleranceList}}
                        <option value="{{Value}}" {{#if Selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{Name}}</option>
                        {{/ToleranceList}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG39}}
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>
              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"> </div>
                <div class="item-inner">
                  <div class="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG40 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="" name="TimeWindow" value="{{TimeWindow}}" maxlength="200">
                  </div>
                </div>
              </li>
              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"><i class="f7-icons icon-report-overview "></i></div>
                <div class="item-inner">
                  <div class="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG10}}</div>
                  <div class="item-input-wrap ">
                    <textarea name="Note" rows="1" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG10}}" maxlength="400"
                      value="">{{Note}}</textarea>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-all "></i>

                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label"></div>
                    <a class="item-link smart-select smart-select-init custom-smart-select" data-open-in="popover"
                      data-close-on-select="true">
                      <select name="LinkedOrder">
                       
                        {{#LinkedOrderTypes}}
                       
                        <option value="{{Value}}" {{#if Selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{Name}}
                          </option>
                        {{/LinkedOrderTypes}} 
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG41 }}
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </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-label"></div>
                    <a class="item-link smart-select smart-select-typejob2 smart-select-init custom-smart-select" data-open-in="popover"
                      data-close-on-select="true">
                      <select name="NextOrder">
                        {{#Orders}}

                        <option value="{{OrderID}}" {{#if Selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{OrderName}}
                        </option>
                        {{/Orders}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label">Choose
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>
              <li class="item-content">
                <div class="item-inner size-16"><b>Contact</b> </div>

              </li>
              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"><i class="f7-icons icon-profile-name "></i></div>
                <div class="item-inner">
                  <div class="item-title item-label"> Name </div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="" name="ContactName" value="{{ContactName}}" maxlength="200"
                      required validate>
                  </div>
                </div>
              </li>
              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"><i class="f7-icons icon-mobile "></i></div>
                <div class="item-inner">
                  <div class="item-title item-label"> Phone</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="" name="ContactPhone" value="{{ContactPhone}}" maxlength="200"
                      required validate>
                  </div>
                </div>
              </li>
              <li class="overflow-visible address-textarea">
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">

                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG06}} <i
                        class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init"
                        data-tooltip="{{@global.LANGUAGE.PROMPT_MSG0103}}"></i></div>
                    <div class="item-input-wrap">
                      <textarea name="GeoAddress" placeholder="{{@global.LANGUAGE.GEOFENCES_MSG06}}" maxlength="400"
                        value="">{{Address}}</textarea>
                      <span class="input-search-button ">
                        <i class="f7-icons icon-search ripple text-color-red ripple-color-red"></i>
                      </span>
                    </div>
                  </div>
                </div>
              </li>
              <li {{#if DeleteButton}} style="padding-bottom: 80px;" {{/if}} >
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-address"></i>
                  </div>
                  <div class="item-inner">

                    <a class="item-link smart-select-poi2 smart-select smart-select-init custom-smart-select"
                      data-open-in="popover" data-close-on-select="true">
                      <select name="POISelect">
                        <option value="0">None selected</option>
                        {{#PoiList}}
                        <option value="{{Code}}">
                          {{Name}}</option>
                        {{/PoiList}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label">{{@global.LANGUAGE.JOB_DESPATCH_MSG16}}<i
                            class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init"
                            data-tooltip="{{@global.LANGUAGE.JOB_DESPATCH_MSG17}}"></i>
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>
             




            </ul>
          </div>



        </form>


        <div class="content">
          <div id="orderMap" class="order-map">
          </div>
        </div>
      </div>


    </div>
  </div>


</template>

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

      var today = moment().format('MMMM DD YYYY, HH:mm');
      var currentTime = moment().format('HH:mm');

      var templateList = self.$app.methods.getFromStorage('templateList');
      var taskList = self.$app.methods.getFromStorage('taskList');
      var poiList = self.$app.methods.getFromStorage('POIList')



      var geofenceList = Protocol.Helper.getGeofenceList();
      var timePeriodList = Protocol.Helper.getTimePeriodList();
      var typeJobList = Protocol.Helper.getTypeJobList();
      var toleranceList = Protocol.Helper.getToleranceList();
      var linkedOrderTypes = Protocol.Helper.getLinkedOrderType();
      var order = null;
      var orders = []

      
      if(self.$route.query.code) {
   
        let taskIndex = taskList.findIndex(x => x.Task.Code == self.$route.query.code);
        if (taskIndex != -1) {
          orders = taskList[taskIndex].Orders
        }



        if(self.$route.query.id) {
          let orderIndex = orders.findIndex(x => x.OrderID == self.$route.query.id);
        
          if (orderIndex != -1) {
            order = orders[orderIndex]
            orders.splice(orderIndex, 1);
          }
 
          //
          let jobIndex = typeJobList.findIndex(x => x.Value == order.JobType);
          if (jobIndex != -1) {
            typeJobList[jobIndex].Selected = true;
          }
          let linkedOrderIndex = linkedOrderTypes.findIndex(x => x.Value == order.LinkedOrder);
          if (linkedOrderIndex != -1) {
            linkedOrderTypes[linkedOrderIndex].Selected = true;
          }
          let nextOrderIndex = orders.findIndex(x => x.OrderID == order.NextOrderId);
          if (nextOrderIndex != -1) {
            orders[nextOrderIndex].Selected = true;
          }
          let toleranceIndex = toleranceList.findIndex(x => x.Value == order.Tolarance);
          if (toleranceIndex != -1) {
            toleranceList[toleranceIndex].Selected = true;
          }
          //
         
          Protocol.Helper.getAddressByGeocoder({ lat: order.StartLat, lng: order.StartLng }, function (address) {
            ret.Address =  address
          });
          ret.PageTitle = 'Edit Order'
          ret.DeleteButton = true

          } else {
            ret.PageTitle = LANGUAGE.JOB_DESPATCH_MSG32
            ret.DeleteButton = false
          }

        }

      
    
      
      ret.OrderName = order ? order.OrderName : ''; 
      ret.Note = order ? order.Note : ''; 
      ret.ContactName = order ? order.CustomerName : ''; 
      ret.ContactPhone = order ? order.CustomerContact : ''; 
      ret.JobDuration = order ? order.Duration : ''; 
      ret.TimeWindow = order ? order.CustomerTimeWindow : ''; 
      ret.PlannedArrival = order ? order.PlannedArrival : today;
      ret.EstimatedArrival = order ? order.EstimatedArrival : today
      ret.ToleranceList = toleranceList
      ret.MapOrder = false;
      ret.TemplateList = templateList;
      ret.TimePeriodList = timePeriodList;
      ret.TypeJobList = typeJobList;
      ret.DriverList = [];
      ret.PoiList = poiList;
      ret.TaskCode = self.$route.query.code
      ret.DriverCode = self.$route.query.driverCode
      ret.LinkedOrderTypes = linkedOrderTypes
      ret.Orders = orders

   

      return ret;
    },
    methods: {
      
      saveOrder: function (data, url) {
        var self = this;

        var userInfo = self.$app.methods.getFromStorage('userInfo');
        var taskList = self.$app.methods.getFromStorage('taskList');
        let task = null

        let taskIndex = taskList.findIndex(x => x.Task.Code == self.TaskCode);
        if (taskIndex != -1) {
          task = taskList[taskIndex]
        }

        self.$app.request.post(url, data, function (result, xhr, status) {
          if (result && result.MajorCode == '000') {

            self.$app.methods.getTaskList(self.$app.data.MajorToken)

          	self.$app.preloader.show(); 
              self.$app.utils.nextTick(() => {
                self.$app.preloader.hide();
                self.$app.popup.close('.popup-fullscreen-createorder')
                createtaskView.router.navigate({
                        name: 'create-task',
                        query: {
                              code: self.TaskCode,
                              name: task.Task.TaskName,
                              driver: task.Task.DriverCode
                        },
                    });

              },1000);
         
          } else {
            self.$app.dialog.alert('Something wrong');
          }
        },
          function (xhr, status) {
            // self.$app.preloader.hide();
            self.$app.dialog.alert('Error occured at Add New  Order  ');
          },
          'json');


         
      },

      deleteOrder(id){
        let self = this;
        let url = API_URL.DELETE_ORDER + '?OrderId=' + id;

        var taskList = self.$app.methods.getFromStorage('taskList');
        let task = null

        let taskIndex = taskList.findIndex(x => x.Task.Code == self.TaskCode);
        if (taskIndex != -1) {
          task = taskList[taskIndex]
        }
        self.$app.preloader.show();   
        self.$app.request.post(url, function (result, xhr, status) {
          if (result && result.MajorCode == '000') {
           
              self.$app.methods.getTaskList(self.$app.data.MajorToken)

           

                self.$app.utils.nextTick(() => {
                  self.$app.preloader.hide();
                  self.$app.popup.close('.popup-fullscreen-createorder')
                  createtaskView.router.navigate({
                          name: 'create-task',
                          query: {
                                code: self.TaskCode,
                                name: task.Task.TaskName,
                                driver: task.Task.DriverCode
                          },
                      });
                  self.$app.methods.customNotification({ text: LANGUAGE.JOB_DESPATCH_MSG45 });
                },1000);

              

    
          } else {
            self.$app.dialog.alert('Something wrong');
          }
        },
          function (xhr, status) {
            // self.$app.preloader.hide();
            self.$app.dialog.alert('Error occured at Delete  Order  ');
          },
          'json');

         

      }

    },

    on: {
      pageMounted: function () {
        let self = this;
 
    
      },
      pageInit: function (e, page) {
        let self = this;

        var form = page.$el.find('[name = "NewOrderForm"]');
        var deleteButtonEl = page.$el.find('.deleteOrder');
        var taskList = self.$app.methods.getFromStorage('taskList');


        var plannedArrivalEl = page.$el.find('input[name="PlannedArrival"]');
        var datepickerFormat = 'DD.MM  HH:mm';
        var plannedArrivalWrapper = page.$el.find('.plannedArrivalWrapper');

        var estimatedArrivalEl = page.$el.find('input[name="EstimatedArrival"]');
        var timepickerFormat = 'DD.MM HH:mm';
        var estimatedArrivalWrapper = page.$el.find('.estimatedArrivalWrapper');


        var estimatedArrivalPicker = new MaterialDatetimePicker({
          el: estimatedArrivalEl[0],
          format: datepickerFormat,
          openedBy: 'click',
        });
        estimatedArrivalWrapper.on('click', function () {
          estimatedArrivalPicker.open();
        });

        var plannedArrivalPicker = new MaterialDatetimePicker({
          el: plannedArrivalEl[0],
          format: datepickerFormat,
          openedBy: 'click',
        });
        plannedArrivalWrapper.on('click', function () {
          plannedArrivalPicker.open();
        });


        deleteButtonEl.on('click', function () {
          self.deleteOrder(self.$route.query.id)
        })

    


        $$('.popup-fullscreen-createorder').on('popup:open', function(popup) {
         
          $$(document).on("smartselect:close", ".smart-select-template", e => {
         let checkedTemplateID = e.srcElement.f7SmartSelect.$selectEl[0].value
         let template
         
      
          $$(".smart-select-template select option").forEach((el, index) => {     
              if($$(el).val() !== '0')  {
              
                template = self.TemplateList.find(item => item.ID == checkedTemplateID)
              }
            })

          if(template !== undefined) {    
            let jobTypeIndex = self.TypeJobList.findIndex(x => x.Value == template.JobType);
          
            if (jobTypeIndex != -1) {
              self.TypeJobList[jobTypeIndex].Selected = true;
              $('.smart-select-typejob .item-after').text(self.TypeJobList[jobTypeIndex].Name);
            }

              self.$setState({
                ContactName: template.ContactName,
                ContactPhone: template.ContactPhone,
                Note: template.Note
              });       
              
          }  
      
        });

       
        });

       



        let searchAddressButtonEl = page.$el.find('.input-search-button');


        self.MapOrder = Protocol.Helper.createMap({ target: 'orderMap', latLng: [38.530015, -101.649213], zoom: 4 });


        searchAddressButtonEl.on('click', function (e) {
          let $GeoAddress = $$(this).siblings('[name="GeoAddress"]');
          let GeoAddressVal = $GeoAddress.val();
          if (!GeoAddressVal || GeoAddressVal.length < 3 || GeoAddressVal === $GeoAddress.data('prev-val')) {
            return;
          }

          let $parent = $$($GeoAddress.parent());
          let resultContainer = $parent.find('.results');

          if (!resultContainer.length) {
            $parent.append('<div class="results find-address-results"></div>');
            resultContainer = $parent.find('.results');
          }

          $GeoAddress.data('prev-val', GeoAddressVal);
          self.$app.progressbar.show();
          MapProvider
            .search({ query: GeoAddressVal })
            .then(function (result) {
              self.$app.utils.nextFrame(() => { self.$app.progressbar.hide(); });

              if (!result.length) {
                self.$app.methods.customNotification({ text: LANGUAGE.PROMPT_MSG008 });
                return;
              }

              let template = '<ul>';
              for (let i = 0; i < result.length; i++) {
                template += `<li data-key="${i}">${result[i].label}</li>`;
              }
              template += '</ul>';
              resultContainer.html(template);
              if (!resultContainer.hasClass('show')) {
                resultContainer.addClass('show');
              }

              $(document).on('click.hideAddressesList', function (e) {
                if (!$$(e.target).closest('.results').length) {
                  resultContainer.removeClass('show');
                  $(document).off('.hideAddressesList');
                }
              });

              resultContainer.find('li').on('click', function (e) {
                $GeoAddress.val(result[e.target.dataset.key].label);
                resultContainer.removeClass('show');
                $(document).off('.hideAddressesList');

                if (self.AddressMarker) {
                  self.MapOrder.removeLayer(self.AddressMarker);
                }
                self.AddressMarker = L.marker([result[e.target.dataset.key].y, result[e.target.dataset.key].x], { icon: Protocol.MarkerIcon[15] });
        
                self.AddressMarker.addTo(self.MapOrder);

                self.MapOrder.fitBounds(result[e.target.dataset.key].bounds, { padding: [16, 16] });

            



              });
            }).catch(function () {
              self.$app.utils.nextFrame(() => { self.$app.progressbar.hide(); });
              self.$app.methods.customNotification({ text: LANGUAGE.COM_MSG36 });
            });
        });


      


        $$('.smart-select-poi2 select').on('change', function (e) {
          let checkedPoiCode = e.srcElement.value
          let poi
         
      
          $$(".smart-select-poi2 select option").forEach((el, index) => {       
              poi = self.PoiList.find(item => item.Code == checkedPoiCode)
          })
          if(poi !== undefined) {
              if (self.AddressMarker) {
                  self.MapOrder.removeLayer(self.AddressMarker);
                }
                self.AddressMarker = L.marker([poi.Lat, poi.Lng], { icon: Protocol.MarkerIcon[15] });
                self.AddressMarker.addTo(self.MapOrder);
                self.MapOrder.fitBounds([[poi.Lat, poi.Lng]], { padding: [16, 16] });
              $$('.address-textarea').addClass('display-none')
            } else {       
              $$('.address-textarea').removeClass('display-none')
              if (self.AddressMarker) {
                  self.MapOrder.removeLayer(self.AddressMarker);
                }
            }

        })

       
        if(self.$route.query.id) {
          let taskIndex = taskList.findIndex(x => x.Task.Code == self.$route.query.code);
          var orders= []

          if (taskIndex != -1) {
            orders = taskList[taskIndex].Orders
          }

          let orderIndex = orders.findIndex(x => x.OrderID == self.$route.query.id);
        
          if (orderIndex != -1) {
            Protocol.Helper.getAddressByGeocoder({ lat: orders[orderIndex].StartLat, lng: orders[orderIndex].StartLng }, function (address) {
              self.$setState({
                Address: address
              })
          
            });
          }
          self.AddressMarker = L.marker([orders[orderIndex].StartLat, orders[orderIndex].StartLng], { icon: Protocol.MarkerIcon[15] });
          self.MapOrder.fitBounds([[orders[orderIndex].StartLat, orders[orderIndex].StartLng]], { padding: [16, 16] });
          self.AddressMarker.addTo(self.MapOrder);

        }
        

        $$(form).on('submit', function (e) {
          e.preventDefault();
          var userInfo = self.$app.methods.getFromStorage('userInfo');

          let url = API_URL.NEW_ORDER + '?MajorToken=' + userInfo.MajorToken + '&MinorToken=' + userInfo.MinorToken

          let coords = {}

            if (self.AddressMarker) {
              coords = self.AddressMarker.getLatLng();
            }


          
          var orderNameEl = page.$el.find('[name = "OrderName"]');
          var templateInputEl = page.$el.find('[name = "TemplateInput"]');
          var typeJobInputEl = page.$el.find('[name = "TypeJobInput"]');
          var jobDurationEl = page.$el.find('[name = "JobDuration"]');
          var planedArrivaleEl = page.$el.find('[name = "PlannedArrival"]');
          var estimatedArrivalEl = page.$el.find('[name = "EstimatedArrival"]');
          var toleranceInputlEl = page.$el.find('[name = "ToleranceInput"]');
          var timeWindowlEl = page.$el.find('[name = "TimeWindow"]');
          var noteEl = page.$el.find('[name = "Note"]');
          var contactNamelEl = page.$el.find('[name = "ContactName"]');
          var contactPhoneEl = page.$el.find('[name = "ContactPhone"]');
          var linkedOrderlEl = page.$el.find('[name = "LinkedOrder"]');
          var nextOrderEl = page.$el.find('[name = "NextOrder"]');


       

          var data = {
            OrderName: orderNameEl.val(),
            TemplateId: templateInputEl.val(),
            JobType: typeJobInputEl.val(),
            Duration: jobDurationEl.val(),
            PlannedArrival: planedArrivaleEl.val(),
            EstimatedArrival: estimatedArrivalEl.val(),
            Tolarance: toleranceInputlEl.val(),
            CustomerTimeWindow: timeWindowlEl.val(),
            Note: noteEl.val(),
            LinkedOrder: linkedOrderlEl.val(),
            NextOrderId: nextOrderEl.val(),
            CustomerName: contactNamelEl.val(),
            CustomerContact: contactPhoneEl.val(),
            StartLat: coords?.lat,
           // EndLat: "",
            StartLng: coords?.lng,
           // EndLng: "",
            TaskCode: self.TaskCode,
            DriverCode: self.DriverCode  // vlad standart
          };

          if(self.$route.query.id) {
            url = API_URL.EDIT_ORDER + '?MajorToken=' + userInfo.MajorToken + '&MinorToken=' + userInfo.MinorToken
            data.OrderId = self.$route.query.id
          }  


 
 
          self.saveOrder(data, url);

          return false;
        });




      },
      pageAfterIn: function () {
        var self = this;
    

      },
      pageAfterOut: function () {
        // page has left the view

      },
      pageBeforeRemove: function () {
        var self = this;
        self.MapOrder.off()
        self.MapOrder.remove()
        //console.log('here');
      }

    }
  };
</script>