var users_pagesize = $('#users_pagesize');
userApp.controller('userCtrl', function (dataHtml, $stateParams, $ionicScrollDelegate, $location, $scope, Users, $sce, $rootScope, $http, //
        $window, $cordovaFileTransfer, $timeout, $interval, Login, Departments, Newfeedtypes, $ionicLoading, $ionicPopup, $focusTest, //
        $cordovaDatePicker, Positiontitles, Appointmentgroups, Skills, Rooms, Roles, Users, $cordovaToast, $cordovaImagePicker, $cordovaKeyboard, //
        Departments, Supplieritems, Userdetails, Usercredentials, Listviews, Pipus,LocationService) {
    $scope.scrollHandle = function (positionID, style, offset) {
        // popup = 'popupEmployeeAdd';
        // if (style != 'Add') popup = 'popupEditEmployee';
        // // $("#" + popup + " .tab-link-4 .itm").removeClass('active');
        // // $("#" + popup + " .tab-link-4 div").eq(offset).addClass('active');
        // $location.hash(positionID); //set the location hash
        // var handle = $ionicScrollDelegate.$getByHandle('popup' + style);
        // handle.anchorScroll(true);
        // $timeout(function() {
        //     var top = handle.getScrollPosition().top - 30;
        //     // console.log(top);
        //     handle.scrollTo(0, top, false);
        // }, 500);
    }

    // $scope.activeTab = function(style) {
    //     popup = 'popupEditEmployee';
    //     if (style != 'Edit') popup = 'popupEmployeeAdd';
    //     var handle = $ionicScrollDelegate.$getByHandle('popup' + style);
    //     var top = handle.getScrollPosition().top;
    //     if (top < 1240) {
    //         $("#" + popup + " .tab-link-4 .itm").removeClass('active');
    //         $("#" + popup + " .tab-link-4 div").eq(0).addClass('active');
    //     } else if (top < 2180) {
    //         $("#" + popup + " .tab-link-4 .itm").removeClass('active');
    //         $("#" + popup + " .tab-link-4 div").eq(1).addClass('active');
    //     } else if (top < 2290) {
    //         $("#" + popup + " .tab-link-4 .itm").removeClass('active');
    //         $("#" + popup + " .tab-link-4 div").eq(2).addClass('active');
    //     } else {
    //         $("#" + popup + " .tab-link-4 .itm").removeClass('active');
    //         $("#" + popup + " .tab-link-4 div").eq(3).addClass('active');
    //     }
    // }

    // $cordovaKeyboard

    $scope.phone = {};
    $scope.info = {};
    $scope.openPopup = function (item, style) {
        if (style == 'info') {
            dataHtml.getTemplate('templates/dashboard/users/users/userPopupMoreInfomodal.tpl').success(function (results) {
                $scope.dataHtml.popupMoreInfo = results;
            });
            $scope.info = item;
            $scope.info.status = $scope.info.status == 1 ? true : false;
            appDialogToggle('open', '#popupEmployeeMoreInfo');
            return;
        }
        dataHtml.getTemplate('templates/dashboard/users/users/userPopupPhonemodal.tpl').success(function (results) {
            $scope.dataHtml.popupPhone = results;
        });
        $scope.selectedUserId.display_name = item.display_name;
        $scope.selectedUserId.fullname = item.first_name + ' ' + item.last_name;
        $scope.phone.cell_phone = item.cell_phone;
        $scope.phone.office_phone = item.office_phone;
        $scope.phone.extension_phone = item.extension_phone;
        $scope.showTarget('#popupEmployeePhone');
    }


    // searchUserHandle();
    // function searchUserHandle() {
    //     toggleDelegateHandle('#user_page', '.link-employee-search', '.user-search');
    //     toggleDelegateHandle('#user_page', '.user-search .search-type .btn-close', '.user-search');
    //     toggleDelegateHandle('#user_page', '.user-search .search-content .btn-close', '.user-search');
    //     closeOutsideHandle('.link-employee-search, .user-search', '.user-search');
    // }

    filterChatHandle();

    function filterChatHandle() {
        toggleDelegateHandle('#user_page', '.link-employee-filter', '.employee-filter');
        closeOutsideHandle('.link-employee-filter, .employee-filter', '.employee-filter');
    }

    $scope.itemEmployeeHandle = function (e) {
        $(e.currentTarget).toggleClass('selected').siblings().removeClass('selected');
        $(e.currentTarget).find('> .info-more').stop(true, true).slideDown(0).closest('.itm-employee').siblings().find('> .info-more').stop(true, true).slideUp(0);
    }
    withoutPopup = $scope;
    $scope.currentPage = 1;
    $scope.currentRoles = role;
    var pager = 25;
    $scope.itemsPerPage = pager ? pager : 25;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchUsers = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: "",
        showUserStatus : 'active'
    };
    $scope.userStatusShow = 'Active';
    $scope.addUsersData = {};
    $scope.addUsersData.assigned_vehicle = [];
    $scope.searchUsers.filterdeparment = null;
    $scope.searchUsers.filterposition = null;
    $scope.deparmentdata = null;
    $scope.dataFilterLoaded = false;
    $scope.searchUsers.sort_action = null;
    $scope.loaded = 0;
    $scope.counter = 0;
    $scope.coundown = 10;
    $scope.myTime = null;
    $scope.sortdepartment = {
        name: 'Oldest'
    };
    $scope.Positiontitles = {
        name: 'Oldest'
    };
    $scope.currentIdLogin = currentIdLogin;
    $scope.posTitle = [];
    $scope.departTitle = [];
    $scope.inprogress = false;
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.isStrategicDevelopment = isStrategicDevelopment;
    $scope.isSupportAssistant = isSupportAssistant;
    $scope.isOutsideSales = isOutsideSales;
    $scope.isInFieldSupervisor = isInFieldSupervisor;
    $scope.departmentId = departmentId;
    $scope.fdate = conFig.formatDate;
    $scope.positiontitles_by_department = [];
    $scope.rootAppGroups = [];
    $scope.rootSupplieritems = [];
    $scope.role = role;
    $scope.Input_value = {};
    $scope.autocompleteList = {};
    $scope.autocompleteList.dataUserAppointmentGroupsCreate = [];
    $scope.autocompleteList.dataUserAppointmentGroupsEdit = [];
    $scope.autocompleteList.dataUserSuppliersCreate = [];
    $scope.autocompleteList.dataUserSuppliersEdit = [];
    $scope.detail = 'close';
    $scope.onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
    $scope.activeRoles = false;
    $scope.dataHtml = {};
    $scope.check_usercredentials = false;
    $scope.displayValue = {};

    $scope.newfeedtypeArrId = {
        newfeedId: []
    };
    $scope.selectedUserId = {};

    $scope.addPipusData = {};
    $scope.currentPagePipus = 1;

    $scope.denyInactive = false;
    $scope.CurrentDate = {day: moment().format("DD"), month: moment().format("MMMM")};
    $scope.disabledSupSelect = false;
    $scope.holdValueAddress = {};
    $scope.holdValueAddress.addUserAddress = [];
    $scope.holdValueAddress.addUserStarLocation = [];
    $scope.holdValueAddress.addUserAssignLocation = [];

    $scope.openAddEmployeePopup = function () {
        $scope.openByGetTemplate('popupEmployeeAdd');
        $ionicLoading.show({template: templateLoading});
        withoutPopup.getDepartments(1);
        $scope.getSupplieritems();
        $scope.initialAppointmentGroup = [];
        $scope.initialSuppliersItem = [];
        $scope.Input_value = {};
        $scope.file = null;
        $scope.imageURI = "";
        $("#popupEmployeeAdd .tab-link-5 .itm").eq(0).addClass('active').siblings().removeClass('active');
        $scope.addUsersData.company_hiredate = '';
        $scope.addUsersData.company_startdate = '';
        $scope.addUsersData.last_review = '';
        $scope.addUsersData.next_review = '';
        $scope.addUsersData.last_raise = '';
        $scope.addUsersData.current_startdate = '';
        $scope.addUsersData.current_hiredate = '';

    }
    $scope.getSupplieritems = function () {
        Supplieritems.getSelect().success(function (data) {
            $scope.rootSupplieritems = data;
        })
    }
    $scope.getDepartments = function (_crud) {
        // document.getElementById("formAddUser").reset();
        // $ionicLoading.show({ template: templateLoading });
        Login.checkLogin().success(function (data) {
            if (data.status) {
                Departments.getSelect().success(function (data) {
                    $scope.departments = data;
                    $scope.orgDepartments = data;
                    $scope.departmentsGroup = data;
                    $scope.getPositiontitles();
                    $timeout(function () {
                        switch (_crud) {
                            case 3:
                            if (!$scope.dataFilterLoaded) {
                                Departments.getSelectFilter().success(function (data) {
                                    $scope.departTitle = $scope.initNode('Department', data);
                                    $scope.dataFilterLoaded = true;
                                });
                            }
                            break;
                            case 2:
                            $scope.getDepartmentsGroupEdit();
                            break;
                            case 1:
                            $scope.addUsersData.appointmentgroup_id = [];
                            $scope.addUsersData.notes = '';
                            if ($scope.deparmentdata == null) {
                                $scope.deparmentdata = data;
                                $scope.getDepartmentsGroup();
                            } else {
                                $scope.addUsersData.positiontitle_id = '';
                                $scope.addUsersData.department_id = '';
                                $('.department_group').hide();
                            }
                            break;
                        }
                    }, 500);
                });
            } else {
                console.log('get department fail!!!');
            }
        });
    }
    $scope.setValueForInput = function (arrData, id) {
        var result = '';
        var index = _.findLastIndex(arrData, {
            id: id
        });
        if (index >= 0)
            result = arrData[index];
        return result;
    }
    $scope.setValueDepartmentGroupInput = function (deparment_group_id) {
        $scope.Input_value.departmentGroup = "";
        $scope.Input_value.departmentGroup = $scope.setValueForInput($scope.departmentsGroup, deparment_group_id).name;
    }
    $scope.setValueRoleInput = function (role_id) {
        $scope.Input_value.role = "";
        $scope.Input_value.role = $scope.setValueForInput($scope.roles, role_id).name;
    }
    $scope.setValueSuperVisor1Input = function (supervisor_user1_id) {
        $scope.Input_value.supervisor_user1 = "";
        $scope.Input_value.supervisor_user1 = $scope.setValueForInput($scope.usersVisor, supervisor_user1_id).nameWithpos;
    }
    $scope.setValueSuperVisor2Input = function (supervisor_user2_id) {
        $scope.Input_value.supervisor_user2 = "";
        $scope.Input_value.supervisor_user2 = $scope.setValueForInput($scope.usersVisor, supervisor_user2_id).nameWithpos;
    }
    $scope.setValuePushChatRoomInput = function (pushChatRoom_id) {
        $scope.Input_value.pushchatroom = "";
        $scope.Input_value.pushchatroom = $scope.setValueForInput($scope.roomsall, pushChatRoom_id).name;
    }
    $scope.setValueUserType = function(usertype_id){
        $scope.Input_value.usertype = "";
        $scope.Input_value.usertype = $scope.setValueForInput($scope.usertypes, usertype_id).name;
    }
    $scope.setValueAssignLocation = function(assigned_location_id){
        $scope.Input_value.assigned_location = "";
        $scope.Input_value.assigned_location = $scope.setValueForInput($scope.assignedLocations, assigned_location_id).name;
    }
    $scope.setValueCurrentWageDetail = function(currentwage_detail_id){
        $scope.Input_value.currentwage_detail_name = "";
        $scope.Input_value.currentwage_detail_name = $scope.setValueForInput($scope.wagedetails, currentwage_detail_id).name;
    }
    $scope.setValueStartingWageDetail = function(startwage_detail_id){
        $scope.Input_value.startwage_detail_name = "";
        $scope.Input_value.startwage_detail_name = $scope.setValueForInput($scope.wagedetails, startwage_detail_id).name;
    }
    $scope.setValueDriverornot = function(driverornot){
        if(driverornot != undefined){
            $scope.Input_value.driverornot = "";
            $scope.Input_value.driverornot = $scope.setValueForInput($scope.driverOrNotSelect, driverornot).name;
        }else{
            $scope.Input_value.driverornot = "Select";
        }
    }

    $scope.getAppointmentGroup = function (query, isInitializing, style) {
        var listIdArray = $scope.autocompleteList.dataUserAppointmentGroupsCreate;
        var returnValue = {
            items: []
        };
        if (style != 'add') {
            listIdArray = $scope.autocompleteList.dataUserAppointmentGroupsEdit;
        }
        $scope.rootAppGroupsMobile.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.indexOf(query) > -1) {
                    returnValue.items.push(item);
                }
            }
        });
        return returnValue;
    };
    $scope.setValueForAppointmentGroup = function (modelValue) {
        for (var i = 0; i < $scope.rootAppGroupsMobile.length; i++) {
            if ($scope.rootAppGroupsMobile[i].id == modelValue) {
                return $scope.rootAppGroupsMobile[i];
            }
        }
        return {};
    };
    $scope.initialAppointmentGroupEdit = [];
    $scope.setValueForAppointmentGroupEdit = function (modelValue) {
        for (var i = 0; i < $scope.rootAppGroupsMobile.length; i++) {
            if ($scope.rootAppGroupsMobile[i].id == modelValue) {
                return $scope.rootAppGroupsMobile[i];
            }
        }
        return {};
    };
    $scope.clickedMethodAppGroup = function (callback, style) {
        if (style == 'add') {
            if ($scope.addUsersData.appointmentgroup_id.indexOf(callback.item) < 0)
                $scope.addUsersData.appointmentgroup_id.push(callback.item);
        } else {
            var flag = true;
            for (var i = $scope.editUsersData.dataUserAppointmentGroups.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataUserAppointmentGroups[i].id == callback.item.id) {
                    flag = false;
                }
            }
            if (flag)
                $scope.editUsersData.dataUserAppointmentGroups.push(callback.item);
        }
    }
    $scope.removeMethodAppGroup = function (callback, style) {
        if (style == 'add') {
            var index = $scope.addUsersData.appointmentgroup_id.indexOf(callback.item);
            $scope.addUsersData.appointmentgroup_id.splice(index, 1);
        } else {
            for (var i = $scope.editUsersData.dataUserAppointmentGroups.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataUserAppointmentGroups[i].id == callback.item.id) {
                    $scope.editUsersData.dataUserAppointmentGroups.splice(i, 1);
                }
            }
        }
    }

    $scope.getSuppliersItem = function (query, isInitializing, style) {
        var returnValue = {
            items: []
        };
        var listIdArray = $scope.autocompleteList.dataUserSuppliersCreate;
        if (style != 'add') {
            listIdArray = $scope.autocompleteList.dataUserSuppliersEdit;
        }
        $scope.rootSupplieritems.forEach(function (item) {
            if (listIdArray.indexOf(item.id) < 0) {
                if (item.name && item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                } else if (item.id.indexOf(query) > -1) {
                    returnValue.items.push(item);
                }
            }
        });
        return returnValue;
    };
    $scope.setValueForInputSuppliersItem = function (modelValue) {
        for (var i = 0; i < $scope.rootSupplieritems.length; i++) {
            if ($scope.rootSupplieritems[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.rootSupplieritems[i];
            }
        }
        return {};
    };
    $scope.initialSuppliersItemEdit = [];
    $scope.setValueForInputSuppliersItemEdit = function (modelValue) {
        for (var i = 0; i < $scope.rootSupplieritems.length; i++) {
            if ($scope.rootSupplieritems[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.rootSupplieritems[i];
            }
        }
        return {};
    };
    $scope.clickedMethodSuppliersItem = function (callback, style) {
        if (style == 'add') {
            if ($scope.addUsersData.supplieritems.indexOf(callback.item) < 0)
                $scope.addUsersData.supplieritems.push(callback.item);
        } else {
            var flag = true;
            for (var i = $scope.editUsersData.dataSupplieritems.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataSupplieritems[i].id == callback.item.id) {
                    flag = false;
                }
            }
            if (flag)
                $scope.editUsersData.dataSupplieritems.push(callback.item);
        }
    }
    $scope.removeMethodSuppliersItem = function (callback, style) {
        if (style == 'add') {
            var index = $scope.addUsersData.supplieritems.indexOf(callback.item);
            $scope.addUsersData.supplieritems.splice(index, 1);
        } else {
            for (var i = $scope.editUsersData.dataSupplieritems.length - 1; i >= 0; i--) {
                if ($scope.editUsersData.dataSupplieritems[i].id == callback.item.id) {
                    $scope.editUsersData.dataSupplieritems.splice(i, 1);
                }
            }
        }
    }
    $scope.search = {};
    $scope.clearSearch = function () {
        $scope.searchUsers.search = '';
        $scope.searchUser();
    }

    $scope.resetFitler = function () {
        $scope.posTitle = [];
        $scope.departTitle = [];
        $scope.dataFilterLoaded = false;
        $('input[name=rdFilterPositionTitle]').attr('checked', false);
        $('input[name=rdFilterDepartment]').attr('checked', false);
        $('.box-expandable').removeClass('expand');
        $('#ckEmployeeFilter_AllUser').attr('checked', false);
        $scope.userStatusShow = 'Active';
        $scope.searchUsers.showUserStatus = 'active';
        $scope.searchUsers.current_page = 1;
        $scope.getUsers();
        $scope.predicate = 'display_name';
        $scope.reverse = false;
        $scope.closeTarget('#popupEmployeeFilter');
    }
    $scope.getfilterClient = function () {
        if (!$scope.posTitle.length && !$scope.departTitle.length) {
            $scope.closeTarget('#popupEmployeeFilter');
            return;
        }
        var _f1 = $scope.changeCallback($scope.posTitle, 1);
        var _f2 = $scope.changeCallback($scope.departTitle, 2);
        $scope.users = _.intersection(_f1, _f2);
        $scope.closeTarget('#popupEmployeeFilter');
        $scope.checkLoadMore = true;

    }
    $scope.usersss = {
        position: []
    };
    $scope.check_value = function (check) {
        if ($scope.user.position.length == $scope.position.length) {
            $scope.usersss = {
                position: [1]
            };
        } else {
            $scope.usersss = {
                position: []
            };
        }
    }
    //check table deparment
    $scope.userssss = {
        depart: []
    };
    $scope.check_valuedepart = function (check) {
        if ($scope.user.depart.length == $scope.depart.length) {
            $scope.userssss = {
                depart: [1]
            };
        } else {
            $scope.userssss = {
                depart: []
            };
        }
    }

    $scope.getDepartmentsGroup = function (department_id) {
        // edit by haudao
        $scope.Input_value.department = "";
        var deparment_index = _.findLastIndex($scope.departments, {
            id: department_id
        });
        if (deparment_index >= 0)
            $scope.Input_value.department = $scope.departments[deparment_index].name;
        // console.log($scope.Input_value.department);
        // end edit
        Departments.getDepartmentsGroup({
            id: department_id
        }).success(function (data) {
            $scope.departmentsGroup = data;
            $scope.addUsersData.department_id == undefined ? '' : $scope.positiontitles_by_department = _.where($scope.positiontitles, {
                department_id: $scope.addUsersData.department_id
            });
            // $scope.addUsersData.positiontitle_id = 1;
            $scope.getListSkill();
            if ($scope.roomsall == undefined) {
                $scope.getRooms();
            }
        });
    }

    $scope.populatecurrent_hiredate = function (action, positiontitle_id) {
        $scope.Input_value.positiontitle = "";
        var positiontitle_index = _.findLastIndex($scope.positiontitles_by_department, {
            id: positiontitle_id
        });
        if (positiontitle_index >= 0)
            $scope.Input_value.positiontitle = $scope.positiontitles_by_department[positiontitle_index].name;
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!
        var yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd
        }
        if (mm < 10) {
            mm = '0' + mm
        }
        var today = mm + '/' + dd + '/' + yyyy;
        if (action == 'add') {
            $scope.addUsersData.current_hiredate = today;
            $scope.addUsersData.current_startdate = today;
            $scope.getListSkill();
        }
        if (action == 'edit') {
            $('#current_hiredateEdit').val(today);
            $('#current_startdateEdit').val(today);
            $scope.getListSkillEdtit();
        }
    }
    $scope.listSkill = [];
    $scope.getListSkill = function () {
        if ($scope.addUsersData.positiontitle_id == undefined || $scope.addUsersData.positiontitle_id == '')
            return;
        Skills.getListSkill($scope.addUsersData.positiontitle_id).success(function (data) {
            $scope.addUsersData = _.extend($scope.addUsersData, {
                positiontitles: data.positiontitle
            });
            $scope.listSkill = data.data;
            if ($scope.roomsall == undefined) {
                $scope.getRooms();
            } else {
                $scope.getRoles();
            }
        });
    }


    // edit by haudao
    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/users/users/userMenuHeadermodal.tpl').success(function (results) {
            $scope.dataHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/users/users/userContentmodal.tpl').success(function (results) {
                $scope.dataHtml.listContent = results;
                var userDetailId = getParameterByName('userId');
                if (userDetailId != undefined && userDetailId != "") {
                    $scope.getUserData(userDetailId, true);
                }
                $timeout(function () {
                    setHeight("#main-content");
                }, 1)
                $scope.getUsers();
            });
        });
    }
    $scope.openByGetTemplate = function (style) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            switch (style) {

                case 'popupEmployeeAdd':
                dataHtml.getTemplate('templates/dashboard/users/users/userPopupAddmodal.tpl').success(function (results) {
                    $scope.dataHtml.popupEmployeeAdd = results;
                    $timeout(function () {
                        $scope.showTarget('#popupEmployeeAdd');
                        $ionicScrollDelegate.$getByHandle('scrollAdd').resize();
                        $ionicScrollDelegate.$getByHandle('scrollAdd').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeFilter':
                dataHtml.getTemplate('templates/dashboard/users/users/userFilterSettingmodal.tpl').success(function (results) {
                    $scope.dataHtml.popupEmployeeFilter = results;
                    $timeout(function () {
                        $scope.showTarget('#popupEmployeeFilter');
                        $ionicScrollDelegate.$getByHandle('scrollFilterSetting').resize();
                        $ionicScrollDelegate.$getByHandle('scrollFilterSetting').scrollTop(true);
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
                case 'popupEmployeeSetSchedule':
                dataHtml.getTemplate('templates/dashboard/users/users/userPopupSetSchedulemodal.tpl').success(function (results) {
                    $scope.dataHtml.popupEmployeeSetSchedule = results;
                    $timeout(function () {
                        $scope.showTarget('#popupEmployeeSetSchedule');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;

                case 'popupConfirmVehiclesAdd':
                dataHtml.getTemplate('templates/dashboard/users/users/popupConfirmVehiclesmodalAdd.tpl').success(function (results) {
                    $scope.dataHtml.popupConfirmVehiclesAdd = results;
                    $timeout(function () {
                        $scope.showTarget('#popupConfirmVehiclesAdd');
                        $ionicLoading.hide();
                    }, 1)
                })
                break;
            }
        }, 500);
    }
    //get User by SinhDang
    $scope.getUsers = function (onClient) {
        $ionicLoading.show({
            template: templateLoading
        });
        Users.getPaging($scope.searchUsers).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $ionicLoading.hide();
                $scope.users = data.data;
                $scope.users = _.each($scope.users, function (val) {
                    return _.extend(val, {
                        mailto: $sce.trustAsHtml('<a href="mailto:' + val.email + '">' + val.email + '</a>')
                    });
                })
                $scope.filterClientdata = data.data;
                $scope.addUsersData.itemLog = [{
                    logData: ''
                }];
                $scope.usertypes = data.usertypes;
                $scope.$emit('sendusertype', {data: data.usertypes});
                if ($scope.loaded == 0) {
                    $scope.loaded = 1;
                }
                request_notify_get_chat = true;
                $timeout(function () {
                    if (data.data.length != 0)
                        $scope.checkLoadMore = true;
                }, 5000);
                $scope.closeTarget(".user-search");
                $("#searchInput").blur();

                $scope.$broadcast('scroll.refreshComplete');
            }
        });
    };

    $scope.refreshPageUser = function(){
        $scope.searchUsers.current_page = 1;
        $scope.getUsers();
    }

    $scope.checkLoadMore = false;
    $scope.LoadMoreUser = function () {
        if (!$scope.checkLoadMore)
            return;
        $scope.searchUsers.current_page++;
        Users.getPaging($scope.searchUsers).success(function (data) {
            if (data.data.length < $scope.itemsPerPage)
                $scope.checkLoadMore = false;
            _.each(data.data, function (val) {
                return _.extend(val, {
                    mailto: $sce.trustAsHtml('<a href="mailto:' + val.email + '">' + val.email + '</a>')
                });
            })
            $scope.users = arrayUnion($scope.users, data.data, function (item1, item2) {
                return item1.id == item2.id;
            });
            $scope.filterClientdata = $scope.users;

        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Add Errror!!!');
        })

        $timeout(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }, 2000);
    };
    $scope.searchUser = function () {
        $scope.searchUsers.current_page = 1;
        $scope.checkLoadMore = false;
        $scope.getUsers();
    }
    $scope.keypress = function (delegate) {
        var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
        if ($scope.searchUsers.search.keyCode >= 112 && $scope.searchUsers.search.keyCode <= 123)
            return;
        if (keysByCode.indexOf($scope.searchUsers.search.keyCode) > -1)
            return;
        $scope.coundown = 10;
        if ($scope.myTime != null)
            clearInterval($scope.myTime);
        $scope.downTimer(delegate);
    };
    $scope.downTimer = function (delegate) {
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                $ionicLoading.show({
                    template: templateLoading
                });
                $scope.searchUser();
                $ionicScrollDelegate.$getByHandle(delegate).scrollTop();
                clearInterval($scope.myTime);
            }
        }, 100);
    }
    $scope.entrypageuser = function (entrypagedata) {
        $scope.searchUsers.rows = entrypagedata;
        $scope.searchUsers.current_page = 1;
        $scope.getUsers();
    }
    $scope.pageChanged = function (currentPage) {
        //console.log($scope.currentPage);
        $scope.searchUsers.current_page = currentPage;
        $scope.getUsers();
    };
    $scope.addRow = function () {
        $scope.addUsersData.itemLog.push({
            logData: ''
        });
    }
    $scope.removeItem = function (index) {
        if ($scope.addUsersData.itemLog.length > 1)
            $scope.addUsersData.itemLog.splice(index, 1);
    }
    $scope.addRowEdit = function () {
        $scope.editUsersData.dataUserLog.push({
            contents: ''
        });
    }
    $scope.removeItemEdit = function (index) {
        if ($scope.editUsersData.dataUserLog.length > 1)
            $scope.editUsersData.dataUserLog.splice(index, 1);
    }

    $scope.order = function (predicate, check) {
        $scope.predicate = predicate;
        if (check == 'Oldest') {
            $scope.reverse = true;
        } else {
            $scope.reverse = false;
        }
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
    };

    $scope.getAppointmentgroups = function () {
        Appointmentgroups.getSelect().success(function (data) {
            $scope.appointmentgroups = data;
            $scope.rootAppGroups = _.filter($scope.appointmentgroups, function (val) {
                return val.department_id != null;
            });
            $scope.getUsersVisor();
        });
    }
    $scope.getAppointmentgroupsMobile = function () {
        Appointmentgroups.getSelect().success(function (data) {
            $scope.rootAppGroupsMobile = _.filter(data, function (val) {
                return val.department_id != null;
            });
        });
    }
    $scope.getAppointmentgroupsMobile();
    $scope.searchChanged = function () {
        $scope.getUsers();
    }
    // edit by haudao
    $scope.openPickerForProfile = function () {
        var options = {
            maximumImagesCount: 1,
            width: 0,
            height: 0,
            quality: 100
        };
        $ionicLoading.show({template: templateLoading});
        $cordovaImagePicker.getPictures(options).then(function (results) {
            $scope.file = results[0];
            window.plugins.Base64.encodeFile($scope.file, function (base64) {
                $scope.imageURI = base64;
                // console.log('file base64 encoding: ' + base64);
            });
            $timeout(function () {
                $ionicLoading.hide();
            }, 3000)
        })
    }
    $scope.validateForm = function (formValidate, file, style) {
        var exitLoop = false;
        if (formValidate.$invalid) {
            $ionicScrollDelegate.$getByHandle('scroll' + style).scrollTop();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if (style == 'Add') {
            if($scope.imageURI == ''){
                $ionicScrollDelegate.$getByHandle('scroll' + style).scrollTop();
                $cordovaToast.showLongTop('Please fill all the required information.!!!');
                return;
            }
            $scope.beforeCreateUsers(file);
        } else {
            $scope.beforeUpdateUsers(file);
        }
    }
    $scope.beforeCreateUsers = function (file) {
        if(parseInt($scope.addUsersData.driverornot) == 1 && !parseInt($scope.addUsersData.assigned_vehicle.id) > 0){
            $cordovaToast.showLongTop('Please assign vehicle');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        if (storeInCloud && file !== undefined && file !== "" && file !== null) {
            $scope.fileUploadData = {};
            $scope.fileUploadData.type = 'image/jpeg';
            $scope.fileUploadData.name = 'user_image.jpg';
            $scope.fileUploadData.bucket = bucketName;
            $scope.fileUploadData.acl = aclConfig;
            $scope.fileUploadData.for = 'users';
            $scope.fileUploadData.email = $scope.addUsersData.email;
            Login.getConfigFileUpload($scope.fileUploadData).success(function (data) {
                var Uoptions = {};
                Uoptions.fileKey = "file";
                Uoptions.fileName = data.folder + '/' + data.microtime + 'user_image.jpg';
                Uoptions.mimeType = "image/jpeg";
                Uoptions.chunkedMode = false;
                Uoptions.headers = {
                    connection: "close"
                };
                Uoptions.params = {
                    "Key": data.folder + '/' + data.microtime + 'user_image.jpg',
                    "AWSAccessKeyId": data.awsAccessKeyId,
                    "acl": data.acl,
                    "Policy": data.policy,
                    "Signature": data.signature,
                    "success_action_status": data.successActionStatus,
                    "Content-Type": "image/jpeg"
                };
                $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', file, Uoptions).then(function (return_data) {
                    try {
                        $scope.fileLocation = return_data.headers.Location;
                    } catch (e) {
                        $scope.jsonObject = xml2json.parser(return_data.response);
                        $scope.fileLocation = $scope.jsonObject.postresponse.location;
                    }
                    $scope.addUsersData.image_pic = $scope.fileLocation;
                    $scope.fileUploadData = {};
                    $scope.createUsers(file);
                })
            });
        } else {
            $scope.createUsers(file);
        }
        if (window.cordova){
            window.cordova.plugins.Keyboard.close();
        }
    }
    $scope.createUsers = function (file) {
        $ionicLoading.show({
            template: templateLoading
        });
        $('#startlocationAddEmployeee').trigger('input');

        $scope.addUsersData = this.addUsersData;
        $scope.addUsersDataCopy = angular.copy($scope.addUsersData);
        $scope.addUsersDataCopy.dob = $('#popupEmployeeAdd input[name="dob"]').val();
        $scope.addUsersDataCopy.company_hiredate = $('#popupEmployeeAdd input[name="company_hiredate"]').val();
        $scope.addUsersDataCopy.company_startdate = $('#popupEmployeeAdd input[name="company_startdate"]').val();
        $scope.addUsersDataCopy.last_review = $('#popupEmployeeAdd input[name="last_review"]').val();
        $scope.addUsersDataCopy.next_review = $('#popupEmployeeAdd input[name="next_review"]').val();
        $scope.addUsersDataCopy.last_raise = $('#popupEmployeeAdd input[name="last_raise"]').val();
        $scope.addUsersDataCopy.current_startdate = $('#popupEmployeeAdd input[name="current_startdate"]').val();
        $scope.addUsersDataCopy.current_hiredate = $('#popupEmployeeAdd input[name="current_hiredate"]').val();
        $scope.addUsersDataCopy.itemLog = $scope.addUsersData.itemLog.length > 0 ? JSON.stringify($scope.addUsersData.itemLog) : [];
        $scope.addUsersDataCopy.listSkill = $scope.listSkill.length > 0 ? JSON.stringify($scope.listSkill) : "[]";
        $scope.addUsersDataCopy.supplieritems = $scope.addUsersData.supplieritems.length > 0 ? JSON.stringify($scope.addUsersData.supplieritems) : "[]";
        $scope.addUsersDataCopy.appointmentgroup_id = $scope.addUsersData.appointmentgroup_id.length > 0 ? JSON.stringify($scope.addUsersData.appointmentgroup_id) : "[]";
        $scope.addUsersDataCopy.userlogin = $scope.currentIdLogin;
        if($scope.addUsersData.assigned_vehicle.id && parseInt($scope.addUsersData.assigned_vehicle.id) > 0){
            $scope.addUsersDataCopy.assigned_vehicle = JSON.stringify($scope.addUsersData.assigned_vehicle);
        }else{
            $scope.addUsersDataCopy.assigned_vehicle = "[]";
        }
        $scope.addUsersDataCopy.phoneApp = false;
        // $scope.addUsersData.image_pic = " ";
        if (!file) {
            Users.save($scope.addUsersDataCopy, file).success(function (data, status, headers, config) {
                if(data.status == false){
                    if(data.type_error == 'vehicle_exist'){
                        $scope.msgConfirmVehicles = data.msg;
                        $scope.currentFileUpdateUser = file;
                        $scope.openByGetTemplate('popupConfirmVehiclesAdd');
                    }else{
                       $cordovaToast.showLongCenter(data.msg);
                   }
               }else{
                $ionicLoading.hide();
                if (data.status) {
                    if($scope.addUsersData.remove_exist_vehicle == true ){
                        $scope.closeTarget('#popupConfirmVehiclesAdd');
                    }
                    $scope.closeTarget('#popupEmployeeAdd');
                    $scope.addUsersData = {};
                    $scope.addUsersData.itemLog = [];
                    $scope.listSkill = [];
                    $scope.addUsersData.supplieritems = [];
                    $scope.addUsersData.appointmentgroup_id = [];
                    $scope.Input_value = {};
                    $scope.holdValueAddress.addUserAddress = [];
                    $scope.holdValueAddress.addUserStarLocation = [];
                    $scope.holdValueAddress.addUserAssignLocation = [];
                    // $scope.getUsers();
                    messagebox('success', 'Create successfull', data.msg)
                } else {
                    messagebox('fail', 'Create failed', 'Add Errror!!!');
                }
            } 
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            messagebox('fail', 'Create failed', 'Add Errror!!!');
        })
        return;
    }
    $scope.addUsersDataCopy.phoneApp = true;

    var options = {
        fileKey: "file",
        params: $scope.addUsersDataCopy,
        chunkedMode: false
    };
    $cordovaFileTransfer.upload(url_server + 'users', file, options).then(function (e) {
        var results = JSON.parse(e.response);
        $ionicLoading.hide();
        if (results.status) {
            if($scope.addUsersData.remove_exist_vehicle == true ){
                $scope.closeTarget('#popupConfirmVehiclesAdd');
            }
            $scope.closeTarget('#popupEmployeeAdd');
            $scope.addUsersData = {};
            $scope.addUsersData.itemLog = [];
            $scope.addUsersData.assigned_vehicle = [];
            $scope.listSkill = [];
            $scope.addUsersData.supplieritems = [];
            $scope.addUsersData.appointmentgroup_id = [];
            $scope.Input_value = {};
                // $scope.getUsers();
                messagebox('success', 'Create successfull', results.msg)
            } else {
                if(results.type_error == 'vehicle_exist'){
                    $scope.msgConfirmVehicles = results.msg;
                    $scope.addUsersData.remove_exist_vehicle = true;
                    $scope.currentFileAddUser = file;
                    $scope.openByGetTemplate('popupConfirmVehiclesAdd');
                }else{
                    messagebox('fail', 'Create failed', results.msg);
                }
            }
        }, function (err) {
            console.log(err);
            console.log("ERROR: " + JSON.stringify(err));
            $ionicLoading.hide();
            messagebox('fail', 'Create failed', 'Add Errror!!!');
        });
};
$scope.confirmVehiclesAdd = function() {
    $scope.addUsersData.remove_exist_vehicle = true;
    $scope.beforeCreateUsers($scope.currentFileAddUser);
}
$scope.emitGetUserData = function (item) {
    $scope.dataHideButton = {};
    $scope.dataHideButton.hideButtonSentFeedInDetail = $scope.hideCheckNewfeed(item);
    $scope.dataHideButton.hideButtonEitInDetail = $scope.hideEditButton(item);
    $scope.dataHideButton.hideButtonDeleteInDetail = $scope.hideDeleteButton(item);
    $scope.$emit('sendGetUserData', {data: item,dataHideButton : $scope.dataHideButton});
}
$scope.refreshUsers = function (data, dataValue) {
    var dataDetail = data.dataUserDetail;
    dataDetail = JSON.parse(dataDetail);
    var data = JSON.parse(data.dataUser);
    var idx = _.findLastIndex($scope.users, {id: parseInt(data.id)});
    if (idx != -1) {
        $scope.users[idx].first_name = data.first_name;
        $scope.users[idx].last_name = data.last_name;
        $scope.users[idx].display_name = data.display_name;
        if (dataValue.positiontitle && dataValue.positiontitle != '')
            $scope.users[idx].positiontitles_name = dataValue.positiontitle;
        if (dataValue.department && dataValue.department != '')
            $scope.users[idx].departments_name = dataValue.department;
        $scope.users[idx].email = data.email;
        $scope.users[idx].cell_phone = data.cell_phone;
        $scope.users[idx].office_phone = data.office_phone;
        $scope.users[idx].extension_phone = data.extension_phone;
        $scope.users[idx].street = dataDetail.street;
    }
    $scope.editUsersData = {};
    $scope.Input_value = {};
    $scope.closeTarget('#popupEditEmployee');
}
$scope.sizeChanged = function (entryLimit) {
    $scope.searchUsers.rows = entryLimit;
    users_pagesize.val($scope.searchUsers.rows);
    localStorage.setItem('users_pagesize', $scope.searchUsers.rows);
    $scope.searchUsers.current_page = 1;
    $scope.getUsers(1);
}
$scope.setPage = function (pageNo) {
    $scope.currentPage = pageNo;
        // console.log('doi page');
    };
    $scope.showsInActiveUsers = function(userStatusShow) {
        $scope.searchUsers.showUserStatus = userStatusShow;
        switch(userStatusShow){
            case 'all':
            $scope.userStatusShow = 'All';
            break;
            case 'active':
            $scope.userStatusShow = 'Active';
            break;
            case 'inactive':
            $scope.userStatusShow = 'Deactivated';
            break;
        }
        $scope.searchUsers.current_page = 1;
        $scope.closeTarget('#popupEmployeeFilter');
        $scope.getUsers();
    }
    // $scope.showsInActiveUsers = function (checkbox) {
    //     $ionicLoading.show({
    //         template: templateLoading
    //     });
    //     if (checkbox == true) {
    //         $scope.searchUsers.showuser = 1;
    //     } else {
    //         $scope.searchUsers.showuser = 0;
    //     }
    //     $scope.searchUsers.current_page = 1;
    //     $scope.getUsers();
    //     $ionicScrollDelegate.$getByHandle('scrollUserContent').resize();
    //     $ionicScrollDelegate.$getByHandle('scrollUserContent').scrollTop();
    // }

    $scope.getUserById = function (id) {
        for (var i = 0; i < $scope.users.length; i++) {
            if (id == $scope.users[i]['id']) {
                $scope.selectedUser = $scope.users[i];
            }
        }
        ;
        return $scope.selectedUser;
    }

    $scope.editUsersData = {};
    $scope.editUsersData.dataSupplieritems = [];
    $scope.editUsersData.dataUserAppointmentGroups = [];
    $scope.fDateInput = function (data) {
        // format date for edit lastservice
        var ch = moment(data.dataUserDetail.company_hiredate).format("MM/DD/YYYY");
        var cs = moment(data.dataUserDetail.company_startdate).format("MM/DD/YYYY");
        var lr = moment(data.dataUserDetail.last_review).format("MM/DD/YYYY");
        var nr = moment(data.dataUserDetail.next_review).format("MM/DD/YYYY");
        var lra = moment(data.dataUserDetail.last_raise).format("MM/DD/YYYY");
        var chi = moment(data.dataUserDetail.current_hiredate).format("MM/DD/YYYY");
        var cst = moment(data.dataUserDetail.current_startdate).format("MM/DD/YYYY");
        var dob = moment(data.dataUserDetail.dob).format("MM/DD/YYYY");
        $scope.editUsersData.dataUserDetail.company_hiredate = ch;
        $scope.editUsersData.dataUserDetail.company_startdate = cs;
        $scope.editUsersData.dataUserDetail.last_review = lr;
        $scope.editUsersData.dataUserDetail.next_review = nr;
        $scope.editUsersData.dataUserDetail.last_raise = lra;
        $scope.editUsersData.dataUserDetail.current_hiredate = chi;
        $scope.editUsersData.dataUserDetail.current_startdate = cst;
        $scope.editUsersData.dataUserDetail.dob = dob;
    }

    $scope.editUsersData.userSkillArrId = {
        skillId: []
    };
    $scope.editScheduleData = {};
    $scope.idnextweeks = '';
    $scope.checkCalendaNext = [];
    $scope.getSchedule = function (itm, date) {
        $scope.openByGetTemplate('popupEmployeeSetSchedule');
        $scope.idnextweeks = itm.id;
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.selectedUserId.display_name = itm.display_name;
        $scope.selectedUserId.fullname = itm.first_name + ' ' + itm.last_name;
        var objParam = {
            rows: 50,
            current_page: 1,
            search: "",
            user_id: itm.id,
            start_time: moment().day("Sunday").format('MM/DD/YYYY'),
            end_time: moment(moment().day("Sunday").add(27, 'days')).format('MM/DD/YYYY'),
        }
        Users.getSchedule(objParam).success(function (data) {
            $ionicLoading.hide();
            if (data['error']) {
                // closePopupById($selector);
                $scope.closeTarget('#popupEmployeeSetSchedule');
                $cordovaToast.showLongTop(data['error']);
            }
            $scope.shifts = data.data;
            // $scope.weeks = data['weeks'];
            // $scope.weeksnext = data['weeksnext'];
            // for (var i = 0; i < data['biweeks'].length; i++) {
            //     data['biweeks'][i].from_hour = moment(data['biweeks'][i].from_hour, 'hh:mm:ss').format('hh:mmA');
            //     data['biweeks'][i].to_hour = moment(data['biweeks'][i].to_hour, 'hh:mm:ss').format('hh:mmA');
            // }
            // for (var i = 0; i < data['biweeksnext'].length; i++) {
            //     data['biweeksnext'][i].from_hour = moment(data['biweeksnext'][i].from_hour, 'hh:mm:ss').format('hh:mmA');
            //     data['biweeksnext'][i].to_hour = moment(data['biweeksnext'][i].to_hour, 'hh:mm:ss').format('hh:mmA');
            // }
            // $scope.checkCalendaNext = data.checkCalendaNext;
            // $scope.biweeks = data['biweeks'];
            // $scope.biweeksnext = data['biweeksnext'];
            // $scope.dataTargetTime = data['dataTargetTime'];
            // $scope.editScheduleData = data;
            // setTimeout(function() {
            //     $scope.$apply(function(val) {
            //         $('.timepicker').attr('readonly', true);
            //         $(".timepicker").keydown(function(event) {
            //             event.preventDefault();
            //         });
            //     });
            // }, 100);
        });
    }
    $scope.updateSchedule = function () {
        if (!$scope.dataTargetTime.punch_in_allow || !$scope.dataTargetTime.punch_out_allow || !$scope.dataTargetTime.sunwed_target1 || !$scope.dataTargetTime.sunwed_target2 || !$scope.dataTargetTime.target_hour1 || !$scope.dataTargetTime.target_hour2) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        var arrBiweeks = $scope.biweeks;
        var arrBiweeksnext = $scope.biweeksnext;
        var checked = 0;
        for (var i = 0; i < $scope.biweeks.length; i++) {
            if ($scope.biweeks[i].checked) {
                var flag = validateTime($scope.biweeks[i].from_hour, $scope.biweeks[i].to_hour);
                if (!flag.status) {
                    $scope.biweeks[i].to_hour = '00:00';
                    checked = 1;
                    $('#popupEmployeeSetSchedule .next-week-control, #popupEmployeeSetSchedule .next-week-content').hide();
                    $('#popupEmployeeSetSchedule .this-week-control, #popupEmployeeSetSchedule .this-week-content').show();
                }
            }
        }
        for (var i = 0; i < $scope.biweeksnext.length; i++) {
            if ($scope.biweeksnext[i].checked) {
                var flag = validateTime($scope.biweeksnext[i].from_hour, $scope.biweeksnext[i].to_hour);
                if (!flag.status) {
                    $scope.biweeksnext[i].to_hour = '00:00';
                    checked = 1;
                    $('#popupEmployeeSetSchedule .next-week-control, #popupEmployeeSetSchedule .next-week-content').show();
                    $('#popupEmployeeSetSchedule .this-week-control, #popupEmployeeSetSchedule .this-week-content').hide();
                }
            }
        }
        if (checked == 1) {
            $cordovaToast.showLongTop('End time must be greater than start time!!!');
            return;
        }
        for (var i = 0; i < arrBiweeks.length; i++) {
            if (arrBiweeks[i].checked) {
                var from = $('#biweeksStart' + i).val();
                var to = $('#biweeksEnd' + i).val();
                arrBiweeks[i].from_hour = moment(from, 'h:mmA').format('HH:mm:ss');
                arrBiweeks[i].to_hour = moment(to, 'h:mmA').format('HH:mm:ss');
            } else {
                arrBiweeks[i].from_hour = "00:00:00";
                arrBiweeks[i].to_hour = "00:00:00";
            }
        }
        for (var i = 0; i < arrBiweeksnext.length; i++) {
            if (arrBiweeksnext[i].checked) {
                var from = $('#biweeksnextStart' + i).val();
                var to = $('#biweeksnextEnd' + i).val();
                arrBiweeksnext[i].from_hour = moment(from, 'h:mmA').format('HH:mm:ss');
                arrBiweeksnext[i].to_hour = moment(to, 'h:mmA').format('HH:mm:ss');
            } else {
                arrBiweeksnext[i].from_hour = "00:00:00";
                arrBiweeksnext[i].to_hour = "00:00:00";
            }

        }

        $ionicLoading.show({template: templateLoading});
        Users.updateSchedules(arrBiweeks, arrBiweeksnext, $scope.dataTargetTime).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.editUsersData = {};
                $scope.closeTarget('#popupEmployeeSetSchedule');
                $('#popupEmployeeSetSchedule .next-week-control, #popupEmployeeSetSchedule .next-week-content').hide();
                $('#popupEmployeeSetSchedule .this-week-control, #popupEmployeeSetSchedule .this-week-content').show();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function () {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection error!!!');
        });

    }
    // end edit//
    $scope.locationChangedCreate = function (location) {
        // console.log(location);
        $scope.addUsersData.city = location['locality'];
        $scope.addUsersData.state = location['administrative_area_level_1'];
        $scope.addUsersData.zipcode = location['postal_code'];
    }
    $scope.dataChangePassword = {};
    $scope.getUserLogin = function () {
        Login.getUserLogin().success(function (data) {
            if (data == false) {
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                $scope.imagePath = pathToPublic + data.image_pic;
                current_ext = data.extension_phone;
                $scope.dataChangePassword.emailShow = data.email;
                $scope.ischange_password = data.ischange_password;
                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.getUsers();
                // by sinhdang
                stopTime = $interval($scope.checkLogin, time_refresh);
            }
            // $scope.getUsers();
        });
    }
    // if (!$stateParams.userID) $scope.getUserLogin();
    $scope.changePassword = function () {
        if ($scope.oldPassword != '') {
            if ($scope.newPassword == '' || $scope.conFirmPassword == '') {
                toastr.error('Xin vui long dien day du thong tin.');
                return;
            }
            if ($scope.newPassword != $scope.conFirmPassword) {
                toastr.error('Mat khau khong khop.');
                return;
            }
            if ($scope.newPassword.length < 6) {
                toastr.error('Mat khau phai co chieu dai lon hon 6.');
                return;
            }
        } else {
            if ($scope.newPassword != '' || $scope.conFirmPassword != '') {
                toastr.error('Nhap lai mat khau cu.');
                return;
            }
        }
        $scope.md_pass = forge.md.sha256.create();
        $scope.md_newpass = forge.md.sha256.create();
        $scope.currentpassword = ($scope.oldPassword == '') ? '' : $scope.md_pass.update($scope.oldPassword);
        $scope.newpassword = ($scope.newPassword == '') ? '' : $scope.md_newpass.update($scope.newPassword);
        $scope.renewpassword = $scope.conFirmPassword;
        $scope.dataChangePassword.currentpassword = $scope.md_pass.digest().toHex();
        $scope.dataChangePassword.newpassword = $scope.md_newpass.digest().toHex();
        return Login.changePassword($scope.dataChangePassword).success(function (data) {
            if (data.status) {
                toastr.success(data.msg);
                $window.location.href = 'users.html';
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.Showpoup = function () {
        var ePopup = '#changepassfirstlogin';
        var title = $(ePopup).find('> .title').html();
        var modal = JSON.parse($(ePopup).attr('data-dialog-modal'));
        var width = $(ePopup).attr('data-dialog-width');
        var options = {
            rounded: '10px',
            title: title,
            messageType: 'none',
            width: (width == undefined ? 550 : width),
            modal: modal,
            overlayColor: '#000000',
            overlayTransparent: .85
        }
        var popup = $(ePopup).dialog(options);
        popup.switchStateDialog("open");
    }
    $scope.addUsersData.supplieritems = [];
    $scope.logout = function () {
        return Login.logout().success(function (data) {
            $window.location.href = url_login;
        });
    }
    $scope.inactive = function (val) {
        return val == 1 ? false : true;
    }
    $scope.checkLogin = function () {
        return Login.checkLogin().success(function (data) {
            if (data.status == false) {
                console.log('false', data);
            } else {
                console.log('true', data);
            }
        });
    }
    // $scope.checkLogin();
    // sinhdang
    $scope.changeCallback = function (node, forFilter) {
        var __where = _.where(node[0].children, {
            selected: true
        });
        var __filter = new Array();
        for (var i = 0; i < __where.length; i++) {
            __filter = _.union(__filter, _.filter($scope.filterClientdata, function (item) {
                if (forFilter == 1) {
                    return item.positiontitles_name === __where[i]['label'];
                } else {
                    return item.departments_name === __where[i]['label'];
                }
            }));
        }
        return _.intersection($scope.filterClientdata, __filter);
    }
    $scope.ExportUsersList = function () {
        $ionicLoading.show({template: templateLoading});
        Users.exportUser($scope.users).success(function (data) {
            $ionicLoading.hide();
            var publicPos = url_site.indexOf("public");
            if(publicPos>-1){
                var link = data.data.replace('./../', url_site.replace('public', ''));
            }
            else{
                var link = data.data.replace('./../','');
                link = url_site+'/'+link;
            }
            $scope.cordovaBrowser(link, 'internal');
        });
    }
    //role
    $scope.viewPhoneNoneFieldworkerNoneMobile = function () {
        if (!$scope.onMobile) {
            if ($scope.roleName == $scope.isAdmin || $scope.roleName == $scope.isManager || $scope.roleName == $scope.isReporter || $scope.roleName == $scope.isScheduler) {
                return true;
            }
        } else {
            return false;
        }
    }
    $scope.viewPhoneWarehouseNoneMobile = function () {
        if (!$scope.onMobile) {
            if ($scope.roleName == $scope.isWarehouse) {
                return true;
            }
        } else {
            return false;
        }
    }
    $scope.viewPhoneFieldworkerNoneMobile = function () {
        if (!$scope.onMobile) {
            if ($scope.roleName == $scope.isFieldinstaller || $scope.roleName == $scope.isSalesman) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    // by sinhdang change select hide / input tag
    $scope.addUsersData.appointmentgroup_id = [];
    $scope.filterAllUser = function ($query, $switch) {
        switch ($switch) {
            case 1: // for app group
            return $scope.rootAppGroups.filter(function ($str) {
                return $str.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
            });
            break;
            case 2: // for app suplier item
            return $scope.rootSupplieritems.filter(function ($str) {
                return $str.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
            });
            break;
            default:
                //
            }
        };
        $timeout(function () {
            $scope.classDevice = isiOs ? 'ios' : 'android';
        }, 2000)

        $scope.getPositiontitles = function () {
        // if ($scope.posTitle.length > 0) return;
        $ionicLoading.show({
            template: templateLoading
        })
        Positiontitles.getSelect().success(function (data) {
            $ionicLoading.hide();
            $scope.positiontitles = data;
            $scope.posTitle = $scope.initNode('Position Title', data);
            $scope.getSupplieritems();
        });
    }



    $scope.redirectTo = function (url) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            $scope.initialEmployeeForSearch = [];
            redirectTo(url);
        }, 1000)
    }
    $scope.redirectToChat = function (id) {
        if (parseInt(id) != parseInt($scope.currentIdLogin)) {
            $ionicLoading.show({template: templateLoading});
            $timeout(function () {
                redirectTo('chat.html#/board/chat/' + id + '_');
            }, 1000)
        }
    }
    $scope.filterEmployeeForSearch = function (query) {
        var returnValue = {
            items: []
        };
        var params = {
            rows: 50,
            current_page: 1,
            search: query,
            showuser: 0
        };
        $('#temp-autocompletetemp-autocomplete .none-result').css('display','none');
        $scope.coundown = 10;
        if ($scope.myTime != null)
            clearInterval($scope.myTime);
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                clearInterval($scope.myTime);
                $ionicLoading.show({template: templateLoading});
                Users.getPaging(params).success(function (data) {
                    $scope.rootDataEmployees = data.data;
                    $scope.rootDataEmployees.forEach(function (item) {
                        item.name = item.first_name + ' ' + item.last_name + '-' + item.positiontitles_name;
                    })
                    // console.log(data);
                    $scope.rootDataEmployees.forEach(function (item) {
                        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                            returnValue.items.push(item);
                        }
                    })
                    $ionicLoading.hide();
                    if(returnValue.items.length > 0){
                        $('#temp-autocomplete .none-result').css('display','none');
                    }
                    else{
                        $('#temp-autocomplete .none-result').css('display','block');
                    }
                })
            }
        }, 100);
        return returnValue;
    }
    $scope.selectEmployeeFormSearch = function (callback) {
        // $scope.redirectTo('#/board/users/' + callback.item.id + '/' + callback.item.status);
        $scope.emitGetUserData(callback.item);
        $scope.initialEmployeeForSearch = [];
    }
    $scope.modelEmployeeForSearch = function (modelValue) {
        return
    };
    $scope.resizeScroll = function (id) {
        $ionicScrollDelegate.$getByHandle(id).resize();
    }
    $scope.openAutocomplete = function (className) {
        $scope.openByGetTemplate("ionAutocomplete");
        dataHtml.getTemplate('templates/dashboard/users/users/userSearchSettingmodal.tpl').success(function (results) {
            $scope.dataHtml.searchUser = results;
        });
        $timeout(function () {
            var ionAutocompleteElement = document.getElementsByClassName(className);
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
            $timeout(function() {
                angular.element('.backdrop').removeClass('visible').removeClass('active');
            }, 1000);
        }, 500)
    }
    $scope.inputChangeColor = function (color, type) {
        if (type == 'add') {
            angular.element("#addUsersDataColor").spectrum("set", color);
        } else {
            angular.element("#editUsersDataColor").spectrum("set", color);
        }
    }

    $scope.selectAddress = function(value,type) {
        if(type == 'adduser'){
            if($scope.holdValueAddress.addUserAddress.length>0){
                $scope.holdValueAddress.addUserAddress.splice(0,1);
            }
        }
        if(type == 'adduserstarlocation'){
            if($scope.holdValueAddress.addUserStarLocation.length>0){
                $scope.holdValueAddress.addUserStarLocation.splice(0,1);
            }
        }
        if(type == 'adduserassignlocation'){
            if($scope.holdValueAddress.addUserAssignLocation.length>0){
                $scope.holdValueAddress.addUserAssignLocation.splice(0,1);
            }
        }
        $scope.valueClone = value;
        var data = [];
        var componentAddressForm = {
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            postal_code: 'short_name'
        };
        LocationService.getDetails(value.place_id).then(function(location) {
            $scope.valueClone.description = location.formatted_address;
            angular.forEach(location.address_components, function(item) {
                var addressType = item.types[0];
                if (componentAddressForm[addressType]) {
                    var val = item[componentAddressForm[addressType]];
                    data[addressType] = val;
                }
            })
            if(type == 'adduser'){
                data['locality'] ? $scope.addUsersData.city = data['locality'] : $scope.addUsersData.city = '';
                data['administrative_area_level_1'] ? $scope.addUsersData.state = data['administrative_area_level_1'] : $scope.addUsersData.state = '';
                data['postal_code'] ? $scope.addUsersData.zipcode = data['postal_code'] : $scope.addUsersData.zipcode = '' ;
                $scope.addUsersData.street = location.formatted_address;
            }
            if(type == 'adduserstarlocation'){
                $scope.addUsersData.start_location = location.formatted_address;
            }
            if(type == 'adduserassignlocation'){
                $scope.addUsersData.assigned_location = location.formatted_address;
            }
        })
    };

    $scope.removetag = function(value,type) {
        if(type == 'adduser'){
            $scope.addUsersData.city = '';
            $scope.addUsersData.state = '';
            $scope.addUsersData.zipcode = '';
            $scope.addUsersData.street = '';
            $scope.holdValueAddress.addUserAddress = [];
        }
        if(type == 'adduserstarlocation'){
            $scope.addUsersData.start_location = '';
            $scope.holdValueAddress.addUserStarLocation = [];
        }
        if(type == 'adduserassignlocation'){
            $scope.addUsersData.assigned_location = '';
            $scope.holdValueAddress.addUserAssignLocation = [];
        }
    };

    if (!$stateParams.userID && page == "users.html") {
        $scope.renderTemplateData();
    }
    $scope.counterNotify = 0;
    $scope.$on('pushCounterChild',function(events,data){
        $scope.counterNotify = data;
    });

    $scope.$on('getJsonData', function (event, data) {
        var jsondata = data.data;
        var index = _.findIndex(jsondata,{roletree_id:'1'});
        var index1 = _.findIndex(jsondata[index].child,{roletree_id:'2'});
        if(jsondata[index].check && jsondata[index].child[index1].check){
            $scope.viewSearch                     = jsondata[index].child[index1].child[0].check;
            $scope.showCheckAllUser               = jsondata[index].child[index1].child[1].check;
            $scope.showAddUser                    = jsondata[index].child[index1].child[2].check;
            $scope.addFullUser                    = jsondata[index].child[index1].child[2].child[0].check;
            
            $scope.addUserOfDepartment            = jsondata[index].child[index1].child[2].child[1].check;
            $scope.addUserOfSuppervisor           = jsondata[index].child[index1].child[2].child[2].check;
            $scope.hideEditByRole                 = jsondata[index].child[index1].child[3].check;
            $scope.editFullUser                   = jsondata[index].child[index1].child[3].child[0].check;
            $scope.editUserOfDepartment           = jsondata[index].child[index1].child[3].child[1].check;
            $scope.editUserOfSuppervisor          = jsondata[index].child[index1].child[3].child[2].check;
            $scope.hideActiveByRole               = jsondata[index].child[index1].child[4].check;
            $scope.activeFullUser                 = jsondata[index].child[index1].child[4].child[0].check;
            $scope.activeUserOfDepartment         = jsondata[index].child[index1].child[4].child[1].check;
            $scope.activeUserOfSuppervisor        = jsondata[index].child[index1].child[4].child[2].check;
            $scope.hideBiweekByRole               = jsondata[index].child[index1].child[5].check;
            $scope.viewBiweeks                    = jsondata[index].child[index1].child[5].child[0].check;
            $scope.viewMyBiweeks                  = jsondata[index].child[index1].child[5].child[0].child[0].check;
            $scope.viewUsersBiweeks               = jsondata[index].child[index1].child[5].child[0].child[1].check;
            $scope.editBiweeks                    = jsondata[index].child[index1].child[5].child[1].check;
            $scope.editBiweeksFullUser            = jsondata[index].child[index1].child[5].child[1].child[0].check;
            $scope.editBiweeksUserOfDepartment    = jsondata[index].child[index1].child[5].child[1].child[1].check;
            $scope.editBiweeksUserOfSuppervisor   = jsondata[index].child[index1].child[5].child[1].child[2].check;
            $scope.hideNewfeedCheck               = jsondata[index].child[index1].child[6].check;
            $scope.checkNewfeedFullUser           = jsondata[index].child[index1].child[6].child[0].check;
            $scope.checkNewfeedUserOfDepartment   = jsondata[index].child[index1].child[6].child[1].check;
            $scope.checkNewfeedUserOfSuppervisor  = jsondata[index].child[index1].child[6].child[2].check;
            $scope.hideExportUser                 = jsondata[index].child[index1].child[7].check;
            $scope.hrInfo                         = $scope.roleName == $scope.isStrategicDevelopment ? false : true;
            if (!$stateParams.userID && page == "users.html") {
                $scope.renderTemplateData();
            }
        }else{
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
        }
    })
    $scope.$on('refreshUsers', function (event, args) {
        $scope.refreshUsers(args.data, args.dataValue);
    });

    $scope.$on('setConditionAdd', function (event, args) {
        if($scope.addFullUser && !$scope.addUserOfDepartment && !$scope.addUserOfSuppervisor){
            $scope.departments = $scope.orgDepartments;
        }else if($scope.addUserOfDepartment && !$scope.addUserOfSuppervisor){
            $scope.departments = _.where($scope.orgDepartments, {id:$scope.departmentId});
        }else if(!$scope.addUserOfDepartment && $scope.addUserOfSuppervisor){
            $scope.departments = $scope.orgDepartments;
            $scope.addUsersData.supervisor_user1 = parseInt($scope.currentIdLogin);
            setTimeout(function() {
                $scope.Input_value.supervisor_user1 = $scope.setValueForInput($scope.usersVisor, parseInt($scope.currentIdLogin)).nameWithpos;
                $scope.disabledSupSelect = true;
            }, 500);
        }else if(!$scope.addFullUser && $scope.addUserOfDepartment && $scope.addUserOfSuppervisor){
            $scope.departments = _.where($scope.orgDepartments, {id:$scope.departmentId});
            $scope.addUsersData.supervisor_user1 = parseInt($scope.currentIdLogin);
            setTimeout(function() {
                $scope.Input_value.supervisor_user1 = $scope.setValueForInput($scope.usersVisor, parseInt($scope.currentIdLogin)).nameWithpos;
                $scope.disabledSupSelect = true;
            }, 500);
        }
    });


    $scope.hideEditButton = function(item){
        if($scope.hideEditByRole){
            if($scope.editFullUser){
                return false;
            }else if(!$scope.editFullUser && $scope.editUserOfDepartment && !$scope.editUserOfSuppervisor){
                if(item.department_id == $scope.departmentId){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.editFullUser && !$scope.editUserOfDepartment && $scope.editUserOfSuppervisor){
                if(item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.editFullUser && $scope.editUserOfDepartment && $scope.editUserOfSuppervisor){
                if(item.department_id == $scope.departmentId || item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }
        }else{
            return true;
        }
    }

    $scope.hideDeleteButton = function(item){
        if($scope.hideEditByRole){
            if($scope.activeFullUser){
                return false;
            }else if(!$scope.activeFullUser && $scope.activeUserOfDepartment && !$scope.activeUserOfSuppervisor){
                if(item.department_id == $scope.departmentId){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.activeFullUser && !$scope.activeUserOfDepartment && $scope.activeUserOfSuppervisor){
                if(item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.activeFullUser && $scope.activeUserOfDepartment && $scope.activeUserOfSuppervisor){
                if(item.department_id == $scope.departmentId || item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }
        }else{
            return true;
        }
    }

    $scope.hideBiweeksButton = function(item){
        if($scope.viewMyBiweeks && $scope.viewUsersBiweeks){
            return false;
        }else if($scope.viewMyBiweeks && !$scope.viewUsersBiweeks){
            if(item.id == $scope.currentIdLogin){
                return false;
            }else{
                return true;
            }
        }else if(!$scope.viewMyBiweeks && !$scope.viewUsersBiweeks){
            return true;
        }else{
            if(item.id != $scope.currentIdLogin){
                return false;
            }else{
                return true;
            }
        }
    }

    $scope.setClickedDepartId = function(item) {
        $scope.disabledVal = true;
        $scope.columNumber = 2;
        if($scope.editBiweeksFullUser){
            $scope.disabledVal = false;
        }else if(!$scope.editBiweeksFullUser && $scope.editBiweeksUserOfDepartment && !$scope.editBiweeksUserOfSuppervisor){
            if(item.department_id == $scope.departmentId){
                return checkUpdateBiweeksAdmin(item.roleId);
            }else{
                $scope.columNumber = 1;
            }
        }else if(!$scope.editBiweeksFullUser && !$scope.editBiweeksUserOfDepartment && $scope.editBiweeksUserOfSuppervisor){
            if(item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                return checkUpdateBiweeksAdmin(item.roleId);
            }else{
                $scope.columNumber = 1;
            }
        }else if(!$scope.editBiweeksFullUser && $scope.editBiweeksUserOfDepartment && $scope.editBiweeksUserOfSuppervisor){
            if(item.department_id == $scope.departmentId || item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                return checkUpdateBiweeksAdmin(item.roleId);
            }else{
                $scope.columNumber = 1;
            }
        }
    }

    function checkUpdateBiweeksAdmin(roleId){
        if(!checkAdmin(roleId)){
            $scope.disabledVal = false;
        }else{
            $scope.disabledVal = true;
            $scope.columNumber = 1;
        }
    }

    $scope.hideCheckNewfeed = function(item){
        if($scope.hideNewfeedCheck){
            if($scope.checkNewfeedFullUser){
                return false;
            }else if(!$scope.checkNewfeedFullUser && $scope.checkNewfeedUserOfDepartment && !$scope.checkNewfeedUserOfSuppervisor){
                if(item.department_id == $scope.departmentId){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.checkNewfeedFullUser && !$scope.checkNewfeedUserOfDepartment && $scope.checkNewfeedUserOfSuppervisor){
                if(item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }else if(!$scope.checkNewfeedFullUser && $scope.checkNewfeedUserOfDepartment && $scope.checkNewfeedUserOfSuppervisor){
                if(item.department_id == $scope.departmentId || item.supervisor_user1 == $scope.currentIdLogin || item.supervisor_user2 == $scope.currentIdLogin){
                    return checkAdmin(item.roleId);
                }else{
                    return true;
                }
            }
        }else{
            return true;
        }

    }

    function checkAdmin(roleId){
        if($scope.roleName == $scope.isAdmin){
            return false;
        }else{
            if(roleId != '1'){
                return false;
            }else{
                return true;
            }
        }
    }

    $scope.$on('sendInactiveUser', function (event, args) {
        //var idx = _.findLastIndex($scope.users, {id: parseInt(args.id)})
        // switch ($scope.searchUsers.showUserStatus) {
        //     case 0:
        //     $scope.users.splice(idx, 1);
        //     break;
        //     case 1:
        //     if (idx != -1) {
        //         $scope.users[idx].status = args.status == "1" ? "0" : "1";
        //     }
        //     break;
        // }
        $scope.getUsers();
    });

    $scope.clickedMethodVehicles = function(callback, style) {
        if (style == 'add') {
            if($scope.addUsersData.assigned_vehicle == undefined){
                $scope.addUsersData.assigned_vehicle = [];
            }
            $scope.addUsersData.assigned_vehicle = callback.item ;
        }
    }
})
