<!--suppress JSAnnotator -->
<template>
  <div class="page" data-name="create-task">
    {{#unless isHideCloseBtn}}
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left"></div>
        <div class="title sliding">{{@global.LANGUAGE.JOB_DESPATCH_MSG00}}</div>
        <div class="right">

          {{#unless isHideCloseBtn}}
          <a href="#" class="link popup-close" data-popup=".popup-fullscreen-createtask">
            <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  ">
      <div class="display-flex flex-direction-column  bottom-section-button-wrapper    justify-content-space-evenly">
        <div class="row">
          <label for="submit-form-new-task" class="col button button-fill color-green elevation-2"
            tabindex="0">
   

            {{@global.LANGUAGE.JOB_DESPATCH_MSG27}}</label>
        </div>
        <!-- <div class="row">
          <button   class="col button button-fill color-red elevation-2"
            tabindex="0">{{@global.LANGUAGE.JOB_DESPATCH_MSG28}}</button>
        </div>  -->
      </div>

    </div>


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

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

        <form name="TaskEditForm" class="page-content no-padding content-sidebar left">

          <input type="submit" id="submit-form-new-task" class="display-none" />
          <div class="list no-margin no-hairlines new-task-list">
            <ul>
              <li class="item-content">
                <div class="item-inner size-16"><b>{{@global.LANGUAGE.JOB_DESPATCH_MSG18}}</b> </div>

              </li>
              <li>
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-driver"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title item-label"></div>
                    <a class="item-link smart-select smart-select-driver smart-select-init custom-smart-select"
                      data-open-in="popover" data-close-on-select="true">
                      <select name="DriverSelectInput">
                        {{#DriverList}}
                        <option value="{{Code}}" {{#if Selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{FirstName}} {{SubName}}</option>
                        {{/DriverList}}
                      </select>
                      <div class="item-inner">
                        <div class="item-title item-label"> {{@global.LANGUAGE.ASSET_EDIT_MSG23}}
                        </div>
                      </div>
                    </a>
                  </div>
                </div>
              </li>


              <li class="item-content item-input ">
                <div class="item-media text-color-lightgray"><i class="f7-icons icon-overspeed "></i></div>
                <div class="item-inner">
                  <div class="item-title item-label"> {{@global.LANGUAGE.JOB_DESPATCH_MSG19 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG19 }}" name="TaskNameInput"
                      value="{{TaskName}}" maxlength="200" required validate>
                  </div>
                </div>
              </li>
              <li class="item-content">
                <div class="item-inner size-16"><b>{{@global.LANGUAGE.JOB_DESPATCH_MSG20}}</b> </div>

              </li>



              <div class="block">
                <div class="row no-gap">
                  <div class="col text-align-center">
                    <i class="f7-icons icon-address text-color-lightgray"></i>

                    <p class="text-color-black no-margin">{{PlacesCount}} orders</p>
                  </div>
                  <div class="col text-align-center">
                    <i class="f7-icons icon-overspeed text-color-lightgray"></i>

                    <p class="text-color-black no-margin">{{TotalDistance}}</p>
                  </div>
                  <div class="col text-align-center">
                    <i class="f7-icons icon-engine text-color-lightgray"></i>

                    <p class="text-color-black no-margin">{{TotalTime}}</p>
                  </div>
                </div>
              </div>

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

              </li>
              <li>
                <div class="item-content item-input startDateTimeWrapper" data-input-name="StartDateTime">
                  <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.ASSET_PLAYBACK_MSG02}}</div>
                    <div class="item-input-wrap">
                      <input type="text" name="StartDateTime" class="StartDateTime"
                        placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG02}}" value="{{StartDateTime}}"
                        maxlength="200" readonly>
                    </div>
                  </div>
                </div>
              </li>
              <li>
                <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-poi 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>

              <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}} </div>
                    <div class="item-input-wrap">
                      <textarea name="GeoAddress" rows="2" style="height: 50px"
                        placeholder="{{@global.LANGUAGE.GEOFENCES_MSG06}}" maxlength="400"
                        value="">{{StartAddress}}</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 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_MSG25}}</div>
                          <div class="item-after">
                            <i class="icon icon-checkbox"></i>
                          </div>
                     
                        <input type="checkbox" name="selectUseStartingAddress" id="selectUseStartingAddress" {{#if isUseStartAddress}} checked {{/if}} />
                        <div class="item-media text-color-lightgray">
                        </div>
                       
                      </label>

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

              </li>
              <li class=" media-list virtual-list no-chevron no-margin no-hairline-bottom ordersList">
                <!-- keep it empty -->
              </li>
              <li>
                <div class="item-content item-input">
                  <div class="item-media text-color-green justify-content-center">
                    <i class="f7-icons icon-add-group icon-add-circle "></i>
                  </div>
                  <div class="item-inner display-flex">
                    <a href="#" class="item-link text-color-green addOrder">{{@global.LANGUAGE.JOB_DESPATCH_MSG26 }}</a>
                  </div>
                </div>
              </li>


            </ul>
          </div>



        </form>



        <div class="content">
          <div id="mapTask" class="task-map">
          </div>
        </div>
      </div>


    </div>
  </div>


</template>

<script>
  // script must return component object
  return {
    data: function () {
      var self = this;
      var ret = {};
      var poiList = self.$app.methods.getFromStorage('POIList')

      var today = moment().format('MMMM DD YYYY, HH:mm');
      var contactList = self.$app.methods.getFromStorage('contactList');
      var taskList = self.$app.methods.getFromStorage('taskList');
      let task = null
      let driverList = []


      var geofenceList = Protocol.Helper.getGeofenceList();
      var timePeriodList = Protocol.Helper.getTimePeriodList();
      var typeJobList = Protocol.Helper.getTypeJobList();



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

        if (taskIndex != -1) {
          task = taskList[taskIndex]

          let contactIndex = contactList.findIndex(x => x.Code == task.Task.DriverCode);

          if (contactIndex != -1) {

            contactList[contactIndex].Selected = true;
        }
      
          //$$('.smart-select-driver .item-after').text(contactList[contactIndex].FirstName + contactList[contactIndex].SubName)
        }


      }

 

      ret = {
        TaskName: self.$route.query.name ? self.$route.query.name : task?.Task.TaskName,
        PoiList: poiList,
        StartDateTime: task?.Task.StartDate ? moment.utc(task?.Task.StartDate).format('MMMM DD YYYY, HH:mm') : today,
        TaskList: [],
        GeofenceList: geofenceList,
        TimePeriodList: timePeriodList,
        TypeJobList: typeJobList,
        DriverList: contactList,
        isUseStartAddress: false,
        StartCoords: '',
        TaskCode: self.$route.query.code,
        VirtualOrdersList: null,
        PlacesCount: 0,
        TotalDistance: '0',
        TotalTime: '0',
        StartAddress: ''
      }


      return ret;
    },
    methods: {
      initOrdersList: function (ordersList) {
        let self = this;
        let listEl = self.$el.find('.ordersList');
        var typeJobList = Protocol.Helper.getTypeJobList();
        var hashMap = {}
        var reverseSortedArray = []

   
        // for(i = 0; i < ordersList?.length; i++) {
        //   hashMap[ ordersList[i].NextOrderId] = ordersList[i].OrderID
        // }

        // let previousOrderID = hashMap[null]

        // for (i = 0; i < ordersList?.length; i++){    
        //   reverseSortedArray.push(previousOrderID)
        //   previousOrderID = hashMap[previousOrderID]
        // }

        // let sortingArr = reverseSortedArray.reverse()
        // let sortOrderList = ordersList.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));
 

        self.VirtualOrdersList = self.$app.virtualList.create({
          el: listEl,
          items: ordersList || [],
          //cache: false,

          height: function (item) {
            return 60
          },
          renderItem: function (item, index) {
            self.PlacesCount += 1
            let jobType = typeJobList.find(obj => obj.Value === item.JobType)

 
            let ret = `
                            <li   data-id="${item.OrderID}" data-index="${index}" groupItemWrapper>`;
            ret += ` <a href="#" class="item-content editOrder link groupOrderItem">
                                      <div class="item-content width-100 item-input">
                                        <div class="item-media align-self-flex-start  justify-content-center">
                                          <div class="order-circle">${index + 1}</div> 
                                            
                                        </div>
                                        <div style="    padding-top: 10px;" class="item-inner display-flex align-items-flex-start flex-direction-column">
                                          <div class="item-title size-16 text-color-black">
                                            ${jobType.Name}
                                             </div>`
            if (item.StartLat == 0 && item.StartLng == 0) {
              ret += `<span class=" no-margin text-color-black">Address is not selected</span>`
            } else {
              ret += `<span class="size-13 no-margin addressOrder text-color-black"></span>`


            }


            ret += `<span class=" size-13 no-margin text-color-gray">${LANGUAGE.JOB_DESPATCH_MSG38}(${item.EstimatedArrival})</span>`


            ret += `
                                            <div class="divider"></div>
                                            </div>
                                            <div class="item-after padding-right">
                                              <i class="f7-icons icon-arrow2 text-color-lightgray size-12"></i> 
                                            </div>
                                      </div>
                                           
                                 </a>
                                
                            </li>`;
            return ret;
          },
          emptyTemplate: ``
        });


        for (let i = 0; i < ordersList?.length; i++) {

          let orderItemEl = $$('.groupOrderItem').closest(`li[data-index="${i}"]`)
          let addressOrderEl = $$(orderItemEl).find('.addressOrder')


          if (ordersList[i].StartLat !== 0) {
            Protocol.Helper.getAddressByGeocoder({ lat: ordersList[i].StartLat, lng: ordersList[i].StartLng }, function (address) {
              $$(addressOrderEl).text(address)
            });
          }
        }
      },




      showOnMap: function (data) {
        let self = this;

        if (data.IMEI && POSINFOASSETLIST && POSINFOASSETLIST[data.IMEI] && POSINFOASSETLIST[data.IMEI].markerIdDashboard) {
          var marker = self.AllMarkersGroup.getLayer(POSINFOASSETLIST[data.IMEI].markerIdDashboard);
          self.AllMarkersGroup.zoomToShowLayer(marker, function () {
            if (self.MapTrack.getZoom() < 15) {
              self.MapTrack.setView(marker.getLatLng(), 15)
            }
            marker.openPopup();
          });
        } else {
          self.$app.methods.customNotification({
            title: data.Name ? data.Name : data.IMEI,
            text: LANGUAGE.PROMPT_MSG031
          });
        }
      },

      updateTask: function (data) {
        let self = this;


        self.$app.request.post(API_URL.JOB_TASK_UPDATE, 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-createtask')
              // 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 Update Task');
          },
          'json');

      }


    },

    on: {
      pageMounted: function () {
        let self = this;




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

        var form = page.$el.find('[name = "TaskEditForm"]');
        var startDateTimeEl = page.$el.find('input[name="StartDateTime"]');
        var datepickerFormat = 'MMMM DD YYYY, HH:mm';
        var startDateTimeWrapper = page.$el.find('.startDateTimeWrapper');
        let searchAddressButtonEl = page.$el.find('.input-search-button');
        let PoiSSEl = page.$el.find('.smart-select-poi');



        var taskList = self.$app.methods.getFromStorage('taskList')

        let task = taskList.find(obj => obj.Task.Code === self.TaskCode)
        let orders = task?.Orders

        self.initOrdersList(orders)



   

        self.MapTask = Protocol.Helper.createMap({ target: 'mapTask', latLng: [38.530015, -101.649213], zoom: 4 });
        self.Routing = L.Routing.control({
          lineOptions: {
            styles: [{ color: '#0095D1', opacity: 1, weight: 3 }]
          },
          //routeWhileDragging: true,
          waypoints: [
            null
          ],

          createMarker: function (i, wp, nWps) {
            if (i === 0) {
              // here change the starting  icon //i === nWps - 1  (here change the  ending icon)
              return L.marker(wp.latLng, {
                icon: Protocol.MarkerIcon[17] // here pass the custom marker icon instance
              });
            } else {

              return L.marker(wp.latLng, {
                icon: new L.DivIcon({
                  className: 'div-icon',
                  html: '<img class="div-image" src="../resources/images/job-pin.svg"/>' +
                    `<span class="text-color-white size-18 div-icon-number">${i}</span>`,
                  iconSize: [25, 25],
                  iconAnchor: [16, 31],
                  popupAnchor: [0, -32]
                })
              });

            }
          }
        }).addTo(self.MapTask);

        self.Routing.on('routesfound', function (e) {
          var routes = e.routes;
          var summary = routes[0].summary;


        self.$setState({
            TotalDistance: Math.floor(summary.totalDistance / 1000 * 100) / 100 + ' km ',
            TotalTime: moment.utc(summary.totalTime * 1000).format('HH:mm:ss')
          });
        });
        $$('.smart-select-poi select').on('change', function (e) {
        
          let checkedPoiCode = e.srcElement.value
          let poi

          $$(".smart-select-poi select option").forEach((el, index) => {
            poi = self.PoiList.find(item => item.Code == checkedPoiCode)
          })

          if (poi !== undefined) {
            let waypointsArr = [L.latLng(poi.Lat, poi.Lng)]
  
            self.$setState({
              StartCoords: waypointsArr[0]
            })

            if(orders) {
              for (let i = 0; i < orders.length; i++) {
                if (orders[i].StartLat !== 0) {
                  waypointsArr.push(L.latLng(orders[i].StartLat, orders[i].StartLng))
                }
              }
            }
           
            self.Routing.setWaypoints(waypointsArr);

            if(waypointsArr.length === 1) {
              self.MapTask.fitBounds([[poi.Lat, poi.Lng]], { padding: [30, 30] });
            }
            $$('.address-textarea').addClass('display-none')
            } else {
              $$('.address-textarea').removeClass('display-none')
              self.Routing.spliceWaypoints(0, 1);
            }
         
        })

        



 

        if (task && task.Task.StartLat !== 0 && task.Task.StartLat !== null) {
          let waypointsArr = [L.latLng(task.Task.StartLat, task.Task.StartLng)]
          self.$setState({
            StartCoords: waypointsArr[0]
          })

          Protocol.Helper.getAddressByGeocoder({ lat: task.Task.StartLat, lng: task.Task.StartLng }, function (address) {
            self.$setState({
              StartAddress: address
            })
          });

          for (let i = 0; i < orders.length; i++) {
            if (orders[i].StartLat !== 0) {
              waypointsArr.push(L.latLng(orders[i].StartLat, orders[i].StartLng))
            }
          }

       
          self.Routing.setWaypoints(waypointsArr);
          if(waypointsArr.length === 1) {
            self.MapTask.fitBounds([[task.Task.StartLat, task.Task.StartLng]], { padding: [30, 30] });
          }
        }



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



        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');

      



                let waypointsArr = [L.latLng(result[+e.target.dataset.key].y, +result[e.target.dataset.key].x),]


                self.$setState({
                  StartCoords: waypointsArr[0]
                })


                for (let i = 0; i < orders?.length; i++) {
                  if (orders[i].StartLat !== 0) {
                    waypointsArr.push(L.latLng(orders[i].StartLat, orders[i].StartLng))
                  }
                }

                self.Routing.setWaypoints(waypointsArr);
               
                if(waypointsArr.length == 1 && !orders) {
                   self.MapTask.fitBounds([waypointsArr[0]], { padding: [30, 30] });
                }






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

        var buttonAddOrder = page.$el.find('.addOrder');
        var driverInputEl = page.$el.find('[name="DriverSelectInput"]')


        buttonAddOrder.on('click', function () {

          let driverCode = driverInputEl.val()

          if (driverCode == '0') {
            self.$app.dialog.alert('Please select a driver');
          } else {
            self.$app.popup.open('.popup-fullscreen-createorder')

            createorderView.router.navigate({
              name: 'create-order',
              query: {
                code: self.TaskCode,
                driverCode: driverCode
              },
            });
          }



        });



        $$('.ordersList').on('click', '.editOrder', function (e) {
          var id = $$(e.target).closest('li').data('id');
          if (id) {

            let driverCode = driverInputEl.val()

            if (driverCode == '0') {
              self.$app.dialog.alert('Please select a driver');
            } else {
              self.$app.popup.open('.popup-fullscreen-createorder')

              createorderView.router.navigate({
                name: 'create-order',
                query: {
                  code: self.TaskCode,
                  driverCode: driverCode,
                  id: id
                },
              });
            }



          }
        })







        $$(form).on('submit', function (e) {
          e.preventDefault();
          var userInfo = self.$app.methods.getFromStorage('userInfo');
          var driverInputEl = page.$el.find('[name="DriverSelectInput"]')
          var taskNameInputEl = page.$el.find('[name="TaskNameInput"]')
          var startDateTimeEl = page.$el.find('[name = "StartDateTime"]');


          var data = {
            DriverCode: driverInputEl.val(),
            CustomerCode: self.$root.MajorToken,
            TaskName: taskNameInputEl.val(),
            Code: self.TaskCode,
            StartLat: self.StartCoords.lat,
            StartLng: self.StartCoords.lng,
            StartDate: startDateTimeEl.val(),
            // "EndLat":"",
            // "EndLng":"",
            // "StartDate":"",
            // "EndDate":"",
            // "EndTime":""
            // "StartAddress":"",
          };




          self.updateTask(data);

          return false;
        });



        // page.$el.on('click', '.showOnMap', function (e) {
        //   let imei = $$(this).data('imei')
        //   let name = $$(this).data('name')
        //   self.showOnMap({ IMEI: imei, Name: name })
        // });





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


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

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

    }
  };
</script>