<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
        <div class="page " data-name="asset-group"> <!-- 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="hidden" name="IMEI" value="{{IMEI}}">
                <input type="submit" id="submit-form" class="display-none" />
                <div class="list margin-top-0">
                    <ul>
                        <li>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-group"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG03}}</div>
                                    <div class="item-input-wrap">
                                        <input type="text" name="Name" placeholder="{{@global.LANGUAGE.ASSET_GROUPS_MSG10}}" value="{{Name}}" maxlength="200" required validate>
                                    </div>
                                </div>
                            </div>
                        </li>                                 

                        
                        
                   <!--  </ul>
                                   </div>
                   
                                   <div class="block-title">{{@global.LANGUAGE.ASSET_GROUPS_MSG05}}</div>
                                   <div class="list ">
                   <ul> -->
                        <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">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG13}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG093}}"></i></div>
                                    <div class="item-input-wrap">
                                        <!-- <input type="text" name="Name" placeholder="Asset name" value="{{Name}}" maxlength="200" required validate> -->
                                        <textarea name="Address" id="" placeholder="{{@global.LANGUAGE.ASSET_GROUPS_MSG06}}" maxlength="400" >{{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>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-radius"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG07}}</div>
                                    <div class="item-input-wrap">
                                        <input type="tel" name="Radius" placeholder="{{@global.LANGUAGE.ASSET_GROUPS_MSG07}}" value="{{Radius}}" class="only_numbers"  pattern="[0-9]*" data-error-message="{{@global.LANGUAGE.PROMPT_MSG024}}" maxlength="200"  required validate>
                                    </div>
                                </div>
                            </div>
                        </li>
                  
                    </ul>
                </div>

                <div class="block-title">{{@global.LANGUAGE.ASSET_GROUPS_MSG08}}</div>
                <div class="list ">
                    <ul>
                        <li>
                            <a class="item-link smart-select smart-select-init custom-smart-select" 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}}">
                                <select name="Assets" multiple>
                                    {{#AssetList}}
                                        <optgroup label="{{Name}}" data-code="{{Code}}">
                                            {{#Assets}}
                                                <option value="{{IMEI}}" {{#if Selected}} 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>  
                    </ul>
                </div>
                
                <!-- <div class="block">
                    <div class="row">
                        <button type="submit" class="col button button-fill color-green elevation-2">{{@global.LANGUAGE.COM_MSG06}}</button>
                    </div>
                </div> -->
				
				
            </form>

        </div>
    </template>


<script>
  // script must return component object
    return {
        data: function () {
            var self = this;
            var ret = {
                Radius: 200
            };                  
            
            if (self.$route.params) {
                if (self.$route.params.code) {
                    var group = '';
                    var groupList = self.$app.methods.getFromStorage('groupList');
                    if (groupList && groupList.length) {                        
                        group = self.$app.methods.findObjectByKey(groupList, 'Code', self.$route.params.code);
                    }  
                    var assetList = self.$app.methods.getFromStorage('assetList');
                    var newAssetlist = [];

                    /*creating temprorary empty obj for sorting groups*/
                    var tempObjects = {
                        '000000': {
                            Name: LANGUAGE.ASSET_GROUPS_MSG11, //'Not in Group'
                            Code: '000000',
                            Assets: [],
                        }                            
                    };
                    for (var i = groupList.length - 1; i >= 0; i--) {                        
                        tempObjects[groupList[i].Code] = {
                            Name: groupList[i].Name,
                            Code: groupList[i].Code,
                            Assets: [],
                        };
                    }
                    
                    /*sorting asset by adding into corresponding object*/
                    $.each(assetList, function(key,val){
                        if (group && group.Assets && self.$app.methods.findObjectByKey(group.Assets, 'IMEI', key) ) {
                            val.Selected = true; 
                        }else{
                            val.Selected = false; 
                        }                         
                        if (val.GroupCode && tempObjects[val.GroupCode]) {                            
                            tempObjects[val.GroupCode].Assets.push(val);                            
                        }else{
                            tempObjects['000000'].Assets.push(val);
                        }
                    });

                    /*creaiting one array with groups and assets*/
                    $.each(tempObjects, function(key,val){
                        /*sorting in alphabet order*/
                        if (val.Assets && val.Assets.length) {
                            val.Assets.sort(function(a,b){
                                if(a.Name < b.Name) return -1;
                                if(a.Name > b.Name) return 1;
                                return 0;
                            }); 
                            newAssetlist.push(val);
                        } 
                    });
        
                    newAssetlist.sort(function(a,b){
                        if(a.Name < b.Name) return -1;
                        if(a.Name > b.Name) return 1;
                        return 0;
                    }); 
                    /*move not assigned asset to the top*/
                    newAssetlist.unshift(newAssetlist.splice(newAssetlist.findIndex(x => x.Code=='000000'), 1)[0]);           

                    if (group) {   
                        /*move current group assets to the top*/
                        newAssetlist.unshift(newAssetlist.splice(newAssetlist.findIndex(x => x.Code==group.Code), 1)[0]);
                        /*console.log(newAssetlist);*/

                        ret = group;
                        ret.PageTitle = LANGUAGE.ASSET_GROUPS_MSG00;

                        if (group.Tag) {                    
                            var temp = group.Tag.split(',');                            
                            if (temp && temp[0]) {
                                ret.lat = temp[0];
                            }
                            if (temp && temp[1]) {
                                ret.lng = temp[1];
                            }
                            if (temp && temp[2]) {
                                ret.Radius = temp[2];
                            }
                        }
                    }else{
                        ret.PageTitle = LANGUAGE.ASSET_GROUPS_MSG02;
                    }
                    ret.AssetList = newAssetlist;

                }else{
                    console.log('There is no id param');
                }
            }else{
                console.log('There is no params');
            }
            //console.log(ret);
            return ret;
        },
        methods: {
            saveGroup: function(data){
                var self = this;

                self.$app.preloader.show();
                self.$app.request.post(API_URL.EDIT_GROUP, data, function (result, xhr, status) { 
                                   
                    console.log(result);
                    if (result && result.MajorCode == '000') {
                        var promise1 = new Promise(function(resolve, reject) {
                            self.$app.methods.getNewAssetsData(resolve, reject);
                        });

                        promise1.then(function(value) {                            
                            self.$app.preloader.hide(); 
                            leftView.router.back();
                            self.$app.methods.initGroupAssetList();
                        });
                                 
                    }else if(result && result.MajorCode == '100' && result.MinorCode == '1003'){ 
                        self.$app.preloader.hide();            
                        self.$app.methods.customDialog({title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051});                        
                    }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 Asset details');                
                },
                'json');  
            },
            onMapClick: function (e) {
                var self = this;
                GroupRadius.setLatLng(e.latlng);   
                self.getPointsInCircle(GroupRadius);

                self.updateGeofenceAddress(e.latlng);     
            },
            updateGeofenceAddress: function(latlng){
                var self = this;
                app.progressbar.show();
                Protocol.Helper.getAddressByGeocoder(latlng,function(address){
                    setTimeout(function(){
                        app.progressbar.hide();        
                    },300);
                                
                    //self.$el.find('[name="Address"]').val(address); 
                    self.$setState({
                        Address: address,
                    });
                }); 
            },
            centeringMap: function(params){
                if (params && params.onlyAddress) {
                    MapTrack.fitBounds([GroupRadius.getBounds()],{padding:[16,16]});
                }else if(params && params.onlyAssets && GroupMarkers && GroupMarkers.getLayers().length > 0){
                    MapTrack.fitBounds([GroupMarkers.getBounds()],{padding:[16,16]});
                }else{
                    if (GroupMarkers && GroupMarkers.getLayers().length > 0) { 
                        MapTrack.fitBounds([GroupMarkers.getBounds(),GroupRadius.getBounds()],{padding:[16,16]});
                    } else{
                        MapTrack.fitBounds([GroupRadius.getBounds()],{padding:[16,16]});
                    }
                }
                    
            },	
            updateGroupMarkers: function (assets){
                var self = this;
                if (GroupMarkers) {
                    GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(GroupMarkers);
                    }        
                }
                GroupMarkers = L.markerClusterGroup({'maxClusterRadius':35,}); 
                if (assets && assets.length > 0) {
                    var point = '';
                    var markerData = '';
                    $.each(assets, function(key, value){   
                        point = ''; 
                        markerData = '';
                        if (POSINFOASSETLIST[value] && POSINFOASSETLIST[value].posInfo && POSINFOASSETLIST[value].posInfo.lat !== 0 && POSINFOASSETLIST[value].posInfo.lng !== 0) {               
                            point = L.marker([POSINFOASSETLIST[value].posInfo.lat,POSINFOASSETLIST[value].posInfo.lng], {icon: Protocol.MarkerIcon[0]}); 
                            markerData = POSINFOASSETLIST[value].Name ? POSINFOASSETLIST[value].Name : POSINFOASSETLIST[value].IMEI;
                            point.bindTooltip(markerData,{permanent: false, direction: 'right'});
                            point.addTo(GroupMarkers);
                        }
                    });
                    GroupMarkers.addTo(MapTrack);
                    
                    var radiusEl = self.$el.find('[name="Radius"]');
                    if (radiusEl && radiusEl.length && radiusEl.val()) {
                        self.centeringMap();
                    }else{
                        self.centeringMap({onlyAssets:true});
                    }
                } 
            },
            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(); 
                   

                    
                }       
            },	
          
        },
       
        on: {
            pageInit: function (e, page) { 
                var self = this;
   
                var latlng = [0, 0];
                var radius = 100;
                var formEl = page.$el.find('[name = "GroupEditForm"]');
                var searchAddressButton = page.$el.find('.input-search-button');
                var radiusEl = formEl.find('[name="Radius"]');
                var assetsEl = formEl.find('[name="Assets"]');     

                var fabViewAll = $$('.fab-viewall');               
                if (MapTrack){
                    MapTrack.removeLayer(AllMarkersGroup);                            
                    if (fabViewAll && !fabViewAll.hasClass('disabled')) {
                        fabViewAll.addClass('disabled');
                    }                        
                }
                                     


                if (self.lat && self.lng) {
                    latlng = [self.lat, self.lng];

                    self.updateGeofenceAddress({'lat': self.lat, 'lng':self.lng});
                }else if(self.Lat && self.Lng){
                    latlng = [self.Lat, self.Lng];

                    self.updateGeofenceAddress({'lat': self.Lat, 'lng':self.Lng});
                }
                if (self.Radius) {
                    radius = self.Radius;
                }

                GroupRadius = L.circle(latlng, {
                    color: '#AA5959',
                    fillColor: '#FF0000',
                    fillOpacity: 0.25,
                    radius: radius,
                }).addTo(MapTrack);                 

                if (self.Assets && self.Assets.length) {
                    var tempAssetArray = [];
                    $.each(self.Assets, function(key, val){
                        tempAssetArray.push(val.IMEI);
                    });
                    self.updateGroupMarkers(tempAssetArray);
                }

                radiusEl.on('change input', function(){
                    var value = this.value;
                    if (!value.match(/[^0-9]/g)) {
                       
                        GroupRadius.setRadius(value);
                        self.centeringMap();
                        self.getPointsInCircle(GroupRadius);
                    }       
                }); 

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

                searchAddressButton.on('click', function(e){ 
                    var valAddress = $$(this).siblings('[name="Address"]').val();
                    if (valAddress.length >= 3) {
                        app.progressbar.show();
                        Protocol.Helper.getLatLngByGeocoder(valAddress,function(latlng){   
                            app.progressbar.hide(); 
                            if (latlng) {                                
                                GroupRadius.setLatLng(latlng);
                                self.centeringMap({onlyAddress:true});                             
                            }else{
                                self.$app.methods.customNotification({                                    
                                    text: LANGUAGE.PROMPT_MSG008                                   
                                });
                            }
                        });
                    }                   
                });

                formEl.on('submit', function(e){
                    e.preventDefault();                    
                    var userInfo = self.$app.methods.getFromStorage('userInfo');
                    var latlngGroup = GroupRadius.getLatLng();
                    var data = {
                        MinorToken: userInfo.MinorToken,
                        MajorToken: userInfo.MajorToken,
                        
                        Code: formEl.find('[name="Code"]').val(),
                        Name: formEl.find('[name="Name"]').val(),
                        Lat: latlngGroup.lat,
                        Lng: latlngGroup.lng,
                        Radius: radiusEl.val(),
                        IMEIs: formEl.find('[name="Assets"]').val()
                    };
                    //console.log(data);
                    self.saveGroup(data);
                    return false;
                });       
            }, 
            pageAfterOut: function (e, page) {
                var self = this;
                MapTrack.off('click', self.onMapClick);
                if (GroupRadius) {
                    MapTrack.removeLayer(GroupRadius);
                }                
                if (GroupMarkers) {
                    GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(GroupMarkers);
                    }        
                }

                var fabViewAll = $$('.fab-viewall');
                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');
                    }
                }
                
            },    

        }
    };
</script>