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

        <div class="right">
          {{#unless TypeDealer}}

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





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



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


        <form name="TemplateEditForm" class="page-content no-padding content-sidebar left">
          <div class="bottom-section-wrapper   bottom-section-button-wrapper bg-color-white">
            <div class="row">
              <label for="submit-form-new-template" class="col button button-fill color-green elevation-2"
                tabindex="0">
                
                {{SubmitButtonName}}
          </label>
            </div>
          </div>


          <input type="submit" id="submit-form-new-template" class="display-none" />
          <div class="list 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_MSG08 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG08 }}" name="TemplateName"
                      value="{{TemplateName}}" maxlength="200" required validate>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content item-input">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-input"></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="TemplateType">
                        {{#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-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="Description" rows="10" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG10}}"
                      maxlength="400" value="">{{Description}}</textarea>
                  </div>
                </div>
              </li>
              <li class="item-content">
                <div class="item-inner size-16"><b>{{@global.LANGUAGE.JOB_DESPATCH_MSG12}}</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"> {{@global.LANGUAGE.JOB_DESPATCH_MSG14 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG14 }}" name="Name"
                      value="{{Name}}" maxlength="200" 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"> {{@global.LANGUAGE.JOB_DESPATCH_MSG15 }}</div>
                  <div class="item-input-wrap ">
                    <input type="text" placeholder="{{@global.LANGUAGE.JOB_DESPATCH_MSG15 }}" name="Phone"
                      value="{{Phone}}" maxlength="200" validate>
                  </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-poi3 smart-select smart-select-init custom-smart-select"
                      data-open-in="popover" data-close-on-select="true">
                      <select name="POISelect">
                        {{#PoiList}}
                        <option value="{{Code}}" {{#if selected}} selected {{/if}} {{#if disabled}} disabled {{/if}}>
                          {{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">
                <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="">{{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>


            </ul>
          </div>



        </form>

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


    </div>
  </div>


</template>

<script>
  // script must return component object
  return {
    data: function () {
      var self = this;
      var ret = {};
      var geofenceList = Protocol.Helper.getGeofenceList();
      var timePeriodList = Protocol.Helper.getTimePeriodList();
      var typeJobList = Protocol.Helper.getTypeJobList();
      var poiList = self.$app.methods.getFromStorage('POIList')

    
      if (self.$route.query.code) {
        let templatesList = self.$app.methods.getFromStorage('templateList');
        if (templatesList && templatesList.length) {

          let template = self.$app.methods.findObjectByKey(templatesList, 'ID', self.$route.query.code);
          ret.template = template ? template : {};
          ret.TemplateName = template.TemplateName
          ret.Description = template.Note
          ret.Name = template.ContactName
          ret.Phone = template.ContactPhone
        }
      }


      ret.PageTitle = self.$route.query.code ? LANGUAGE.JOB_DESPATCH_MSG23 : LANGUAGE.JOB_DESPATCH_MSG07;

     

      if (self.$route.query.code &&  ret.template) {
        let jobIndex = typeJobList.findIndex(x => x.Value == ret.template.JobType);
   
        if (jobIndex != -1) {
          typeJobList[jobIndex].Selected = true;
        }
      }
   
 
 
      ret.PoiList = poiList;
      ret.MapTemplate = false;
      ret.GeofenceList = geofenceList;
      ret.TimePeriodList = timePeriodList;
      ret.TypeJobList = typeJobList;
      ret.SubmitButtonName = self.$route.query.code ? LANGUAGE.JOB_DESPATCH_MSG46 : LANGUAGE.JOB_DESPATCH_MSG13

      return ret;
    },
    methods: {


      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.MapTemplate.getZoom() < 15) {
              self.MapTemplate.setView(marker.getLatLng(), 15)
            }
            marker.openPopup();
          });
        } else {
          self.$app.methods.customNotification({
            title: data.Name ? data.Name : data.IMEI,
            text: LANGUAGE.PROMPT_MSG031
          });
        }
      },

 

      saveTemplate: function (url, data) {
        var self = this;
        self.$app.preloader.show();
        self.$app.request.post(url, data, function (result, xhr, status) {
          self.$app.utils.nextFrame(()=>{
                        self.$app.preloader.hide();
                    });
          if (result && result.MajorCode === '000') {
           self.$app.popup.close('.popup-fullscreen-newtemplate') 

           leftView.router.refreshPage();

          }
        },
          function (xhr, status) {
            console.log('Error occured doring  add template');
          },
          'json');
      },
    
    },

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


        // $$('.smart-select-poi3 select').on('change', function (e) {
        //   let checkedPoiCode = e.srcElement.value
        // })
        
   

        $$(document).on("smartselect:close", ".smart-select-poi3", e => {
          //checked options
          $$(".smart-select-poi3 select option").forEach((el, index) => {
            let checkedPoiCode = $$(el).is(":checked") ? el.value : '';
            let poi = self.PoiList.find(item => item.Code == checkedPoiCode)

            L.Routing.control({
              waypoints: [
                L.latLng(poi.Lat, poi.Lng)
              ]
            }).addTo(self.MapTemplate);

            self.MapTemplate.fitBounds([[poi.Lat, poi.Lng]], { padding: [16, 16] });

          })


        });


        let searchAddressButtonEl = page.$el.find('.input-search-button');
        var form = page.$el.find('[name = "TemplateEditForm"]');

      
        self.MapTemplate = Protocol.Helper.createMap({ target: 'mapTemplate', 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) {
                //   MapTemplate.removeLayer(self.AddressMarker);
                // }
                // self.AddressMarker = L.marker([result[e.target.dataset.key].y, result[e.target.dataset.key].x], { icon: Protocol.MarkerIcon[9] });
                // self.AddressMarker.bindPopup(result[e.target.dataset.key].label, { maxWidth: self.$app.data.MaxMapPopupWidth, closeButton: false });
                // self.AddressMarker.addTo(MapTemplate);


                L.Routing.control({
                  waypoints: [
                    L.latLng(result[+e.target.dataset.key].y, +result[e.target.dataset.key].x)

                  ]
                }).addTo(self.MapTemplate);



                self.MapTemplate.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 });
            });
        });
        $$(form).on('submit', function (e) {
          e.preventDefault();
          let templateName = form.find('[name="TemplateName"]').val()
          let jobType = form.find('[name="TemplateType"]').val()
          let note = form.find('[name="Description"]').val()
          let name = form.find('[name="Name"]').val()
          let phone = form.find('[name="Phone"]').val()

          // var userInfo = self.$app.methods.getFromStorage('userInfo');
          var data = {
            ContactName: name,
            ContactPhone: phone,
            CustomerCode: self.$root.MajorToken,
            TemplateName: templateName,
            JobType: jobType,
            Note: note
          };
          let url = API_URL.ADD_TEMPLATE
 
          if (self.$route.query.code) {
              url = API_URL.JOB_TEMPLATE_EDIT;
              data.ID = self.$route.query.code;
          }

           self.saveTemplate(url, data);
          
          // self.saveUserDetails(data, otherData);

          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(e, page) {
        page.router.clearPreviousHistory();
      },
      pageAfterOut: function () {
        // page has left the view
        var self = this;
    

      },
      pageBeforeRemove: function () {
        var self = this;
        self.MapTemplate.off()
        self.MapTemplate.remove()

       
        //console.log('here');
      }

    }
  };
</script>