var settings_pagesize = $('#settings_pagesize');
settingApp.controller('SettingsController', function ($ionicPopup, $cordovaToast, $ionicLoading, $ionicScrollDelegate, $scope, $http, //
    $rootScope, $window, $interval, Login, Appointmentgroups, Users, Settings, Tasks, $interval, dataHtml, $timeout, TagInputConfig) {
    $scope.tier = tier;
    $scope.currentPage = 1;
    var pager = localStorage.getItem('settings_pagesize');
    $scope.itemsPerPage = pager ? pager : 5;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchSettings = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: ""
    };
    $scope.currentIdLogin = currentIdLogin;
    withoutPopup_TG = $scope;
    $scope.ShowAll_TaskGroup = false;
    $scope.ShowAll_Appointmentype = 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.departmentId = departmentId;
    $scope.searchUsers = {
        rows: 50,
        current_page: 1,
        search: "",
        showuser: 1
    };
    $scope.check_init_settings = false;
    $scope.itemsPerPageAppType = pager ? pager : 50;
    $scope.searchAppointmentType = {
        rows: $scope.itemsPerPageAppType,
        current_page: $scope.currentPage,
        search: "",
        show_all: false
    };
    $scope.AddUserNewFeed = {};
    $scope.dataHtml = {};
    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/settings/settingsMenuHeadermodal.tpl').success(function (results) {
            $scope.dataHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/settings/settingsContentmodal.tpl').success(function (results) {
                $scope.dataHtml.settingsContent = results;
                $scope.getUsers();
            });
        });
    }
    $scope.openByGetTemplate = function (style) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            switch (style) {
                case 'popupSettingTaskGroup':
                console.log(style);
                dataHtml.getTemplate('templates/dashboard/settings/settingsTaskGroupManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.popupSettingTaskGroup = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupTaskGroupAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.popupSettingTaskGroupAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupTaskGroupEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.popupSettingTaskGroupEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupTaskGroupDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.popupSettingTaskGroupDelete = results;
                                showTarget('#popupSettingTaskGroup');
                                $ionicLoading.hide();
                            });

                        });
                    });
                });
                break;
                case 'settingNoteTaskManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsNoteTaskManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingNoteTaskManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupNoteTaskAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingNoteTaskManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupNoteTaskEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingNoteTaskManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupNoteTaskDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingNoteTaskManagementDelete = results;
                                showTarget('#settingNoteTaskManagement');
                                $ionicLoading.hide();
                            });

                        });
                    });
                });
                break;
                case 'settingLoginManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsLoginManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingLoginManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupLoginAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingLoginManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupLoginEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingLoginManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupLoginDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingLoginManagementDelete = results;
                                showTarget('#settingLoginManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'settingApptGroupManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsApptGroupManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingApptGroupManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptGroupAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingApptGroupManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptGroupEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingApptGroupManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptGroupDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingApptGroupManagementDelete = results;
                                showTarget('#settingApptGroupManagement');
                                $ionicLoading.hide();
                            });
                        });

                    });
                });
                break;
                case 'settingApptTypeManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsApptTypeManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingApptTypeManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptTypeAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingApptTypeManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptTypeEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingApptTypeManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupApptTypeDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingApptTypeManagementDelete = results;
                                showTarget('#settingApptTypeManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'settingNewsfeedTypeManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsNewsfeedTypeManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingNewsfeedTypeManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupNewfeedsAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingNewsfeedTypeManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupNewfeedsEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingNewsfeedTypeManagementEdit = results;
                            showTarget('#settingNewsfeedTypeManagement');
                            $ionicLoading.hide();
                        });
                    });
                });
                break;
                case 'popupEditSettingMarketingMessage':
                dataHtml.getTemplate('templates/dashboard/settings/settingsInvoiceMarketingMsgManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.popupEditSettingMarketingMessage = results;
                    $scope.loadMarketingMessage();
                    showTarget('#popupEditSettingMarketingMessage');
                    $ionicLoading.hide();
                });
                break;
                case 'settingSupplierManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsSupplierManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingSupplierManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupSupplierAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingSupplierManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupSupplierEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingSupplierManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupSupplierDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingSupplierManagementDelete = results;
                                showTarget('#settingSupplierManagement');
                                $ionicLoading.hide();
                            });

                        });
                    });
                });
                break;
                case 'settingPasswordManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsPasswordManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingPasswordManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupPasswordmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingPasswordManagementEdit = results;
                        showTarget('#settingPasswordManagement');
                        $ionicLoading.hide();
                    });
                });

                break;
                case 'settingRoomManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsRoomManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingRoomManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupRoomAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingRoomManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupRoomEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingRoomManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupRoomDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingRoomManagementDelete = results;
                                showTarget('#settingRoomManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'settingCouponManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsCouponManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingCouponManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupCouponAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingCouponManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupCouponEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingCouponManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupCouponDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingCouponManagementDelete = results;
                                showTarget('#settingCouponManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'popupSettingTaskGroupAdd':
                dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupTaskGroupmodal.tpl').success(function (results) {
                    $scope.dataHtml.popupSettingTaskGroupAdd = results;
                    appDialogToggle('open', '#popupSettingTaskGroupAdd');
                    $ionicLoading.hide();
                });
                break;
                case 'settingCriteriaManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsCriteriaManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingCriteriaManagement = results;
                    showTarget('#settingCriteriaManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'settingFeedTitleManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsFeedTitleManagement.tpl').success(function (results) {
                    $scope.dataHtml.settingFeedTitleManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupFeedTitleAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingFeedTitleManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupFeedTitleEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingFeedTitleManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupFeedTitleDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingFeedTitleManagementDelete = results;
                                showTarget('#settingFeedTitleManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'settingPositionTitleManagement':
                dataHtml.getTemplate('templates/dashboard/settings/settingsPositionTitleManagementmodal.tpl').success(function (results) {
                    $scope.dataHtml.settingPositionTitleManagement = results;
                    dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupPositionTitleAddmodal.tpl').success(function (results) {
                        $scope.dataHtml.settingPositionTitleManagementAdd = results;
                        dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupPositionTitleEditmodal.tpl').success(function (results) {
                            $scope.dataHtml.settingPositionTitleManagementEdit = results;
                            dataHtml.getTemplate('templates/dashboard/settings/settingsPopup/settingsPopupPositionTitleDeletemodal.tpl').success(function (results) {
                                $scope.dataHtml.settingPositionTitleManagementDelete = results;
                                showTarget('#settingPositionTitleManagement');
                                $ionicLoading.hide();
                            });
                        });
                    });
                });
                break;
                case 'optionSettingTaskGroup':
                dataHtml.getTemplate('templates/dashboard/settings/optionSettingTaskGroup.tpl').success(function (results) {
                    $scope.dataHtml.optionSettingTaskGroup = results;
                    showTarget('#optionSettingTaskGroup');
                    $ionicLoading.hide();
                });
                break;
                case 'optionSettingNoteTaskManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionSettingNoteTaskManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionSettingNoteTaskManagement = results;
                    showTarget('#optionSettingNoteTaskManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionApptGroupManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionApptGroupManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionApptGroupManagement = results;
                    showTarget('#optionApptGroupManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionApptTypeManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionApptTypeManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionApptTypeManagement = results;
                    showTarget('#optionApptTypeManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionSupplierManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionSupplierManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionSupplierManagement = results;
                    showTarget('#optionSupplierManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionRoomManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionRoomManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionRoomManagement = results;
                    showTarget('#optionRoomManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionCouponManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionCouponManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionCouponManagement = results;
                    showTarget('#optionCouponManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionFeedTitleManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionFeedTitleManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionFeedTitleManagement = results;
                    showTarget('#optionFeedTitleManagement');
                    $ionicLoading.hide();
                });
                break;
                case 'optionPositionTitleManagement':
                dataHtml.getTemplate('templates/dashboard/settings/optionPositionTitleManagement.tpl').success(function (results) {
                    $scope.dataHtml.optionPositionTitleManagement = results;
                    showTarget('#optionPositionTitleManagement');
                    $ionicLoading.hide();
                });
                break;
            }
        }, 500);
}
$scope.CreateUserNewFeed = function () {
    if ($scope.AddUserNewFeed.users.length > 0) {
            // if($scope.AddUserNewFeed.users.id)
            $('.tblloader_newsfeed').show();
            Settings.saveusernewfeed($scope.AddUserNewFeed, $scope.currentIdLogin).success(function (data) {
                $('.tblloader_newsfeed').hide();
                if (data.status) {
                    $scope.AddUserNewFeed = {};
                    toastr.success(data.msg);
                } else {
                    toastr.error(data.msg);
                }
                console.log(data);
            });
        } else {
            toastr.error('Not Null Send to');
        }
    }
    $scope.getSettings = function () {
        $('.loader').show();
        Settings.getPaging($scope.searchSettings).success(function (data) {
            $scope.settings = data.data;
            $scope.selectFeedTitle = data.Newfeedtypes;
            $('.loader').hide();
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchSettings.rows;
            settings_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            !$scope.check_init_settings ? $interval($scope.getDataTaskGroup) : '';
        });
    };
    $scope.marketingmessage = {};
    $scope.loadMarketingMessage = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate('settingInvoiceMarketingMsgManagement');
        Settings.loadMarketingMessage().success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $ionicLoading.hide();
                $scope.marketingmessage.data = data;
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.loadUsers = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate('settingPasswordManagement');
        Users.getPaging($scope.searchUsers).success(function (data) {
            $scope.userdata = data.data;
            $scope.userdataRoot = data.data;
            $scope.currentPageUsers = data.page;
            $scope.itemsPerPageUsers = $scope.searchUsers.rows;
            $scope.totalItemsUsers = data.total_rows;
            $ionicLoading.hide();
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.pageChangedUsers = function (currentPage) {
        $scope.searchUsers.current_page = currentPage;
        $scope.loadUsers();
    };
    $scope.keypress = function ($event) {
        var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
        if ($event.keyCode >= 112 && $event.keyCode <= 123)
            return;
        if (keysByCode.indexOf($event.keyCode) > -1)
            return;
        $scope.coundown = 10;
        if ($scope.myTime != null)
            clearInterval($scope.myTime);
        $scope.downTimer();
    };
    $scope.downTimer = function () {
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                clearInterval($scope.myTime);
                $scope.loadUsers();
            }
        }, 100);
    }
    $scope.updateMarketingMessage = function () {
        // console.log($scope.marketingmessage.data);
        if (!$scope.marketingmessage.data || $scope.marketingmessage.data.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.updatemarketingmessage({
            data: $scope.marketingmessage.data
        }).success(function (data) {
            closeTarget('#popupEditSettingMarketingMessage');
            $scope.loadMarketingMessage();
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };
    $scope.getAppointmentype = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate('settingApptTypeManagement');
        $scope.searchAppointmentType.show_all = $scope.ShowAll_Appointmentype;
        Appointmentgroups.getAppointmenType($scope.searchAppointmentType).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $ionicLoading.hide();
                $scope.appointmentype = data.data;
                $scope.totalItemsApptype = data.total_rows;
                $scope.appointmenGroupSelect = data.appointmentgroups;
            }
            
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    setTimeout(function () {
        $("#task-groupdata").trigger("click");
    }, 100);
    $scope.ShowActive_AT = function (show_all) {
        $scope.ShowAll_Appointmentype = show_all;
        $scope.getAppointmentype();
    }
    $scope.dataAppointmentType = {};
    $scope.createAppointmentType = function (formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Appointmentgroups.saveAppointmentType($scope.dataAppointmentType).success(function (data) {
            $scope.getAppointmentype();
            closeTarget('#settingApptTypeManagementAdd');
            if (data.status) {
                $scope.dataAppointmentType = {};
                $scope.Input_value = {};
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };
    $scope.editAppointmentType = function (id) {
        Appointmentgroups.show(id).success(function (data) {
            $scope.dataEditAppointmentType = data;
            $scope.setValueForApptGroup(data.parent_id);
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.updateAppointmentType = function (formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.dataEditAppointmentType.id;
        Appointmentgroups.update(id, $scope.dataEditAppointmentType).success(function (data) {
            $scope.getAppointmentype();
            closeTarget('#settingApptTypeManagementEdit');
            if (data.status) {
                $scope.dataEditAppointmentType = {};
                $scope.Input_value = {};
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.deleteAppointmenttypesData = {};
    $scope.confrimAppointmenttype = function (item) {
        $scope.deleteAppointmenttypesData = item;
    }
    // $scope.DeleteApptGroup = function() {
    //     closeTarget('#settingApptTypeManagementDelete')

    //             $ionicLoading.show({
    //                 template: templateLoading
    //             });
    //             Appointmentgroups.destroy(id, status).success(function(data) {
    //                 $scope.getAppointmentgroups();
    //                 if (data.status) {
    //                     $cordovaToast.showLongTop(data.msg);
    //                 } else {
    //                     $cordovaToast.showLongTop(data.msg);
    //                 }
    //             });

    // }
    $scope.deleteAppointmenttype = function () {
        var id = $scope.deleteAppointmenttypesData.id;
        var status = $scope.deleteAppointmenttypesData.status;
        $ionicLoading.show({
            template: templateLoading
        });
        Appointmentgroups.destroy(id, status).success(function (data) {
            closeTarget('#settingApptTypeManagementDelete');
            $scope.deleteAppointmenttypesData = {};
            $ionicLoading.hide();
            var idx = _.findLastIndex($scope.appointmentype, {id: id.toString()});
            if (data.status) {
                if ($scope.searchAppointmentType.show_all) {
                    $scope.appointmentype[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.appointmentype.splice(idx, 1);
                }
                $ionicScrollDelegate.$getByHandle('scrollAppointmentype').resize()
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });

    }
    $scope.searchChanged = function () {
        $scope.getSettings();
    }
    $scope.sizeChanged = function () {
        $scope.searchSettings.rows = $scope.entryLimit;
        settings_pagesize.val($scope.searchSettings.rows);
        localStorage.setItem('settings_pagesize', $scope.searchSettings.rows);
        $scope.searchSettings.current_page = 1;
        $scope.getSettings();
    }
    $scope.pageChanged = function () {
        console.log($scope.currentPage);
        $scope.searchSettings.current_page = $scope.currentPage;
        $scope.getSettings();
    };
    //$scope.getSettings();
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addSettingsData = {};
    $scope.createSettings = function () {
        console.log($scope.addSettingsData);
        Settings.save($scope.addSettingsData).success(function (data) {
            $scope.addSettingsData = {};
            $scope.getSettings();
            if (data.status) {
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.editSettingsData = {};
    $scope.editSettings = function (id) {
        $('.loader').show();
        Settings.show(id).success(function (data) {
            $('.loader').hide();
            $scope.editSettingsData = data;
        });
    }
    $scope.updateSettings = function () {
        var id = $scope.editSettingsData.id;
        $('.loader').show();
        Settings.update(id, $scope.editSettingsData).success(function (data) {
            $('.loader').hide();
            if (data.status) {
                $scope.editSettingsData = {};
                //$('#modal_edit_settings').modal('hide');
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
            $scope.getSettings();
        });
    }
    $scope.deleteSettingsData = {};
    $scope.deleteSettingsData = {};
    $scope.confrimSettings = function (id, title, content) {
        $scope.deleteSettingsData = {
            id: id
        };
        var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
            messageType: 'warning',
            titleIcon: 'remove',
            overlayTransparent: .75
        }, function () {
            $scope.deleteSettings(id, confirm);
        });
    }
    $scope.deleteSettings = function (id, confirm) {
        Settings.destroy(id).success(function (data) {
            $scope.deleteSettingsData = {};
            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.getSettings();
        });
    }
    $scope.getUserLogin = function () {
        return Login.getUserLogin().success(function (data) {

            if (data == false) {
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                $scope.imagePath = pathToPublic + data.image_pic;
                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;
                }
            }
            // Settings.getFeedTitle().success(function(data) {
            //     $scope.selectFeedTitle = data;
            //     $scope.getSettings();
            // });
        });
    }
    $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();
            }
        });
    }

    $scope.address = {};
    $scope.AddUserNewFeed.users = [];
    $scope.refreshAddresses = function (address) {
        if (address.length > 0) {
            var params = {
                search: address
            };
            Users.searchAssign(params).success(function (data) {
                var diff = differentArray(data, $scope.AddUserNewFeed.users);
                $scope.addresses = diff;
            })
        }
    };
    // for task createTask asana
    $scope.formData = {};
    $scope.getUsers = function () {
        $scope.userFollow = [];
        $ionicLoading.show({template: templateLoading});
        Users.getSelect().success(function (data) {
            $ionicLoading.hide();
            $scope.allUser = [];
            _.each(data, function (val, index) {
                // tam thoi loai bo trung
                // nick_name = val.display_name;
                // if (_.where($scope.allUser, {
                //     name: val.display_name
                // }).length > 0) {
                //     nick_name = val.display_name + val.id;
                // }
                nick_name = val.first_name + ' ' + val.last_name;
                var _item = {
                    id: val.id,
                    screen_name: nick_name + ' - ' + val.positiontitles_name,
                    name: nick_name,
                    imgprofile: val.image_pic,
                    email: val.email
                }
                $scope.allUser.push(_item);
            });
            $scope.currentIdLogin = parseInt($scope.currentIdLogin);
            // $scope.allUser = _.filter($scope.allUser, function(val) {
            //     return val.id != $scope.currentIdLogin;
            // });
        });
    };
    // $scope.filterFollow = function($query) {
    //     var qStringUser = [];
    //     ($scope.formData.assign == undefined || $scope.formData.assign == '') ? qStringUser = $scope.allUser: qStringUser = _.filter($scope.allUser, function(val) {
    //         return val.id != parseInt($scope.formData.assign.id);
    //     });
    //     return qStringUser.filter(function(user) {
    //         return user.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
    //     });
    // };
    // change assign
    $scope.onSelectCreate = function ($item, $model, $label) {
        if (_.filter($scope.userFollow, function (val) {
            return parseInt(val.id) == parseInt($item.id);
        }).length > 0) {
            setTimeout(function () {
                $scope.$apply(function (val) {
                    $('#holdTCAssign').val('');
                    toastr.warning('User exits in Follower');
                });
            }, 1);
            return;
        }
    }
    $scope.resetTaskGroupAdd = function () {
        $scope.userFollow = [];
        $scope.formData = {};
        $scope.initialFollower = [];
        $scope.initialAssignUser = [];

    }
    $scope.createTaskGroup = function (formValide) {
        if (formValide.$invalid || !$scope.formData.assign || $scope.formData.assign.length == 0 || $scope.userFollow.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        var objParam = _.extend(this.formData, {
            usersfollow: $scope.userFollow,
        });
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.createTaskGroup(objParam).success(function (data) {
            $scope.getDataTaskGroup();
            if (data.status) {
                closeTarget("#popupSettingTaskGroupAdd");
                $scope.resetTaskGroupAdd();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.formDataedit = [];
    $scope.gettaskgroupdataEdit = function (id) {
        Tasks.getDataGroup(id).success(function (data) {
            $scope.userFollow = [];
            var arr = [];
            angular.forEach(data.follow, function (item) {
                arr.push(item.id);
            })
            $scope.initialFollowerEdit = arr;
            $scope.initialAssignUserEdit = [data.assige.id];
            $scope.formDataedit.name = data.groups.name;
            $scope.formDataedit.status = data.groups.status;
            $scope.formDataedit.id = data.groups.id;
            showTarget("#popupSettingTaskGroupEdit");
            // console.log($scope.formDataedit);
        });
    }
    $scope.ActiveCoupon = false;
    $scope.loadCoupon = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.openByGetTemplate('settingCouponManagement');
        Settings.getCoupon($scope.ActiveCoupon).success(function (data) {
            $scope.coupon = data;
            $ionicLoading.hide();
            $timeout(function () {
                $ionicScrollDelegate.$getByHandle('scrollCouponContent').scrollTop();
            }, 1000);
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.viewAllCoupon = function () {
        $scope.ActiveCoupon == false ? $scope.ActiveCoupon = true : $scope.ActiveCoupon = false;
        $scope.loadCoupon();
    }
    $scope.addCoupondata = {};
    $scope.editCoupondata = {};
    $scope.addCoupondata.type = "%";
    $scope.addCoupon = function (formValide) {
        if (formValide.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.addCoupon($scope.addCoupondata).success(function (data) {
            if (data.status) {
                $ionicLoading.hide();
                $scope.loadCoupon();
                closeTarget('#settingCouponManagementAdd');
                $scope.addCoupondata = {};
                $cordovaToast.showLongTop(data.msg);
            } else {
                $ionicLoading.hide();
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.editCoupon = function (formValide) {
        if (formValide.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.editCoupon($scope.editCoupondata).success(function (data) {
            $ionicLoading.hide();
            $scope.loadCoupon();
            if (data.status) {
                closeTarget('#settingCouponManagementEdit');
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.getEditCoupon = function (id) {
        $ionicLoading.show({template: templateLoading})
        Settings.getEditCoupon(id).success(function (data) {
            $ionicLoading.hide();
            $scope.editCoupondata = data.data;
            $scope.Input_value.typeEditCoupon = $scope.editCoupondata.type;
        });
    }
    $scope.ShowActiveCoupon = function (show) {
        $scope.loadCoupon();
    }
    $scope.deleteCouponData={};
    $scope.confrimCoupon = function (item) {
        $scope.deleteCouponData=item;
    }
    $scope.deleteCoupon = function () {
        var id=$scope.deleteCouponData.id;
        var status=$scope.deleteCouponData.status;
        $ionicLoading.show({template: templateLoading});
        Settings.deleteCoupon(id, status).success(function (data) {
            $ionicLoading.hide();
            closeTarget('#settingCouponManagementDelete');
            var idx = _.findLastIndex($scope.coupon, {id: id});
            if (data.status) {
                if ($scope.ActiveCoupon) {
                    $scope.coupon[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.coupon.splice(idx, 1);
                }
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.infoCoupon = {};
    $scope.openPopupCouponOption = function (id, status) {
        $scope.infoCoupon.id = parseInt(id);
        $scope.infoCoupon.status = status;
        $scope.getEditCoupon(id);
        appDialogToggle('open', '#popupSettingCouponOption');
    }

    $scope.ActiveCriteria = false;
    $scope.criteria = {};

    $scope.loadCriteria = function () {
        $scope.criteria.data1 = [];
        $scope.criteria.data2 = [];
        $scope.criteria.data3 = [];
        $scope.openByGetTemplate("settingCriteriaManagement");
        $ionicLoading.show({template: templateLoading});
        Settings.getCriteria($scope.ActiveCriteria).success(function (data) {
            $ionicLoading.hide();
            var criterias = _.indexBy(data, 'name');
            var data1 = criterias['Criteria#1'].contents != "" ? criterias['Criteria#1'].contents.split(';') : [];
            var data2 = criterias['Criteria#2'].contents != "" ? criterias['Criteria#2'].contents.split(';') : [];
            var data3 = criterias['Criteria#3'].contents != "" ? criterias['Criteria#3'].contents.split(';') : [];
            if (data1.length > 0) {
                data1.forEach(function (itm) {
                    $scope.criteria.data1.push({value: itm});
                })
            }

            if (data2.length > 0) {
                data2.forEach(function (itm) {
                    $scope.criteria.data2.push({value: itm});
                })
            }

            if (data3.length > 0) {
                data3.forEach(function (itm) {
                    $scope.criteria.data3.push({value: itm});
                })
            }

        });
    }
    // var tagInputCriteria1 = TagInputConfig.getByHandle('criteria1');
    // tagInputCriteria1.onTagAdded(function(tag) {
    //     console.log('added');
    //     console.log(tag);
    //     console.log($scope.criteria1)
    // })
    // tagInputCriteria1.onTagRemoved(function(tag) {
    //         console.log('remove');
    //         console.log(tag);
    //         console.log($scope.criteria1)
    //     })

    $scope.updateCriteria = function () {
        // console.log($scope.criteria);
        var dataCriteria = {
            'Criteria#1': _.pluck($scope.criteria.data1, 'value').join(';'),
            'Criteria#2': _.pluck($scope.criteria.data2, 'value').join(';'),
            'Criteria#3': _.pluck($scope.criteria.data3, 'value').join(';')
        };
        // console.log(dataCriteria);
        $ionicLoading.show({template: templateLoading});
        Settings.updateCriteria(dataCriteria).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                closeTarget('#settingCriteriaManagement');
                $codovaToast.showLongTop(data.msg);
            } else {
                $codovaToast.showLongTop(data.msg);
            }
        });
    }

    $scope.EditTaskGroup = function (formValide) {
        if (formValide.$invalid || !$scope.formDataedit.assign || $scope.formDataedit.assign.length == 0 || $scope.userFollow.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        var objParams = _.extend(this.formDataedit, {
            usersfollow: $scope.userFollow,
        });
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.EditTaskGroup($scope.formDataedit.assign, $scope.formDataedit.name, $scope.formDataedit.status, $scope.formDataedit.id, $scope.userFollow).success(function (data) {
            $scope.getDataTaskGroup();
            if (data.status) {
                closeTarget("#popupSettingTaskGroupEdit")
                $scope.userFollow = [];
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.openAutocomplete = function (className) {
        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);
    }
    $scope.filterAssignUserForChangePassword = function (query, style) {
        var returnValue = {
            items: []
        };
        $scope.allUser.forEach(function (item) {
            item.screen_name= item.name + '-' + item.email;
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
            } else if (item.email.toString().indexOf(query) > -1) {
                returnValue.items.push(item);
            }
        });
        return returnValue;
    };
    $scope.onSelectAssginUserForChangePassword = function (callback) { // change assign
       $scope.forgotPassword(callback.item);
       $scope.initialAssignUserChangePassword=[];
   }
   $scope.forgotPassword = function (item) {
    $ionicLoading.show({
        template: templateLoading
    });
    return Login.forgotPassword(item.email).success(function (data) {
        showTarget('#settingPasswordManagementEdit');
        $scope.forgotPasswordCode = data.code;
        $scope.forgotPasswordEmail = item.email;
        $scope.dataPassword = {};
        $scope.dataPassword.name=item.name;
        $ionicLoading.hide();
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}
$scope.dataPassword = {}
$scope.resetPassword = function (formValide) {
    if (formValide.$invalid) {
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.dataResetPassword = {};
    $scope.dataResetPassword.email = $scope.forgotPasswordEmail;
    $scope.dataResetPassword.codeReset = $scope.forgotPasswordCode;
    $scope.dataResetPassword.md_pass = forge.md.sha256.create();
    $scope.dataResetPassword.md_newpass = forge.md.sha256.create();
    $scope.dataResetPassword.newpassword = $scope.dataPassword.newpassword;
    $scope.dataResetPassword.renewpassword = $scope.dataPassword.renewpassword;
    if ($scope.dataResetPassword.newpassword !== $scope.dataResetPassword.renewpassword) {
        $cordovaToast.showLongTop("The password does not match.");
        return;
    }
    if ($scope.dataResetPassword.newpassword.length < 6) {
        $cordovaToast.showLongTop('The password must be at least 6 characters.');
        return;
    }
    $scope.dataResetPassword.newpasswordTohex = ($scope.dataResetPassword.newpassword == '') ? '' : $scope.dataResetPassword.md_pass.update($scope.dataResetPassword.newpassword);
    $scope.dataResetPassword.renewpasswordTohex = ($scope.dataResetPassword.renewpassword == '') ? '' : $scope.dataResetPassword.md_newpass.update($scope.dataResetPassword.renewpassword);
    $scope.dataResetPassword.newpasswordTohex = $scope.dataResetPassword.md_newpass.digest().toHex();
        // return 
        $ionicLoading.show({
            template: templateLoading
        });
        return Login.resetPassword($scope.dataResetPassword).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.dataPassword = {}
                closeTarget('#settingPasswordManagementEdit');
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    //    $scope.deleteTaskGroup = {};
    // $scope.deleteTaskGroup = {};
    // $scope.confrimTaskGroup = function(id,title, content){
    //  $scope.deleteTaskGroup={id:id};
    //  var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
    //      messageType: 'warning',
    //      titleIcon: 'remove',
    //      overlayTransparent: .75
    //  },
    //  function() {
    //      $scope.DeleteTaskGroup(id,confirm);
    //  });
    // }
    // $scope.DeleteTaskGroup = function(id,confirm){
    //  Settings.destroy(id).success(function(data){
    //      $scope.deleteSettingsData = {};
    //      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.getSettings();
    //  });
    // }
    $scope.confirmDeleteTaskGroup = function (item) {
        $scope.deleteTaskGroup = item;
        showTarget('#popupSettingTaskGroupDelete');
    }
    $scope.DeleteTaskGroup = function () {
        var id = $scope.deleteTaskGroup.id;
        var status = $scope.deleteTaskGroup.status;
        $ionicLoading.show({
            template: templateLoading
        });
        Settings.DeleteTaskGroup(id, status).success(function (data) {
            $ionicLoading.hide();
            closeTarget('#popupSettingTaskGroupDelete');
            var idx = _.findLastIndex($scope.TaskGroupData, {id: id});
            if (data.status) {
                if ($scope.ShowAll_TaskGroup) {
                    $scope.TaskGroupData[idx].status = status == "1" ? "0" : "1";
                } else {
                    $scope.TaskGroupData.splice(idx, 1);
                }
                $ionicScrollDelegate.$getByHandle('scrollTaskGroup').resize()
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });

    }
    $scope.TaskGroupData = [];
    $scope.getDataTaskGroup = function () {
        $ionicLoading.show({
            template: templateLoading
        });
        var total = 200;
        var page = $scope.currentPageTaskGroup ? $scope.currentPageTaskGroup : 1;
        Settings.getDataTaskGroup(page, total, $scope.ShowAll_TaskGroup).success(function (data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                $scope.TaskGroupData = data.data;
                $scope.totalItemsTaskGroup = data.total_rows;
                $scope.itemsPerPageTaskGroup = data.rows;
                $scope.currentPageTaskGroup = data.page;
                $ionicLoading.hide();
                !$scope.check_init_settings ? $interval($scope.checkLogin, time_refresh) : '';
                request_notify_get_chat = true;
                $scope.check_init_settings = true;
            }
        });
    }
    //$scope.getDataTaskGroup();
    $scope.ShowActive_TG = function (show_all) {
        $scope.ShowAll_TaskGroup = show_all;
        $scope.getDataTaskGroup();
    }
    $scope.pageChanged = function (action, id, index, page) {
        $scope.currentPageTaskGroup = page;
        $scope.getDataTaskGroup();
    };
    $scope.pageChangedApptype = function () {
        $scope.searchAppointmentType.current_page = $scope.currentPageApptype;
        $scope.getAppointmentype();
    };
    

    $scope.autocompleteList = {};
    $scope.filterAssignUser = function (query, style) {
        var returnValue = {
            items: []
        };
        var id = style == 'add' ? $scope.autocompleteList.refferedAssignUser : $scope.autocompleteList.refferedAssignUserEdit;
        $scope.allUser.forEach(function (item) {
            var count = _.filter($scope.userFollow, function (val) {
                return parseInt(val.id) == parseInt(item.id);
            });
            if (id != item.id && count.length == 0) {
                if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                } else if (item.id.toString().indexOf(query) > -1) {
                    returnValue.items.push(item);
                }
            }
        });
        return returnValue;
    };
    // $interval(function(){
    //     console.log( $scope.initialAssignUser, $scope.initialFollower);
    // },1000);
    $scope.initialAssignUser = [];
    $scope.initialAssignUserEdit = [];
    $scope.setValueForAssignUser = function (modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            if ($scope.allUser[i].id == modelValue) {
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.onSelectAssginUser = function (callback, style) { // change assign
        if (style == 'add') {
            $scope.formData.assign = callback.item;
        } else {
            $scope.formDataedit.assign = callback.item;
        }
        // console.log($scope.formData.assign);
    }
    $scope.onRemoveAssginUser = function (callback, style) {
        if (style == 'add') {
            $scope.formData.assign = [];
        } else {
            $scope.formDataedit.assign = [];
        }
        // console.log($scope.formData.assign)
    }
    $scope.filterUser = function (search) {
        $scope.userdata = _.filter($scope.userdataRoot, function (val) {
            return val.user_name.toLowerCase().indexOf(search.toLowerCase()) != -1;
        });
        $ionicScrollDelegate.$getByHandle('userPasswordContent').resize();
    }
    $scope.filterFollow = function (query, style) {
        var assignId = -1;
        if (style == 'add' && $scope.formData.assign) {
            assignId = $scope.formData.assign.id;
        } else if (style == 'edit' && $scope.formDataedit.assign) {
            assignId = $scope.formDataedit.assign.id;
        }
        var returnValue = {
            items: []
        };
        var listIdArray = style == 'add' ? $scope.autocompleteList.refferedFollowerAdd : $scope.autocompleteList.refferedFollowerEdit;
        $scope.allUser.forEach(function (item) {
            if (listIdArray.indexOf(item.id) < 0) {
                if (parseInt(item.id) != parseInt(assignId)) {
                    if (item.screen_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.initialFollower = [];
    $scope.initialFollowerEdit = [];
    $scope.setValueForFollower = function (modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            // console.log($scope.allUser[i].id,modelValue)
            if ($scope.allUser[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.onSelectFollower = function (callback) {
        if ($scope.userFollow.indexOf(callback.item) < 0)
            $scope.userFollow.push(callback.item);
        // console.log($scope.userFollow);
    }
    $scope.onRemoveFollower = function (callback) {
        // if ($scope.roleName == $scope.isSalesman || $scope.roleName == $scope.isFieldinstaller) {
        //     return false;
        // }
        var index = $scope.userFollow.indexOf(callback.item);
        $scope.userFollow.splice(index, 1);
        // console.log($scope.userFollow);
    }
    $scope.infoTaskGroupAction = {};
    $scope.openPopupTaskGroupOption = function (id, status) {
        $scope.infoTaskGroupAction.id = id;
        $scope.infoTaskGroupAction.status = status;
        $scope.gettaskgroupdataEdit(id);
        showTarget('#popupSettingTaskGroupEdit');
    }
    $scope.Input_value = {};
    $scope.setValueForApptGroup = function (id) {
        $scope.Input_value.apptgroup = "";
        var index = _.findLastIndex($scope.appointmenGroupSelect, {
            id: id
        });
        if (index >= 0)
            $scope.Input_value.apptgroup = $scope.appointmenGroupSelect[index].name;
    }
    $scope.setValueForCouponType = function (val, type) {
        $scope.Input_value.typeAddCoupon = "";
        $scope.Input_value.typeEditCoupon = "";
        if (type == 'add') {
            $scope.Input_value.typeAddCoupon = val;
        } else {
            $scope.Input_value.typeEditCoupon = val;
        }
    }

    $scope.infoApptType = {};
    $scope.openPopupApptGroupOption = function (id, status) {
        $scope.infoApptType.id = parseInt(id);
        $scope.infoApptType.status = status;
        $scope.editAppointmentType(id);
        appDialogToggle('open', '#popupSettingApptTypeOption');
    }

    $scope.setIndexView = function(index,type){
        switch (type) {
            case 'taskgroup':
            $scope.index_option_task_group=index;
            $timeout( function(){
                $('#btn-view-option-task-group-'+index).next('.quick-popup').addClass('show');
            }, 100);
            break;
            case 'appointmentype':
            $scope.index_option_appointmen_type=index;
            $timeout( function(){
                $('#btn-view-option-appointmen-type-'+index).next('.quick-popup').addClass('show');
            }, 100);
            break;
            case 'changepassword':
            $scope.index_option_change_password=index;
            $timeout( function(){
                $('#btn-view-option-change-password-'+index).next('.quick-popup').addClass('show');
            }, 100);
            break;
            case 'coupon':
            $scope.index_option_coupon=index;
            $timeout( function(){
                $('#btn-view-option-coupon-'+index).next('.quick-popup').addClass('show');
            }, 100);
            break;
        }
    }

    function checkViewClientRole(jsonDataObj){
        $scope.viewTabTaskGr = jsonDataObj.child[0].check;
        $scope.viewTaskGr = jsonDataObj.child[0].child[0].check;
        $scope.addTaskGr = jsonDataObj.child[0].child[1].check;
        $scope.editTaskGr = jsonDataObj.child[0].child[2].check;
        $scope.deleteTaskGr = jsonDataObj.child[0].child[3].check;

        $scope.viewTabNoteTaskOp = jsonDataObj.child[1].check;
        $scope.viewNoteTaskOp = jsonDataObj.child[1].child[0].check;
        $scope.addNoteTaskOp = jsonDataObj.child[1].child[1].check;
        $scope.editNoteTaskOp = jsonDataObj.child[1].child[2].check;
        $scope.deleteNoteTaskOp = jsonDataObj.child[1].child[3].check;

        $scope.viewTabLogin = jsonDataObj.child[2].check;
        $scope.viewLogin = jsonDataObj.child[2].child[0].check; 
        $scope.addLogin = jsonDataObj.child[2].child[1].check; 
        $scope.editLogin = jsonDataObj.child[2].child[2].check; 
        $scope.deleteLogin = jsonDataObj.child[2].child[3].check;

        $scope.viewTabAppointmentGr = jsonDataObj.child[3].check;
        $scope.viewAppointmentGr = jsonDataObj.child[3].child[0].check;  
        $scope.addAppointmentGr = jsonDataObj.child[3].child[1].check;  
        $scope.editAppointmentGr = jsonDataObj.child[3].child[2].check;  
        $scope.deleteAppointmentGr = jsonDataObj.child[3].child[3].check;

        $scope.viewTabAppointmentType = jsonDataObj.child[4].check; 
        $scope.viewAppointmentType = jsonDataObj.child[4].child[0].check;
        $scope.addAppointmentTypeBut = jsonDataObj.child[4].child[1].check;
        $scope.editAppointmentTypeBut = jsonDataObj.child[4].child[2].check;
        $scope.deleteAppointmentTypeBut = jsonDataObj.child[4].child[3].check;

        $scope.viewTabNewfeedType = jsonDataObj.child[5].check;
        $scope.viewNewfeedType = jsonDataObj.child[5].child[0].check;
        $scope.addNewfeedType = jsonDataObj.child[5].child[1].check;
        $scope.editNewfeedType = jsonDataObj.child[5].child[2].check;

        $scope.viewTabMarketingMessage = jsonDataObj.child[6].check;
        $scope.viewMarketingMessage = jsonDataObj.child[6].child[0].check;
        $scope.editMarketingMessage = jsonDataObj.child[6].child[1].check;

        $scope.viewTabSupplierItems = jsonDataObj.child[7].check;
        $scope.viewSupplierItems = jsonDataObj.child[7].child[0].check;
        $scope.addSupplierItems = jsonDataObj.child[7].child[1].check;
        $scope.editSupplierItems = jsonDataObj.child[7].child[2].check;
        $scope.deleteSupplierItems = jsonDataObj.child[7].child[3].check;

        $scope.viewTabChangePassword = jsonDataObj.child[8].check;
        $scope.viewChangePassword = jsonDataObj.child[8].child[0].check;
        $scope.editChangePassword = jsonDataObj.child[8].child[1].check;

        $scope.viewTabRooms = jsonDataObj.child[9].check;
        $scope.viewRooms = jsonDataObj.child[9].child[0].check;
        $scope.addRoomBut = jsonDataObj.child[9].child[1].check;
        $scope.editRoomBut = jsonDataObj.child[9].child[2].check;
        $scope.deleteRoomBut = jsonDataObj.child[9].child[3].check;

        $scope.viewTabCoupon = jsonDataObj.child[10].check;
        $scope.viewCoupon = jsonDataObj.child[10].child[0].check;
        $scope.addCouponBut = jsonDataObj.child[10].child[1].check;
        $scope.editCouponBut = jsonDataObj.child[10].child[2].check;
        $scope.deleteCouponBut = jsonDataObj.child[10].child[3].check;

        $scope.viewTabCriteria = jsonDataObj.child[11].check;
        $scope.viewCriteria = jsonDataObj.child[11].child[0].check;
        $scope.editCriteria = jsonDataObj.child[11].child[1].check;

        $scope.viewTabFeedTitle = jsonDataObj.child[12].check;
        $scope.viewFeedTitle = jsonDataObj.child[12].child[0].check;
        $scope.addFeedTitle = jsonDataObj.child[12].child[1].check;
        $scope.editFeedTitle = jsonDataObj.child[12].child[2].check;
        $scope.deleteFeedTitle = jsonDataObj.child[12].child[3].check;

        $scope.viewTabPositionTitile = jsonDataObj.child[13].check;
        $scope.viewPositionTitile = jsonDataObj.child[13].child[0].check;
        $scope.addPositionTitile = jsonDataObj.child[13].child[1].check;
        $scope.editPositionTitile = jsonDataObj.child[13].child[2].check;
        $scope.deletePositionTitile = jsonDataObj.child[13].child[3].check;
        
        $scope.viewTabRingGroup = jsonDataObj.child[14].check;
        $scope.viewRingGroup = jsonDataObj.child[14].child[0].check;
        $scope.addRingGrBut = jsonDataObj.child[14].child[1].check;
        $scope.editRingGrBut = jsonDataObj.child[14].child[2].check;
        $scope.deleteRingGrBut = jsonDataObj.child[14].child[3].check;
    }

    $scope.$on('getJsonData', function (event, args) {
        var jsondata = args.data;
        var index = _.findIndex(jsondata,{roletree_id:'94'});

        if(jsondata[index].check){
            checkViewClientRole(jsondata[index]);
            if (page == 'settings.html')
                $scope.renderTemplateData();
        }else{
            localStorage.setItem("login_status", "0");
            redirectTo('index.html');
        }
    });
    // end edit
})
