angular.module('notetasksCtrl', []).controller('notetasksController', function($cordovaToast, $ionicLoading, $ionicScrollDelegate, //
    $scope, $http, $window, $interval, Login, Notetasks, Users, Notetasktypes, $location, dataHtml, $timeout) {
    noteTaskScope = $scope;
    $scope.currentPage = 1;
    var pager = localStorage.getItem('notetasks_pagesize');
    $scope.itemsPerPage = pager ? pager : 5;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchNotetasks = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: ""
    };
    $scope.loaded = false;
    $scope.initialAddFollower = [];
    /*$scope.getUsers = function(){
        User.get().success(function(data){
            $scope.users= data;
        });
    }
    $scope.getUsers();
    */
    $scope.getUsers = function() {
        Users.getSelect().success(function(data) {
            $scope.allUser = data;
            $scope.allUser.forEach(function(itm) {
                itm.screen_name = itm.first_name + ' ' + itm.last_name + '-' + itm.positiontitles_name;
                itm.name = itm.nameWithpos;
            })
            $scope.loaded = true;
        });
    }
    $scope.getNotetasktypes = function() {
        $ionicLoading.show({ template: templateLoading });
        Notetasktypes.getSelect().success(function(data) {
            if (!startpage) ionicLoading.hide();
            $scope.notetasktypes = data;
            $scope.getUsers();
        });
    }
    $scope.getNotetasktypes();
    $scope.getNotetasks = function() {
        Notetasks.getPaging($scope.searchNotetasks).success(function(data) {
            $scope.notetasks = data.data;
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchNotetasks.rows;
            notetasks_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            $('#tableNotetasks').tableRespondsive();
        });
    };
    $scope.loadDataSelect = function() {
        // if(!$scope.loaded){
            $scope.getNotetasktypes();
        // }
    }
    $scope.searchChanged = function() {
        $scope.getNotetasks();
    }
        /*$scope.getSelectNotetasks = function(){
            Notetasks.getSelect().success(function(data){
                $scope.selectNotetasks = data;
            });
        }
        $scope.getSelecNotetasks();*/
        /*
        xem demo upload file tai day:
        http://jsfiddle.net/danialfarid/1m6fn6re/
        $scope.upload = function (file) {
            Upload.upload({
                url: '/todo',
                fields: $scope.todoData,
                file: file
            }).progress(function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
            }).success(function (data, status, headers, config) {
                console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
            }).error(function (data, status, headers, config) {
                console.log('error status: ' + status);
            })
        };
        */
        $scope.sizeChanged = function() {
            $scope.searchNotetasks.rows = $scope.entryLimit;
            notetasks_pagesize.val($scope.searchNotetasks.rows);
            localStorage.setItem('notetasks_pagesize', $scope.searchNotetasks.rows);
            $scope.searchNotetasks.current_page = 1;
            $scope.getNotetasks();
        }
        $scope.pageChanged = function() {
            console.log($scope.currentPage);
            $scope.searchNotetasks.current_page = $scope.currentPage;
            $scope.getNotetasks();
        };
    //$scope.getNotetasks();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addNotetasksData = {};
    $scope.addNotetasksData.status = 1;
    // edit by haudao
    $scope.validateForm = function(formValidate, style) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        };
        if (style == 'Add') {
            $scope.createNotetasks();
        } else {
            $scope.updateNotetasks();
        }
    }
        // end <i class="el el-edit"></i>
        $scope.createNotetasks = function() {
            $scope.addNotetasksDataCopy = angular.copy($scope.addNotetasksData);
            $ionicLoading.show({
                template: templateLoading
            });
            $startTimeCheck = moment($scope.addNotetasksDataCopy.from_time, 'hh:mmA').format('HH:mm:ss');
            $endTimeCheck = moment($scope.addNotetasksDataCopy.to_time, 'hh:mmA').format('HH:mm:ss');
            if ($startTimeCheck > $endTimeCheck || $startTimeCheck == $endTimeCheck) {
                $scope.addNotetasksDataCopy.to_time = '';
                $ionicScrollDelegate.$getByHandle('scrollAddNotesTask').scrollBottom();
                $ionicLoading.hide();
                $cordovaToast.showLongTop('End time must be greater than start time');
                return;
            }
            if ($scope.addNotetasksDataCopy.fieldworker.length > 0) {
                $scope.addNotetasksDataCopy.from_time = $startTimeCheck;
                $scope.addNotetasksDataCopy.to_time = $endTimeCheck;
                $scope.addNotetasksDataCopy.date = $('#frmAddNotesTask input[name="date"]').val();
                $scope.addNotetasksDataCopy.show_on_schedule = $scope.addNotetasksDataCopy.show_on_schedule == true ? true : false;
                Notetasks.save($scope.addNotetasksDataCopy).success(function(data) {
                    $ionicLoading.hide();
                    if (data.status) {
                        closeTarget('#popupAddScheduleNote');
                        $scope.loadAppointmentByDay($("#scheduleDayValue").val());
                        $scope.addNotetasksData = {};
                        $scope.addNotetasksData.fieldworker = [];
                        $scope.addNotetasksData.show_on_schedule = true;
                        $scope.initialAddFollower = [];
                        $scope.Input_value = {};
                        $cordovaToast.showLongTop(data.msg);
                    //$scope.getNotetasks();
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            });
            } else {
                $ionicLoading.hide();
                $cordovaToast.showLongTop('Field worker Not Null');
            }
        }
        $scope.$on('editNotetasksFormMyschedule', function(event, args) {
            $scope.editNotetasks(args.id);

        });
        $scope.editNotetasksData = {};
        $scope.editNotetasks = function(id) {
            console.log(id);
            $ionicLoading.show({ template: templateLoading });
        // if (page == 'myschedule.html') {
        //     $timeout(function() {
        //         dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupTaskNoteEditmodal.tpl').success(function(results) {
        //             $scope.dataMyAppHtml.editTaskNote = results;
        //         })
        //     }, 500)
        // }
        $scope.initialEditFollower = [];
        Notetasks.show(id).success(function(data) {
            $ionicLoading.hide();
            showTarget('#popupEditScheduleNote');
            $scope.notetasktypes = _.union($scope.notetasktypes, [data.notetasktype_data]);
            data.from_time = moment(data.from_time, 'HH:mm:ss').format('hh:mmA');
            data.to_time = moment(data.to_time, 'HH:mm:ss').format('hh:mmA');
            $scope.editNotetasksData = data;
            $scope.setValueNotesTaskType($scope.editNotetasksData.notetasktype_data.id);
            $scope.setValueStatus($scope.editNotetasksData.status);
            $scope.initialEditFollower = $scope.editNotetasksData.fieldworker.id;
        });
    }
    $scope.updateNotetasks = function($whatfor) {
        var id = $scope.editNotetasksData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        var check = validateTime($scope.editNotetasksData.from_time, $scope.editNotetasksData.to_time);
        if (!check.status) {
            $scope.editNotetasksData.to_time = '';
            $ionicScrollDelegate.$getByHandle('scrollEditNotesTask').scrollBottom();
            $ionicLoading.hide();
            $cordovaToast.showLongTop('End time must be greater than start time');
            return;
        }
        $scope.editNotetasksData.from_time = check.start;
        $scope.editNotetasksData.to_time = check.end;
        $scope.editNotetasksData.date = $('#frmEditNotesTask input[name="date"]').val();
        Notetasks.update(id, $scope.editNotetasksData).success(function(data) {
            closeTarget('#popupEditScheduleNote');
            $ionicLoading.hide();
            page == 'myschedule.html' ? $scope.getSchedule() : $scope.loadAppointmentByDay($("#scheduleDayValue").val());
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.deleteNotetasksData = {};
    $scope.deleteNotetasksData = {};
    $scope.confrimNotetasks = function(id, title, content) {
        $scope.deleteNotetasksData = {
            id: id
        };
        var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
            messageType: 'warning',
            titleIcon: 'remove',
            overlayTransparent: .75
        }, function() {
            $scope.deleteNotetasks(id, confirm);
        });
    }
    $scope.deleteNotetasks = function(id, confirm) {
        Notetasks.destroy(id).success(function(data) {
            $scope.deleteNotetasksData = {};
            if (data.status) {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            } else {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            }
            $scope.getNotetasks();
        });
    }
    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                $scope.getNotetasks();
                var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }
        });
    }
    $scope.logout = function() {
        return Login.logout().success(function(data) {
            $window.location.href = url_login;
        });
    }
    $scope.checkLogin = function() {
        return Login.checkLogin().success(function(data) {
            if (data.status == false) {
                $window.location.href = url_login;
            } else {
                $scope.getUserLogin();
            }
        });
    }
    if ((window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'notetasks.html') {
        $scope.checkLogin();
        stopTime = $interval($scope.checkLogin, time_refresh);
    }
    $scope.addNotetasksData.fieldworker = [];
    $scope.fieldWorker = [];
    $scope.refresFieldWorker = function(search) {
        if (search.length > 0) {
            var params = {
                search: search
            };
            Users.getSelect2(params).success(function(data) {
                var diff = differentArray(data, $scope.addNotetasksData.fieldworker);
                $scope.fieldWorker = diff;
            })
        }
    };
    $scope.fieldWorkerEdit = [];
    $scope.refresFieldWorkerEdit = function(search) {
        if (search.length > 0) {
            var params = {
                search: search
            };
            Users.getSelect2(params).success(function(data) {
                var diff = differentArray(data, $scope.editNotetasksData.fieldworker);
                $scope.fieldWorkerEdit = diff;
            })
        }
    };
    // edit by haudao
    $scope.$on('send_fieldWorkerId', function(event, data) {
        $scope.initialAddFollower = [parseInt(data.id)];
        $scope.Input_value.notesTaskType = "";
        // console.log();
    });
    $scope.$on('send_taskNotesId', function(event, data) {
        $scope.editNotetasks(data.id);
        // console.log();
    });
    $scope.Input_value = {};
    $scope.setValueNotesTaskType = function(typeId) {
        $scope.Input_value.notesTaskType = "";
        var index = _.findLastIndex($scope.notetasktypes, {
            id: typeId
        });
        if (index >= 0) $scope.Input_value.notesTaskType = $scope.notetasktypes[index].name;
    }
    $scope.setValueStatus = function(statusId) {
        $scope.Input_value.status = "";
        switch (parseInt(statusId)) {
            case 1:
            $scope.Input_value.status = "Pending";
            break;
            case 2:
            $scope.Input_value.status = "Enroute";
            break;
            case 3:
            $scope.Input_value.status = "Working";
            break;
            case 4:
            $scope.Input_value.status = "Finished";
            break;
        }
    }
    $scope.autocompleteList = {};
    $scope.filterFollow = function(query) {
        var returnValue = {
            items: []
        };
        var listIdArray = [];
        if (Array.isArray($scope.autocompleteList.refferedFollower)) {
            listIdArray = $scope.autocompleteList.refferedFollower;
        } else {
            listIdArray = [$scope.autocompleteList.refferedFollower];
        }
        var params = { search: query };
        Users.getSelect2(params).success(function(data) {
            $scope.allUser = data;
            $scope.allUser.forEach(function(item) {
                if (listIdArray.indexOf(item.id) < 0) {
                    if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        returnValue.items.push(item);
                    } else if (item.id.toString().indexOf(query) > -1) {
                        returnValue.items.push(item);
                    }
                }
            });

        })


        return returnValue;
    };
    $scope.initialEditFollower = [];
    $scope.setValueForFollower = function(modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            if (parseInt($scope.allUser[i].id) == parseInt(modelValue)) {
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.onSelectFollower = function(callback, style) {
        if (style == 'Add') {
            if ($scope.addNotetasksData.fieldworker.indexOf(callback.item) < 0) $scope.addNotetasksData.fieldworker.push(callback.item);
            // console.log($scope.addNotetasksData.fieldworker);
        } else {
            $scope.editNotetasksData.fieldworker = { id: callback.item.id, name: callback.item.screen_name };
            // console.log($scope.editNotetasksData.fieldworker);
        }
    }
    $scope.onRemoveFollower = function(callback, style) {
        if (style == 'Add') {
            var index = $scope.addNotetasksData.fieldworker.indexOf(callback.item);
            $scope.addNotetasksData.fieldworker.splice(index, 1);
                // console.log($scope.addNotetasksData.fieldworker);
            } else {
                $scope.editNotetasksData.fieldworker = "";
                // console.log($scope.editNotetasksData.fieldworker);
            }
        }
        $scope.$on('sentFieldworkerId', function (event, args) {
            $scope.addNotetasksData.fieldworker = [];
            if(!args.fieldworker == ''){
                $scope.initialAddFollower = args.fieldworker;
            }      
            $scope.$emit('openPopupAddScheduleNote', {});
        });
        // end
    })
