mapApp.controller('mapCtrl', function ($scope, $state, $cordovaGeolocation, $ionicLoading, $cordovaActionSheet,
	Users, dataHtml, ivhTreeviewMgr, Maps, Appointments,Customerfiles, Callaheads, $cordovaFileTransfer, //
	$cordovaImagePicker, $ionicScrollDelegate, $ionicActionSheet, $window, $timeout,$cordovaToast) {
    var options = { timeout: 10000, enableHighAccuracy: true };

    $scope.dataMapHtml = {};

    $scope.searchMapInfo = {};
    $scope.searchMapInfo.fieldworker = [];
    $scope.searchMapInfo.arrFieldworkerId = [];

    $scope.today = moment().format('YYYY-MM-DD');
    $scope.searchMapInfo.fromDate = $scope.today;
    $scope.searchMapInfo.toDate = $scope.today;

    $scope.showSeeMore = false;
    $scope.dataTreeLoad = false;
    $scope.setTime = false;
    $scope.totalAppoinment = 0;

    $scope.searchAppDetail = {};
    $scope.viewStarting = false;
    $scope.firstLoadMap = true;
    $scope.setCenter = true;

    $scope.icon = { url: "resources/images/icons/marker.png", scaledSize: new google.maps.Size(20, 20) };
    $scope.iconTodayPin = { url: "resources/images/icons/bluepin.png", scaledSize: new google.maps.Size(40, 40) };

    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/map/filterAppPopup.tpl').success(function (results) {
            $scope.dataMapHtml.filterAppPopup = results;
            dataHtml.getTemplate('templates/dashboard/map/miniAppDetailView.tpl').success(function (results) {
                $scope.dataMapHtml.miniAppDetailView = results;
                dataHtml.getTemplate('templates/dashboard/map/listAppointment.tpl').success(function (results) {
                    $scope.dataMapHtml.listAppointment = results;
                    $scope.loadTreeDepart();
                });
            });
        });
    }
    $scope.loadTreeDepart = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        if (!$scope.dataTreeLoad) {
            Users.getUsersByDepart().success(function (data) {
                $('.f.tblloader').hide();
                $scope.filterClientdata = data;
                $scope.isbuildtree = true;
                $scope.dataTreeLoad = true;
                if ($scope.isbuildtree) {
                    $scope.createStructTreeDepart();
                    $scope.isbuildtree = false;
                }
            });
        }
    };

    $scope.createStructTreeDepart = function () {
        if ($scope.isbuildtree) {
            $scope.addresschecked = [];
            var depart = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "name", "departmentId", 'usersName', 'id'), {
                    label: currentObject.name,
                    id: currentObject.userId,
                    uid: "level_" + currentObject.userId + "_" + currentObject.departmentId,
                    level: "1"
                });
            }), function (item, key, depart) {
                return item.name;
            });
            $scope.usersFill = _.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "name", "departmentId", 'usersName', 'id'), {
                    label: currentObject.usersName,
                    id: currentObject.userId,
                    uid: currentObject.departmentId + "_" + currentObject.userId,
                    level: "2"
                });
            });
            var depart = _.each(depart, function (item) {
                usersOfDepart = _.where($scope.usersFill, {
                    departmentId: item.departmentId
                });
                item.children = usersOfDepart;
                return item;
            });
            $scope.stuff0 = [{
                label: 'Select All',
                level: "0",
                children: depart
            }];
            ivhTreeviewMgr.selectAll($scope.stuff0, true);
            $scope.searchMapInfo.fieldworker = _.where($scope.usersFill, {
                selected: true
            });
            $scope.getMapInfo();
        }
    }

    $scope.changeDepartGetFieldWokerId = function () {
        $scope.searchMapInfo.fieldworker = _.where($scope.usersFill, {
            selected: true
        });
    }

    $scope.changStarting = function (value) {
        $scope.viewStarting = value;
    }

    $scope.getMapInfo = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.searchMapInfo.from_date = moment($scope.searchMapInfo.fromDate).format('MM/DD/YYYY');
        $scope.searchMapInfo.to_date = moment($scope.searchMapInfo.toDate).format('MM/DD/YYYY');

        $scope.searchMapInfo.arrFieldworkerId = [];
        _.each($scope.searchMapInfo.fieldworker, function (value) {
            $scope.searchMapInfo.arrFieldworkerId.push(value.id);
        });
        $scope.searchMapInfo.viewStarting = $scope.viewStarting;
        Maps.getPaging($scope.searchMapInfo).success(function (data) {
            $scope.dataStartingLocation = data.dataStarting;
            $scope.dataListApp = data.data;
            $scope.totalAppoinment = $scope.dataListApp.length;
            $scope.dataListAppSort = [];
            if ($scope.searchMapInfo.from_date == $scope.searchMapInfo.to_date) {
                $scope.dataListAppSort = _.sortBy(_.sortBy($scope.dataListApp, 'arrivalwindow'), 'endarrivalwindow');
            }
            else {
                _.each($scope.dataListApp, function (item) {
                    _.extend(item, {
                        dateToSort: moment(item.dateofappt, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD')
                    });
                });
                $scope.arrDay = _.uniq(_.pluck(_.sortBy($scope.dataListApp, 'dateofappt'), "dateToSort"));
                _.each($scope.arrDay, function (item) {
                    $scope.oneDay = _.where($scope.dataListApp, { dateToSort: item });
                    if ($scope.oneDay.length > 0) {
                        $scope.appAfterSortPerDay = _.sortBy(_.sortBy($scope.oneDay, 'arrivalwindow'), 'endarrivalwindow');
                        _.each($scope.appAfterSortPerDay, function (item) {
                            $scope.dataListAppSort.push(item);
                        });
                    }

                });
            }
            $scope.addressToMap($scope.dataListAppSort, $scope.dataStartingLocation);
        });
    };
    $scope.addressToMap = function (dataAppMap, dataStartingLocationMap) {
        $cordovaGeolocation.getCurrentPosition(options).then(function (position) {
            $scope.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var myLatLng = { lat: -25.363, lng: 131.044 };
            var mapOptions = {
                center: myLatLng,
                zoom: 13,
                mapTypeControl: false,
                fullscreenControl: false,
                //styles: [{ "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#e0efef" }] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "hue": "#1900ff" }, { "color": "#c0e8e8" }] }, { "featureType": "road", "elementType": "geometry", "stylers": [{ "lightness": 100 }, { "visibility": "simplified" }] }, { "featureType": "road", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit.line", "elementType": "geometry", "stylers": [{ "visibility": "on" }, { "lightness": 700 }] }, { "featureType": "water", "elementType": "all", "stylers": [{ "color": "#7dcdcd" }] }]
            };
            $scope.$broadcast('scroll.refreshComplete');
            $scope.objMapFromMap = new google.maps.Map(document.getElementById("map"), mapOptions);
            $scope.setTime = true;
            var bounds = new google.maps.LatLngBounds();
            for (var i = 0; i < dataAppMap.length; i++) {
                var position = new google.maps.LatLng(dataAppMap[i].lat, dataAppMap[i].long);
                if (dataAppMap[i].dataInfor.status != 'Pending') {

                    $scope.etaTitle = dataAppMap[i].dataInfor.eta != null ? dataAppMap[i].dataInfor.eta : "N/A";
                    $scope.etcTitle = dataAppMap[i].dataInfor.etc != null ? dataAppMap[i].dataInfor.etc : "N/A";
                    $scope.wapTitle = dataAppMap[i].dataInfor.wap != null ? dataAppMap[i].dataInfor.wap : "N/A";

                    $scope.pinTitle = $scope.etaTitle + ' | ' + $scope.etcTitle + ' | ' + $scope.wapTitle;

                    if (dataAppMap[i].dataInfor.status == 'EnRoute' && parseInt(dataAppMap[i].callahead_id) != NoCAId) {
                        $scope.statusesColor = differentNoCaAndRouteColor;
                    }
                    else {
                        $scope.statusesColor = dataAppMap[i].statusesColor;
                    }
                }
                else {
                    $scope.statusesColor = dataAppMap[i].statusesColor;
                    $scope.pinTitle = 'No available information';
                }

                if (moment(dataAppMap[i].dateofappt, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY') == moment().format('MM/DD/YYYY')) {
                    var todayPin = '<?xml version="1.0" encoding="UTF-8"?>' +
                    '<svg viewBox="0 0 2481 2073" version="1.1" width="50px" height="50px" xmlns="http://www.w3.org/2000/svg">' +
                    '<g fill-rule="evenodd">' +
                    '<path d="m730.94 1839.6c-38.766-190.3-107.12-348.67-189.9-495.44-61.407-108.87-132.54-209.36-198.36-314.94-21.972-35.243-40.934-72.476-62.047-109.05-42.216-73.137-76.444-157.94-74.269-267.93 2.125-107.47 33.208-193.68 78.03-264.17 73.719-115.94 197.2-210.99 362.88-235.97 135.47-20.424 262.48 14.082 352.54 66.748 73.596 43.038 130.6 100.53 173.92 168.28 45.22 70.716 76.36 154.26 78.97 263.23 1.3401 55.83-7.7999 107.53-20.68 150.42-13.03 43.409-33.99 79.695-52.64 118.45-36.41 75.659-82.05 144.98-127.86 214.34-136.44 206.61-264.5 417.31-320.58 706.03z" fill="' + dataAppMap[i].userColor + '" stroke-miterlimit="10" stroke-width="37"/>' +
                    '<circle cx="729.55" cy="651.05" r="183.33" fill="' + $scope.statusesColor + '"/>' +
                    '</g>' +
                    '</svg>';
                    marker = new google.maps.Marker({
                        map: $scope.objMapFromMap,
                        position: position,
                        appId: dataAppMap[i].id,
                        icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(todayPin) },
                        title: $scope.pinTitle,
                    });
                }
                else {
                    var svg = '<?xml version="1.0"?>' +
                    '<svg width="36.011px" height="45.16px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 36.011 45.16">' +
                    '<path fill="' + dataAppMap[i].userColor + '" d="M17.758,0.375L17.454,0L0.184,22.91L0,23.153l18.477,21.906l0.084,0.101L35.824,21.96l0.188-0.241 L17.758,0.375z M17.758,0.375"/>' +
                    '<circle fill="' + $scope.statusesColor + '" cx="18.006" cy="22.581" r="7.247"/>' +
                    '</svg>';
                    marker = new google.maps.Marker({
                        map: $scope.objMapFromMap,
                        position: position,
                        appId: dataAppMap[i].id,
                        icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg) },
                        title: $scope.pinTitle
                    });
                }

                dataAppMap[i].marker = marker;
                with ({ mark: marker }) {
                    google.maps.event.addListener(mark, 'click', function () {
                        x = 0
                        setTimeout(function () {
                            if (x == 0) {
                                $scope.eventOnAppMarker(mark.appId, 'click', mark);
                            };
                        }, 300);
                    });
                    google.maps.event.addListener(mark, 'dblclick', function () {
                        x = 1
                        $scope.viewAppDetail(mark.appId)
                    });
                }
                bounds.extend(marker.position);
            }

            for (var j = 0; j < dataStartingLocationMap.length; j++) {
                var position = new google.maps.LatLng(dataStartingLocationMap[j].lat, dataStartingLocationMap[j].long);
                var makerStarting = new google.maps.Marker({
                    map: $scope.objMapFromMap,
                    position: position,
                    icon: $scope.icon,
                    title: dataStartingLocationMap[j].first_name + ' ' + dataStartingLocationMap[j].last_name + ' ' + moment(dataStartingLocationMap[j].from_hour, 'HH:mm:ss').format("h:mm A") + '-' + moment(dataStartingLocationMap[j].to_hour, 'HH:mm:ss').format("h:mm A")
                });

                with ({ mark: makerStarting }) {
                    google.maps.event.addListener(mark, 'click', function () {
                        $cordovaToast.showLongCenter(mark.title);
                    });
                }

                bounds.extend(makerStarting.position);
            }

            if (dataAppMap.length > 0 || dataStartingLocationMap.length > 0) {
                $scope.objMapFromMap.fitBounds(bounds);
            }

            if (dataAppMap.length == 1 && !dataStartingLocationMap.length > 0) {
                var positionToCenter = new google.maps.LatLng(dataAppMap[0].lat, dataAppMap[0].long);
                $scope.objMapFromMap.setCenter(positionToCenter);
            }
            if (!dataAppMap.length > 0 && dataStartingLocationMap.length == 1) {
                var positionToCenterStarting = new google.maps.LatLng(dataStartingLocationMap[0].lat, dataStartingLocationMap[0].long);
                $scope.objMapFromMap.setCenter(positionToCenterStarting);
            }
            $ionicLoading.hide();
        }, function (error) {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Can not get current location !');
        });
}

