<!--suppress JSAnnotator -->
<template>
    <!-- Page, data-name contains page name which can be used in callbacks -->
    <div class="page " data-name="geofence"> <!-- 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">{{PageTitle}}</div>
                <div class="right">

                </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="GroupEditForm" class="page-content">

            <input type="hidden" name="Code" value="{{Code}}">

            <input type="submit" id="submit-form" class="display-none" />
            <div class="list margin-top-0 no-hairline-top">
                <ul>
                    <li>
                        <div class="item-content item-input">
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-admin-geofences"></i>
                            </div>
                            <div class="item-inner">
                                <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG04}}</div>
                                <div class="item-input-wrap">
                                    <input type="text" name="Name" placeholder="{{@global.LANGUAGE.GEOFENCES_MSG05}}" value="{{Name}}" maxlength="200" required validate>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li class="item-content">
                        <div class="item-media text-color-lightgray">
                            <i class="f7-icons icon-active"></i>
                        </div>
                        <div class="item-inner">
                            <div class="item-title">{{@global.LANGUAGE.GEOFENCES_MSG09}}</div>
                            <div class="item-after">
                                <label class="toggle toggle-init">
                                    <input type="checkbox" name="ActiveState" {{#if ActiveState}}checked="checked"{{/if}}>
                                    <span class="toggle-icon"></span>
                                </label>
                            </div>
                        </div>
                    </li>
                    <li class="overflow-visible">
                        <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">
                                <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>
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-assets" 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}}" data-popup-close-link-text="{{@global.LANGUAGE.COM_MSG115}}">
                            <select name="Assets" multiple required validate  >
                                {{#AssetList}}
                                <optgroup label="{{Name}}" data-code="{{Code}}">
                                    {{#Assets}}
                                    <option value="{{IMEI}}" data-id="{{Id}}" {{#if AssetSelected}} selected {{/if}} >{{Name}}</option>
                                    {{/Assets}}
                                </optgroup>
                                {{/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>
                    </li>
                    <li>
                        <a class="item-link smart-select smart-select-init custom-smart-select" data-open-in="popover" >
                            <select name="AlarmType" multiple required validate>
                                {{#AlarmType reverse="true"}}
                                <option value="{{Val}}" {{#if State}} selected {{/if}}>{{Name}}</option>
                                {{/AlarmType}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-admin-alarms"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG08}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{#if NotifyEmailsLoaded}}
                    <li >
                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectContacts" 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.COM_MSG84}}">
                            <select name="NotifyEmails" multiple  >
                                {{#NotifyEmails}}
                                {{#if EMail}}
                                <option value="{{Code}}" {{#if Selected}} selected {{/if}}>{{EMail}}({{FullName}})</option>
                                {{/if}}
                                {{/NotifyEmails}}
                            </select>
							<div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-email"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG14}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
				   
                    {{else}}
                    <li key="PreloaderIntervalServicesList">
                        <div  class="item-content">
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-email"></i>
                            </div>
                            <div class="item-inner">
                                <div  class="item-title text-align-center">
                                    <div class="preloader color-red"></div>
                                </div>
                            </div>
                        </div>
                    </li>

                    {{/if}}




                </ul>
            </div>

            <div class="list no-hairline-top">
                <ul>
                    <li class="item-content">
                        <div class="item-inner">
                            <div class="item-title">{{@global.LANGUAGE.COM_MSG71}} <i class="f7-icons text-color-gray icon-hint margin-left-4 margin-right-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG0107}}"></i></div>
                            <div class="item-after">
                                <label class="toggle toggle-ignore-between">
                                    <input type="checkbox" name="IgnoreBetweenState" {{#if IgnoreBetweenState}}checked="checked"{{/if}}>
                                    <span class="toggle-icon"></span>
                                </label>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content item-input {{#unless IgnoreBetweenState}} 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.COM_MSG69}}</div>
                                        <div class="item-input-wrap">
                                            <input type="text" name="PickerStart" readonly="readonly" />
                                        </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" readonly="readonly" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <a class="item-link smart-select custom-smart-select smart-select-days-of-week {{#unless IgnoreBetweenState}} disabled {{/unless}}" 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">{{@global.LANGUAGE.COM_MSG72}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                </ul>
            </div>

            <div class="list no-hairline-top">
                <ul>
                    <li class="item-content">
                        <div class="item-inner">
                            <div class="item-title">{{@global.LANGUAGE.GEOFENCES_MSG18}} <i class="f7-icons text-color-gray icon-hint margin-left-4 margin-right-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG0106}}"></i></div>
                            <div class="item-after">
                                <label class="toggle toggle-share">
                                    <input type="checkbox" name="Share" {{#if Share}}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 assetList = self.$app.methods.getAssetsByGroups({NoGroupToBottom: true});

            //console.log(assetList);
            var ret = {
                PageTitle: self.$route.query.code ? LANGUAGE.COM_MSG73 : LANGUAGE.GEOFENCES_MSG03,
                Code: self.$route.query.code,
                //AssetList: assetList,
                AssetList: [],
                Name: '',
                Address: '',
                //Radius: 200,
                ActiveState: false,
                AlarmType: Protocol.Helper.getGoefenceAlarmTypes(),
                //GeofenceTypes: Protocol.Helper.getGeofenceTypes(),
                //GeofenceType: 1, //circle

                IgnoreBetweenState: false,
                TimePickerStart: false,
                TimePickerEnd: false,
                DaysOfWeekSelect: false,
                DaysOfWeek: [],

                //GroupRadius: false,
                GroupMarkers: false,

            };

            return ret;
        },
        methods: {
            initIgnoreBetweenBlock: function(params = {}){
                let self = this;

                if (params.BeginTime) {
                    params.BeginTime = moment(params.BeginTime,'HH:mm:ss').add(app.data.UTCOFFSET,'minutes').format('HH:mm:ss');
                }
                if (params.EndTime) {
                    params.EndTime = moment(params.EndTime,'HH:mm:ss').add(app.data.UTCOFFSET,'minutes').format('HH:mm:ss');
                }

                let StartTimeValArray = params.BeginTime ? params.BeginTime.split(':') : [];
                let EndTimeInputArray = params.EndTime ? params.EndTime.split(':') : [];
                let ignoreBetweenStateEl = self.$el.find('[name="IgnoreBetweenState"]');
                let daysOfWeekEl = self.$el.find('.smart-select-days-of-week');
                let daysOfWeekArray = Protocol.Helper.getWeekArray();

                if (!StartTimeValArray || !StartTimeValArray.length) {
                    StartTimeValArray = ['19', '00'];
                }
                if (!EndTimeInputArray || !EndTimeInputArray.length) {
                    EndTimeInputArray = ['06', '00'];
                }

                ignoreBetweenStateEl.on('change', function(){
                    self.$setState({
                        IgnoreBetweenState: this.checked
                    });
                });

                self.TimePickerStart = app.picker.create({
                    inputEl: self.$el.find('[name="PickerStart"]'),
                    rotateEffect: true,
                    value: StartTimeValArray,
                    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.TimePickerEnd = app.picker.create({
                    inputEl: self.$el.find('[name="PickerEnd"]'),
                    rotateEffect: true,
                    value: EndTimeInputArray,
                    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];
                    },
                });

                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,
                    IgnoreBetweenState: params.IgnoreBetweenState ? true : false,
                });

                self.DaysOfWeekSelect = app.smartSelect.create({
                    el: daysOfWeekEl,
                    openIn: 'popover',
                });


            },
            onMapClick: function (e) {
                var self = this;
                //self.GroupRadius.setLatLng(e.latlng);
                //self.getPointsInCircle(self.GroupRadius);

                self.updateGeofenceAddress(e.latlng);
            },
            updateGeofenceAddress: function(latlng){
                var self = this;
                app.progressbar.show();
                Protocol.Helper.getAddressByGeocoder(latlng,function(address){

                    self.$app.utils.nextTick(()=>{
                        app.progressbar.hide();
                    }, 300);


                    self.$setState({
                        Address: address,
                    });
                });
            },
            centeringMap: function(params){
                var self = this;
                if (params && params.onlyAddress) {
                    //MapTrack.fitBounds([self.GroupRadius.getBounds()],{padding:[16,16]});
                    //MapTrack.fitBounds([self.GeofenceLayer.getBounds()],{padding:[16,16]});
                    MapTrack.setView(params.coords,10);
                }else if(params && params.onlyAssets && self.GroupMarkers && self.GroupMarkers.getLayers().length > 0){
                    MapTrack.fitBounds([self.GroupMarkers.getBounds()],{padding:[16,16]});
                }else{
                    if (self.GroupMarkers && self.GroupMarkers.getLayers().length > 0 && self.GeofenceLayer) {
                        //MapTrack.fitBounds([self.GroupMarkers.getBounds(),self.GroupRadius.getBounds()],{padding:[16,16]});
                        MapTrack.fitBounds([self.GroupMarkers.getBounds(),self.GeofenceLayer.getBounds()],{padding:[16,16]});
                    }else if(self.GroupMarkers && self.GroupMarkers.getLayers().length > 0){
                        MapTrack.fitBounds([self.GroupMarkers.getBounds()],{padding:[16,16]});
                    } else if (self.GeofenceLayer){
                        //MapTrack.fitBounds([self.GroupRadius.getBounds()],{padding:[16,16]});
                        MapTrack.fitBounds([self.GeofenceLayer.getBounds()],{padding:[16,16]});
                    }else{
                        console.log('cant center map');
                    }
                }

            },
            updateGroupMarkers: function (assets){
                var self = this;
                if (self.GroupMarkers) {
                    self.GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(self.GroupMarkers);
                    }
                }
                self.GroupMarkers = L.markerClusterGroup({'maxClusterRadius':35,});
                if (assets && assets.length > 0) {
                    var point = '';
                    var markerData = '';
                    for (var i = assets.length - 1; i >= 0; i--) {
                        point = '';
                        markerData = '';
                        if (POSINFOASSETLIST[assets[i]] && POSINFOASSETLIST[assets[i]].posInfo && POSINFOASSETLIST[assets[i]].posInfo.lat !== 0 && POSINFOASSETLIST[assets[i]].posInfo.lng !== 0) {
                            point = L.marker([POSINFOASSETLIST[assets[i]].posInfo.lat,POSINFOASSETLIST[assets[i]].posInfo.lng], {icon: !self.$app.data.AppDetails.customMapMarker ? Protocol.MarkerIcon[2] : self.$app.data.AppDetails.customMapMarker, pmIgnore: true});
                            markerData = POSINFOASSETLIST[assets[i]].Name ? POSINFOASSETLIST[assets[i]].Name : POSINFOASSETLIST[assets[i]].IMEI;
                            point.bindTooltip(markerData,{permanent: false, direction: 'right'});
                            point.addTo(self.GroupMarkers);
                        }
                    }
                    self.GroupMarkers.addTo(MapTrack);

                    self.centeringMap();

                }
            },







            saveGeofence: function(data, url){
                var self = this;

                self.$app.preloader.show();
                self.$app.request.post(url, data, function (result, xhr, status) {

                      //console.log(result);
                      if (result && result.MajorCode == '000') {
                          self.$app.preloader.hide();
                          leftView.router.back();

                      }else{
                          self.$app.preloader.hide();
                          self.$app.dialog.alert('Something wrong');
                      }

                  },
                  function (xhr, status) {
                      self.$app.preloader.hide();
                      self.$app.dialog.alert('Error occured at Save Geofence details');
                  },
                  'json');
            },

            getPointsInCircle: function (circle) {
                var self = this;
                if (AllMarkersGroup && circle !== undefined) {
                    var circle_lat_long = circle.getLatLng();

                    var pointsInCircle = [];

                    AllMarkersGroup.eachLayer(function(layer) {
                        var distance_from_layer_circle = layer.getLatLng().distanceTo(circle_lat_long);

                        if (distance_from_layer_circle <= circle.getRadius()) {
                            if (layer._custom_asset_imei) {
                                pointsInCircle.push(layer._custom_asset_imei);
                            }
                        }
                    });

                    var select = self.$el.find('select[name="Assets"]');
                    var notInGroupAssetsGroup = select.find('optgroup[data-code="000000"]');
                    if (notInGroupAssetsGroup && notInGroupAssetsGroup.length) {
                        notInGroupAssetsGroup.find("option").prop('selected', false);
                    }
                    if (pointsInCircle.length) {
                        $.each(pointsInCircle, function(key, val){
                            //check is the asset in any group if not then select this asset
                            notInGroupAssetsGroup.find('option[value="'+val+'"]').prop('selected', true);
                        });
                    }
                    select.change();

                }
            },

            getEmailList: function(){
                let self = this;
                let userInfo = self.$app.methods.getFromStorage('userInfo');

                self.$app.request.post(API_URL.GET_CONTACT_USERS_LIST, {MajorToken: userInfo.MajorToken}, function (result, xhr, status) {
                      let contactList = [];
                      if (result && result.length) {
                          contactList = self.$app.methods.sortContactList(result);
                          //console.log(self.ContactList);
                          if (self.ContactList && self.ContactList.length) {
                              for (let i = self.ContactList.length - 1; i >= 0; i--) {
                                  if (self.ContactList[i].Code) {
                                      let index = contactList.findIndex(x => x.Code==self.ContactList[i].Code);
                                      if (index != -1) {
                                          contactList[index].Selected = true;
                                      }
                                  }
                              }
                          }

                      }
					  contactList.push({
						EMail: userInfo.UserInfo.Email,
						FirstName: userInfo.UserInfo.FirstName,
						SubName: userInfo.UserInfo.SurName,
						Code: self.$app.data.MajorToken,
						CustomerCode: self.$app.data.MinorToken,						
						FullName: userInfo.UserInfo.FirstName + ' ' + userInfo.UserInfo.SurName,
						Mobile: userInfo.UserInfo.Mobile,
						Number: userInfo.UserInfo.Number,
						Phone: userInfo.UserInfo.Mobile,
					});
                          
                      self.$setState({
                          NotifyEmails: contactList,
                          NotifyEmailsLoaded: true
                      });
                  },
                  function (xhr, status) {

                      self.$app.dialog.alert('Error occured at Get Contact List ');
                  },
                  'json');
            },
            isClockwise: function(poly){
                var sum = 0;
                for (var i=0; i<poly.length-1; i++) {
                    var cur = poly[i],
                      next = poly[i+1];
                    sum += (next.lat - cur.lat) * (next.lng + cur.lng)
                }
                return sum > 0
            },
            pmDrawStart: function(e){
                var self = this;
                if (self.GeofenceLayer) {
                    MapTrack.removeLayer(self.GeofenceLayer);
                }
            },
            pmCreate: function(e){
                var self = this;
                self.GeofenceLayer = e.layer;
            },
            clickOnLiAddress: function (e) {
                let self = this;
            }

        },

        on: {
            pageInit: function (e, page) {
                let self = this;
                let assetList = self.$app.methods.getAssetsByGroups({NoGroupToBottom: true});
                //let filteredAssetList = assetList.filter(itm => !itm.isShared )
                assetList.forEach(group => {
                    group.Assets = group.Assets.filter(itm => !itm.isShared )
                })
                //let latlng = [0, 0];

                let formEl = page.$el.find('[name = "GroupEditForm"]');
                //let radiusEl = page.$el.find('[name="Radius"]');
                let assetsEl = page.$el.find('[name="Assets"]');
                let searchAddressButtonEl = page.$el.find('.input-search-button');
                let searchAddressInputEl = page.$el.find('[name="GeoAddress"]');
                //let geofenceTypeEl = page.$el.find('[name="GeofenceType"]');




                // MapTrack.on('click', self.onMapClick);

                //Leaflet.PM global Settings
                MapTrack.pm.setPathOptions(self.$app.data.PolygonCustomization);

                MapTrack.pm.addControls({
                    position: 'topleft',
                    drawMarker: false,
                    drawPolyline: false,
                    //drawRectangle: false,
                    cutPolygon: false,
                    //drawCircle: false,
                });

                MapTrack.on('pm:drawstart', self.pmDrawStart);
                MapTrack.on('pm:create', self.pmCreate);

                if (!self.Code) {
                    self.initIgnoreBetweenBlock();



                    self.$setState({
                        AssetList: assetList,
                    });

                    /*self.GroupRadius = L.circle(latlng, {
		                color: '#AA5959',
		                fillColor: '#FF0000',
		                fillOpacity: 0.25,
		                radius: self.Radius,
		            }).addTo(MapTrack); */
                }else{
                    let geofenceList = self.$app.methods.getFromStorage('geofenceList');
                    let geofence = geofenceList[self.Code];
                    let weeks = '';
                    let latlng = [geofence.Lat, geofence.Lng];

                    if (geofence.Week && geofence.Week.length) {
                        for (let i = geofence.Week.length - 1; i >= 0; i--) {
                            weeks += geofence.Week[i].Week+',';
                        }
                        weeks.slice(0, -1);
                    }

                    if (geofence.SelectedAssetList && geofence.SelectedAssetList.length) {
                        for (let i = geofence.SelectedAssetList.length - 1; i >= 0; i--) {
                            for (var y = assetList.length - 1; y >= 0; y--) {
                                if (assetList[y].Assets && assetList[y].Assets.length) {
                                    let found = assetList[y].Assets.findIndex(x => x.Id == geofence.SelectedAssetList[i].AsCode);
                                    if (found != -1) {
                                        assetList[y].Assets[found].AssetSelected = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (geofence.GeoType == 1) { //circle
                        self.GeofenceLayer = L.circle(latlng, {
                            ...self.$app.data.PolygonCustomization,
                            radius: geofence.Radius,
                        }).addTo(MapTrack);
                    }else{
                        if (geofence.GeoPolygon) {
                            var polygonCoordsArr = geofence.GeoPolygon.split('((').pop().split('))')[0].split(',');
                            var geojsonArr = [];
                            for (var i = polygonCoordsArr.length - 1; i >= 0; i--) {
                                geojsonArr.push(polygonCoordsArr[i].split(' ').map(parseFloat).reverse());
                            }
                            self.GeofenceLayer = L.polygon(geojsonArr, {
                                ...self.$app.data.PolygonCustomization,
                            }).addTo(MapTrack);
                        }
                    }

                    /*self.GeofenceLayer = L.circle(latlng, {
                        ...self.$app.data.PolygonCustomization,
                    }).addTo(MapTrack);*/

                    self.initIgnoreBetweenBlock({
                        IgnoreBetweenState: geofence.Inverse,
                        Weeks: weeks,
                        BeginTime: weeks ? geofence.Week[0].BeginTime : '',
                        EndTime: weeks ? geofence.Week[0].EndTime : '',

                    });
                    console.log('c',geofence.ContactList);
                    self.$setState({
                        Name: geofence.Name,
                        //Radius: geofence.Radius,
                        Address: geofence.Address,
                        ActiveState: geofence.State ? true : false,
                        AssetList: assetList,
                        AlarmType: Protocol.Helper.getGoefenceAlarmTypes(geofence.Alerts),
                        //GeofenceTypes: Protocol.Helper.getGoefenceAlarmTypes(geofence.GeoType),
                        //GeofenceType: geofence.GeoType,
                        ContactList: geofence.ContactList,
                        Share: geofence.Share ? true : false,
                    });

                    if (geofence.SelectedAssetList && geofence.SelectedAssetList.length) {
                        let tempAssetArray = [];
                        for (var i = geofence.SelectedAssetList.length - 1; i >= 0; i--) {
                            tempAssetArray.push(geofence.SelectedAssetList[i].IMEI);
                        }
                        self.updateGroupMarkers(tempAssetArray);
                    }

                }

                self.getEmailList();

                assetsEl.on('change', function(){
                    self.updateGroupMarkers($$(this).val());
                });

                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){
                                  MapTrack.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(MapTrack);
                              MapTrack.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 });
                    });
                });

                formEl.on('submit', function(e){
                    e.preventDefault();

					

                    if (self.GeofenceLayer) {
                        var userInfo = self.$app.methods.getFromStorage('userInfo');
                        //var latlng = self.GroupRadius.getLatLng();

                        var selectedAssetsArr = assetsEl.find('option:checked');
                        var selectedAssetIds = '';
                        var ignoreDaysArr = formEl.find('[name="IgnoreDays"]').val();
                        for (var i = selectedAssetsArr.length - 1; i >= 0; i--) {
                            selectedAssetIds += ','+$$(selectedAssetsArr[i]).data('id');
                        }
                        if (selectedAssetIds) {
                            selectedAssetIds = selectedAssetIds.substr(1);
                        }
                        /*console.log(formEl.find('[name="NotifyEmails"]').val());
                              console.log(formEl.find('[name="NotifyEmails"]').val().toString());*/

                        var url = API_URL.GEOFENCE_ADD;

                        var data = {
                            MinorToken: userInfo.MinorToken,
                            MajorToken: userInfo.MajorToken,

                            Name: formEl.find('[name="Name"]').val(),
                            Lat: 0,
                            Lng: 0,
                            Radius: 0,
                            Alerts: formEl.find('[name="AlarmType"]').val().toString(),
                            Address: formEl.find('[name="GeoAddress"]').val(),
                            AssetCodes: selectedAssetIds,
                            ContactCodes: formEl.find('[name="NotifyEmails"]').val().toString(),

                            AlertConfigState: formEl.find('[name="ActiveState"]').is(":checked") ? 1 : 0,

                            Inverse: formEl.find('[name="IgnoreBetweenState"]').is(":checked") ? 1 : 0,
                            BeginTime: moment(formEl.find('[name="PickerStart"]').val(), 'HH:mm').utc().format('HH:mm:ss'),
                            EndTime: moment(formEl.find('[name="PickerEnd"]').val(), 'HH:mm').utc().format('HH:mm:ss'),

                            Share: formEl.find('[name="Share"]').is(":checked") ? 1 : 0,

                            DelayTime: 0,
                            GeoType: 1, //circle
                            CycleType: 3, // NONE = 0, TIME = 1, DATE = 2, WEEK = 3

                        };

                        if (self.GeofenceLayer.options.radius) { //circle
                            var latlng = self.GeofenceLayer.getLatLng();

                            data.Lat = latlng.lat;
                            data.Lng = latlng.lng;
                            data.Radius = parseInt(self.GeofenceLayer.getRadius(),10);
                        }else{ // else Polygon
                            var latlngs = self.GeofenceLayer.getLatLngs();
                            if (latlngs.length === 1 && $.isArray(latlngs[0]) && latlngs[0].length > 1) {
                                latlngs=latlngs[0];
                                if (latlngs[0].lat !== latlngs[latlngs.length-1].lat || latlngs[0].lng !== latlngs[latlngs.length-1].lng){
                                    latlngs.push(latlngs[0]);
                                }
                            }
                            if (!self.isClockwise(latlngs)){
                                latlngs = latlngs.reverse();
                            }
                            data.GeoType = 2;

                            var latlngArry=[];
                            for(var i=0;i<latlngs.length;i++){
                                latlngArry.push(latlngs[i].lng+" "+latlngs[i].lat);
                            }
                            data.GeoPolygon = "POLYGON(("+latlngArry.join(',')+"))";

                            data.Lat = latlngs[0].lat;
                            data.Lng = latlngs[0].lng;
                        }

                        if (ignoreDaysArr && ignoreDaysArr.length) {
                            data.Days = ignoreDaysArr.toString();
                        }

                        if (self.Code) {
                            data.Code = self.Code;
                            url = API_URL.GEOFENCE_EDIT;
                        }

                        //console.log(data);

                        self.saveGeofence(data, url);
                    }else{
                        self.$app.methods.customDialog({text:LANGUAGE.PROMPT_MSG0102});
                    }




                    return false;
                });



            },
            pageBeforeIn: function(e, page){
                var self = this;
                let fabViewAll = $$('.fab-viewall');
                let fabMapSettings = $$('.fab-map-settings');


                MapTrack.removeLayer(AllMarkersGroup);
                if (fabViewAll && !fabViewAll.hasClass('disabled')) {
                    fabViewAll.addClass('disabled');
                }

                self.$app.utils.nextFrame( () =>{
                    if (fabMapSettings && !fabMapSettings.hasClass('disabled')) {
                        fabMapSettings.addClass('disabled');
                    }
                });

                let bottomAssetDetailsWidget = $$('.asset-details-widget');
                bottomAssetDetailsWidget.addClass('display-none')
            },
            pageBeforeOut: function(e, page){
                var self = this;

                MapTrack.pm.disableGlobalEditMode(); // fix to dlose edit mode if it not closed when saving
                MapTrack.pm.removeControls();
                MapTrack.off('pm:drawstart', self.pmDrawStart);
                MapTrack.off('pm:create', self.pmCreate);
                if (self.GeofenceLayer) {
                    MapTrack.removeLayer(self.GeofenceLayer);
                }
                if (self.AddressMarker){
                    MapTrack.removeLayer(self.AddressMarker);
                }

                let bottomAssetDetailsWidget = $$('.asset-details-widget');
                bottomAssetDetailsWidget.removeClass('display-none')
            },
            pageAfterOut: function (e, page) {
                var self = this;
                let fabViewAll = $$('.fab-viewall');

                if (self.GroupMarkers) {
                    self.GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(self.GroupMarkers);
                    }
                }


                if (MapTrack && !MapTrack.hasLayer(AllMarkersGroup)) {
                    if (AllMarkersGroup.getBounds().isValid()) {
                        MapTrack.fitBounds(AllMarkersGroup.getBounds(),{padding:[16,16]});
                        AllMarkersGroup.addTo(MapTrack);
                    }

                    if (fabViewAll && fabViewAll.hasClass('disabled')) {
                        fabViewAll.removeClass('disabled');
                    }
                    /*if (fabMapSettings && fabMapSettings.hasClass('disabled')) {
	                    fabMapSettings.removeClass('disabled');
	                }   */
                }

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

            },
			
			

        }
    };
</script>