$scope.beforesetCenterMaker = function (data) {
    if($scope.setCenter){
        $scope.setCenterMaker(data);
    }

}


$scope.setCenterMaker = function (data) {
    $scope.closeTarget('#popupListMapAppointment');
    var position = new google.maps.LatLng(data.lat, data.long);
    $scope.objMapFromMap.setCenter(position);
    data.marker.setAnimation(google.maps.Animation.BOUNCE);
    setTimeout(function () { data.marker.setAnimation(null); }, 2000);
}

$scope.eventOnAppMarker = function (id, action, marker) {
    $scope.searchAppDetail.id = id;
    $scope.searchAppDetail.action = action;
    Maps.clickOnAppMarker($scope.searchAppDetail).success(function (data) {
        if (action == 'click') {
            $scope.dataAppViewDetail = data.data[0];
            $scope.shortOfficeNote = $scope.dataAppViewDetail.officeNote;
                //if ($scope.dataAppViewDetail.officeNote != null && $scope.dataAppViewDetail.officeNote.length > 160) {
                //    $scope.showSeeMore = true;
                //    $scope.shortOfficeNote = $scope.dataAppViewDetail.officeNote.substring(0, 160);
                //}
                //else {
                //    $scope.showSeeMore = false;
                //    $scope.shortOfficeNote = $scope.dataAppViewDetail.officeNote;
                //}

                $scope.dataAppViewDetail.nothomeutil = moment($scope.dataAppViewDetail.nothomeutil, 'HH:mm:ss').format("h:mm A");
                $scope.showTarget('#popupViewAppDetail');
            }
            else {
                if (data.data.status == 'Pending') {
                    $scope.infowindow = new google.maps.InfoWindow({
                        content: 'No available information'
                    });
                }
                else {
                    $scope.infowindow = new google.maps.InfoWindow({
                        content: data.data.eta + ' | ' + data.data.etc + ' | ' + data.data.wap
                    });
                }

                $scope.infowindow.open($scope.objMapFromMap, marker);
            }
        });
}

$scope.viewAppDetail = function (id) {
    $scope.setCenter = false;
    $scope.paramsToApp = {};
    $scope.paramsToApp.id = id;
    $scope.$broadcast('openAppDetailFromMap', $scope.paramsToApp);
    $timeout(function() {
        $scope.setCenter = true;
    }, 500);
}

$scope.$on('refreshMap', function (event, args) {
    $scope.closeTarget('#scheduleDetailEdit');
    $scope.getMapInfo();
});

$scope.submitFormFieldWorker = function () {
    $scope.getMapInfo();
    $scope.closeTarget('#popupMapFilter');
};

$scope.$watch('searchMapInfo.fromDate', function (value) {
    if ($scope.setTime) {
        $scope.getMapInfo();
    }
})
$scope.$watch('searchMapInfo.toDate', function (value) {
    if ($scope.setTime) {
        $scope.getMapInfo();
    }
})

$scope.refreshPage = function() {
    $scope.getMapInfo();
}


$scope.$on('getJsonData', function (event, args) {
    var jsondata = args.data;
    var index = _.findIndex(jsondata,{roletree_id:'46'});
    var index1 = _.findIndex(jsondata[index].child,{roletree_id:'49'});
    if(jsondata[index].child[index1].check){
        $scope.viewFilterApp = jsondata[index].child[index1].child[0].check;
    }else{
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
    }
});
if (page == "map.html") $scope.renderTemplateData();
})
