paymentApp.controller('paymentCtrl', function ($ionicHistory, $cordovaFile, $cordovaActionSheet, //
        $cordovaCamera, $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $interval, $cordovaToast, //
        $ionicLoading, $ionicPopup, $scope, $http, $window, $interval, Login, Paymenthistories, Orders, ivhTreeviewMgr, Ordertypes, dataHtml,Users) {
    searchPaymentHandle();

    function searchPaymentHandle() {
        toggleDelegateHandle('#payment_page', '.link-payment-search', '.payment-search');
        toggleDelegateHandle('#payment_page', '.payment-search .search-type .btn-close', '.payment-search');
        toggleDelegateHandle('#payment_page', '.payment-search .search-content .btn-close', '.payment-search');
        closeOutsideHandle('.link-payment-search, .payment-search', '.payment-search');
    }
    $scope.currentIdLogin = currentIdLogin;
    $scope.currentPage = 1;
    var pager = 50;
    $scope.itemsPerPage = pager ? pager : '50';
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchPaymenthistories = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: ""
    };
    $scope.searchPaymenthistories = {};
    $scope.searchPaymenthistories.rows = $scope.itemsPerPage;
    $scope.searchPaymenthistories.current_page = 1;
    //$scope.searchPaymenthistories.submitType = 'view';
    //$scope.searchPaymenthistories.dateType = 'payment';
    // $scope.searchPaymenthistories.invoiceEstimate = [];
    // $scope.searchPaymenthistories.paymentMethod = [];
    // $scope.searchPaymenthistories.arrPaymentMethodId = [];
    // $scope.searchPaymenthistories.createdUser = [];
    // $scope.searchPaymenthistories.modifiedUser = [];
    // $scope.searchPaymenthistories.paymentUser = [];
    // $scope.searchPaymenthistories.status = [];
    // $scope.searchPaymenthistories.arStatusId = [];
    $scope.searchPaymenthistories.paymenthistoriesDate = {};
    $scope.searchPaymenthistories.app = true;
    $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.check_init_payment = false;
    $scope.setTime = false;
    $scope.checkLoadMore = false;
    $scope.showPicker = false;
    // $scope.searchPaymenthistories.paymenthistoriesDate.from_date = moment().add(-2, 'years').format('MM/DD/YYYY');;
    // $scope.searchPaymenthistories.paymenthistoriesDate.to_date = moment().format('MM/DD/YYYY');
    $scope.setTime = false;
    $scope.time = {};
    $scope.time.start = moment().add(-90, 'days').format('MM/DD/YYYY');
    $scope.time.end = moment().format('MM/DD/YYYY');
    $scope.dataPaymentHtml = {};
    $scope.dataPaymentHtml.totalItems = 0;
    $scope.dataPaymentHtml.currentCountItems = 0;
    $scope.arrPaymentMethod = [{'type': 'Cash', 'label': 'Cash', 'level': '1'},
    {'type': 'CC Manual', 'label': 'CC Manual', 'level': '1'},
    {'type': 'Check', 'label': 'Check', 'level': '1'},
    {'type': 'Prepaid', 'label': 'Prepaid', 'level': '1'},
    {'type': 'Wells Fargo Plan', 'label': 'Wells Fargo Plan', 'level': '1'},
    {'type': 'Payment Plan', 'label': 'Payment Plan', 'level': '1'},
    ];
    $scope.dataFilterPayment = {};
    $scope.dataFilterPayment.arrinvoiceEstimateId =[];
    $scope.dataFilterPayment.arrPaymentMethodId = [];
    $scope.dataFilterPayment.arrCreatedUserId = [];
    $scope.dataFilterPayment.arrModifiedUserId = [];
    $scope.dataFilterPayment.arrPaymentUserId = [];
    $scope.dataFilterPayment.arStatusId = [];

    $scope.dataFilterPayment.status = [];
    $scope.Input_value = {};
    $scope.sortby = {};

    $scope.autocompleteList = {};
    $scope.autocompleteList.estimateInvoice = [];
    $scope.autocompleteList.paymentMethod = [];
    $scope.autocompleteList.createdUser = [];
    $scope.autocompleteList.modifiedUser = [];
    $scope.autocompleteList.paymentUser = [];
    $scope.autocompleteList.status = [];
    $scope.paymentStatusSelect = [];
    $scope.status_payment_well_fargo = [
        { id: '0', name: 'Non-Deposited' },
        { id: '1', name: 'Deposited' },
        ];
    $scope.renderTemplateData = function () {
        dataHtml.getTemplate('templates/dashboard/payment/paymentMenuHeadermodal.tpl').success(function (results) {
            $scope.dataPaymentHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/payment/paymentContentmodal.tpl').success(function (results) {
                $scope.dataPaymentHtml.paymentContent = results;
                dataHtml.getTemplate('templates/dashboard/payment/paymentQueryTimemodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.queryTime = results;
                    dataHtml.getTemplate('templates/dashboard/payment/paymentPopupSearchmodal.tpl').success(function (results) {
                        $scope.dataPaymentHtml.searchPayment = results;
                        $timeout(function () {
                            $timeout(function () {
                                setHeight("#main-content");
                            }, 1)
                            $scope.getUserLogin();
                            $scope.searchPaymentStatus();
                            $scope.getAllUsers();
                        }, 500);
                    });
                });
            });
        });
    }
    $scope.openByGetTemplate = function (style) {
        $ionicLoading.show({template: templateLoading});
        $timeout(function () {
            switch (style) {
                case 'popupPaymentFilter':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupFiltermodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentFilter = results;
                    $scope.showTarget('#popupPaymentFilter');
                    $ionicLoading.hide();
                });
                break;

                case 'confirmDeletePayment':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupDeletemodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.confirmDeletePayment = results;
                    $scope.showTarget('#confirmDeletePayment');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentNote':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupNotemodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentNote = results;
                    $scope.showTarget('#popupPaymentNote');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentCollectionCallLog':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupCollectionCallLogmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentCollectionCallLog = results;
                    $scope.showTarget('#popupPaymentCollectionCallLog');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentNoteAdd':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupNoteAddmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentNoteAdd = results;
                    $scope.showTarget('#popupPaymentNoteAdd');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentCollectionCallLogAdd':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupCollectionCallLogAddmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentCollectionCallLogAdd = results;
                    $scope.showTarget('#popupPaymentCollectionCallLogAdd');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentDetail':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupDetailmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentDetail = results;
                    $scope.showTarget('#popupPaymentDetail');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentChangeStatus':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupChangeStatusmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentChangeStatus = results;
                    $scope.showTarget('#popupPaymentChangeStatus');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPaymentChangeStatusWellFargo':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupChangeStatusWellFargomodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.popupPaymentChangeStatusWellFargo = results;
                    $scope.showTarget('#popupPaymentChangeStatusWellFargo');
                    $ionicLoading.hide();
                });
                break;
                case 'paymentPopupNoteDetailmodal':
                dataHtml.getTemplate('templates/dashboard/payment/paymentPopupNoteDetailmodal.tpl').success(function (results) {
                    $scope.dataPaymentHtml.paymentPopupNoteDetailmodal = results;
                    $scope.showTarget('#paymentPopupNoteDetailmodal');
                    $ionicLoading.hide();
                });
                break;
            }
        }, 500);
    }

    $scope.getPagingSimple = function () {
        $scope.dataGetBy = 'paging';
        $ionicLoading.show({
            template: templateLoading
        });
        $scope.checkLoadMore = false;
        $scope.searchPaymenthistories.current_page = 1;
        Paymenthistories.getPaging($scope.searchPaymenthistories).success(function (data) {
            $scope.dataTemp = _.groupBy(data.data,'invoice_no');
            _.each($scope.dataTemp, function(val) {
                return val.dateToSort = new Date(moment(val[0].maxdate,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'));
            })
            $scope.paymenthistories =  _.sortBy($scope.dataTemp, 'dateToSort').reverse();
            $ionicLoading.hide();
            if (data.data.length != 0) {
                $timeout(function () {
                    $scope.checkLoadMore = true;
                }, 5000);
            }
            $scope.credittermplans = data.credittermplans;
            request_notify_get_chat = true;
            $scope.check_init_payment = true;
            //$scope.setTime = true;
            $ionicScrollDelegate.$getByHandle('scrollPaymentContent').scrollTop(true);
            $ionicScrollDelegate.$getByHandle('scrollPaymentContent').resize();
            $scope.closeTarget(".payment-search");
            $scope.$broadcast('scroll.refreshComplete');
            $("#searchInput").blur();
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });

    }

    $scope.getPaymenthistories = function() {
        if($scope.isFilterExport){
           $scope.submitFomFiter();
        }
        else{
            $scope.getPagingSimple();
        }
    };

    // $scope.getPagingSimple = function() {
    //     $('.tblloader_content').show();
    //     $('#document').show();
    //     $('.tblloader_root').hide();
    //     Paymenthistories.getPaging($scope.searchPaymenthistories).success(function(data) {

    //         $scope.dataTemp = _.groupBy(data.data,'invoice_no');
    //         _.each($scope.dataTemp, function(val) {
    //             return val.dateToSort = new Date(moment(val[0].maxdate,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'));
    //         })
    //         $scope.paymenthistories =  _.sortBy($scope.dataTemp, 'dateToSort').reverse();
    //         $('.tblloader_content').hide();
    //         $scope.currentPage = data.page;
    //         $scope.itemsPerPage = data.rows;
    //         //paymenthistories_pagesize.val($scope.itemsPerPage);
    //         $scope.totalItems = data.total_rows;
    //         $scope.isbuildtree = true;
    //         $scope.filterClientdata = $scope.paymenthistories;
    //         if ($scope.isbuildtree) {
    //             $scope.createStructTreeDate();
    //             $scope.createStructType();
    //             $scope.createStructTreeStatus();
    //             $scope.isbuildtree = false;
    //             $scope.checkdate = false;
    //             $scope.checkstatus = false;
    //             $scope.checktype = false;
    //         }
    //         !$scope.check_init_payment ? $interval($scope.checkLogin, time_refresh) : '';
    //         request_notify_get_chat = true;
    //         $scope.check_init_payment = true;
    //         $scope.repalaceres();
    //     });
    // }

    $scope.submitFomFiter = function() {
        $scope.dataGetBy = 'filter';
        if( $scope.dataFilterPayment.dateType != null && $scope.dataFilterPayment.dateType!= ''){
            $scope.dataFilterPayment.form = moment($scope.dataFilterPayment.form).format("YYYY-MM-DD");
            $scope.dataFilterPayment.to = moment($scope.dataFilterPayment.to).format("YYYY-MM-DD");
        }
        if( $scope.dataFilterPayment.serviceTo  != null && $scope.dataFilterPayment.serviceTo != ''){
            $scope.dataFilterPayment.serviceForm = moment($scope.dataFilterPayment.serviceForm).format("YYYY-MM-DD");
            $scope.dataFilterPayment.serviceTo = moment($scope.dataFilterPayment.serviceForm).format("YYYY-MM-DD");
        } 
        $scope.dataFilterPayment.rows =  $scope.itemsPerPage;
        $scope.dataFilterPayment.current_page = $scope.currentPage;
        $scope.dataFilterPayment.submitType = $scope.submitType;
        if($scope.submitType == 'view'){
            $scope.isFilterExport  = true;
        }
        Paymenthistories.filter($scope.dataFilterPayment).success(function(data) {
            if(data.status == false){
                $cordovaToast.showLongCenter(data.msg);
            }
            else{
                if($scope.submitType == 'view'){
                    if (data.data.length < $scope.itemsPerPage)
                        $scope.checkLoadMore = false;
                    $scope.dataTemp = _.groupBy(data.data,'invoice_no');
                    _.each($scope.dataTemp, function(val) {
                        return val.dateToSort = new Date(moment(val[0].lastestDatePayment,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'));
                    })
                    $scope.paymenthistories =  _.sortBy($scope.dataTemp, 'dateToSort').reverse();
                    $ionicLoading.hide();
                    if (data.data.length != 0) {
                        $timeout(function () {
                            $scope.checkLoadMore = true;
                        }, 5000);
                    }
                    $scope.closeTarget('#popupPaymentFilter');
                }
                else{
                    $scope.submitType = 'view';
                    var publicInxdex = url_site.lastIndexOf("/public");
                    var res = url_site.substr(0, publicInxdex);
                    var arrRes = data.link.split("./..");
                    var linkOnApp = res+arrRes[1];
                    $scope.closeTarget('#popupPaymentFilter');
                    $scope.downloadFile(linkOnApp);
                }
            }           
        });
    }


    $scope.LoadMorePayment = function () {
        if (!$scope.checkLoadMore)
            return;
        if($scope.dataGetBy == 'paging'){

            $scope.searchPaymenthistories.current_page++;
            Paymenthistories.getPaging($scope.searchPaymenthistories).success(function (data) {
                if (data.data.length < $scope.itemsPerPage)
                    $scope.checkLoadMore = false;
                tempData = _.groupBy(data.data,'invoice_no');
                _.each(tempData, function(val) {
                    return val.dateToSort = new Date(moment(val[0].maxdate,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'));
                })
                tempData =  _.sortBy(tempData, 'dateToSort').reverse();
                $scope.paymenthistories = Object.assign($scope.paymenthistories, tempData);
            }).error(function (data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        }
        else{
            $scope.dataFilterPayment.current_page++;
            Paymenthistories.filter($scope.dataFilterPayment).success(function(data) {
                if (data.data.length < $scope.itemsPerPage)
                    $scope.checkLoadMore = false;
                if($scope.submitType == 'view'){
                    $scope.dataTemp = _.groupBy(data.data,'invoice_no');
                    _.each($scope.dataTemp, function(val) {
                        return val.dateToSort = new Date(moment(val[0].lastestDatePayment,'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'));
                    })
                    $scope.dataTemp =  _.sortBy($scope.dataTemp, 'dateToSort').reverse();
                    $scope.paymenthistories = Object.assign($scope.paymenthistories, $scope.dataTemp);
                    $ionicLoading.hide();
                    if (data.data.length != 0) {
                        $timeout(function () {
                            $scope.checkLoadMore = true;
                        }, 2000);
                    }
                    else{
                        $scope.checkLoadMore = false;
                    }
                }
                else{
                    $('.tblloader_content').hide();
                    $scope.submitType = 'view';
                    window.location.href = data.link;
                    closePopupById('popuppaymentfilter');
                }

            });
        }
        $timeout(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }, 2000);
    }

    $scope.searchChanged = function () {
        $scope.getPaymenthistories();
    }
    $scope.$watch('time.start', function (value) {
        if ($scope.setTime) {
            $('#start_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.getPaymenthistories();
        }
    })
    $scope.$watch('time.end', function (value) {
        if ($scope.setTime) {
            $('#end_time').html(moment(value).format('MM/DD/YYYY'));
            $scope.getPaymenthistories();
        }
    })


    $scope.Export = function () {
        $('.tblloader_content').show();
        Paymenthistories.exportPaymenthistories($scope.paymenthistories).success(function (data) {
            window.location.href = data;
            $('.tblloader_content').hide();
        });
    }
    /*$scope.getSelectPaymenthistories = function(){
     Paymenthistories.getSelect().success(function(data){
     $scope.selectPaymenthistories = data;
     });
     }
     $scope.getSelecPaymenthistories();*/
    /*
     xem demo upload file tai day:
     http://jsfiddle.net/danialfarid/1m6fn6re/
     $scope.upload = function (file) {
     Upload.upload({
     url: '/todo',
     fields: $scope.todoData,
     file: file
     }).progress(function (evt) {
     var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
     console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
     }).success(function (data, status, headers, config) {
     console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
     }).error(function (data, status, headers, config) {
     console.log('error status: ' + status);
     })
     };
     */
     $scope.sizeChanged = function () {
        $scope.searchPaymenthistories.rows = $scope.entryLimit;
        paymenthistories_pagesize.val($scope.searchPaymenthistories.rows);
        localStorage.setItem('paymenthistories_pagesize', $scope.searchPaymenthistories.rows);
        $scope.searchPaymenthistories.current_page = 1;
        $scope.getPaymenthistories();
    }
    $scope.pageChanged = function () {
        console.log($scope.currentPage);
        $scope.searchPaymenthistories.current_page = $scope.currentPage;
        $scope.getPaymenthistories();
    };
    //$scope.getPaymenthistories();
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addPaymenthistoriesData = {};
    $scope.createPaymenthistories = function () {
        console.log($scope.addPaymenthistoriesData);
        Paymenthistories.save($scope.addPaymenthistoriesData).success(function (data) {
            $scope.addPaymenthistoriesData = {};
            $scope.getPaymenthistories();
            if (data.status) {
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.editPayment = function (data) {
        if (data.type == 'Wells Fargo Plan') {
            $scope.editPaymenthistoriesWellGoPlan(data.id);
        } else {
            $scope.editPaymenthistories(data.id);
        }
        // $scope.openByGetTemplate('popupPaymentEdit');
    }
    $scope.editPaymenthistoriesData = {};
    $scope.editPaymenthistories = function (id) {
        $ionicLoading.show({template: templateLoading});
        $scope.openByGetTemplate('popupPaymentChangeStatus');
        Paymenthistories.show(id).success(function (data) {
            $ionicLoading.hide();
            $scope.editPaymenthistoriesData = data;
            $scope.editPaymenthistoriesData.status = String($scope.editPaymenthistoriesData.status);
            $scope.setValuePaymentStatusInput($scope.editPaymenthistoriesData.status);
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.editPaymenthistoriesWellGoPlan = function (id) {
        $ionicLoading.show({template: templateLoading});
        $scope.openByGetTemplate('popupPaymentChangeStatusWellFargo');
        Paymenthistories.show(id).success(function (data) {
            $ionicLoading.hide();
            $scope.WellFargoPlan = data;
            $scope.WellFargoPlan.authorization_number = parseInt($scope.WellFargoPlan.authorization_number);
            $scope.WellFargoPlan.authorization_amount = parseFloat($scope.WellFargoPlan.authorization_amount);
            $scope.Input_value.paymentStatusWellFargo = $scope.WellFargoPlan.payment_status == '0' ? 'Non-Deposited' : 'Deposited';
            $scope.Input_value.CreditTerm = $scope.WellFargoPlan.credit_term_plan_number;
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.wellFargoSelectChange = function (type) {
        if (type == 'payment_status') {
            $scope.Input_value.paymentStatusWellFargo = $scope.WellFargoPlan.payment_status == '0' ? 'Non-Deposited' : 'Deposited';
        } else {
            $scope.Input_value.CreditTerm = $scope.WellFargoPlan.credit_term_plan_number;
        }
    }
    $scope.updatePaymenthistories = function (formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        ;
        var id = $scope.editPaymenthistoriesData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Paymenthistories.save(id, $scope.editPaymenthistoriesData).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                var key = moment($scope.editPaymenthistoriesData.created_date).format('MM/DD/YYYY');
                var idx = -1;
                if ($scope.paymenthistories[key])
                    idx = _.findIndex($scope.paymenthistories[key], {id: id});
                if (idx != -1) {
                    if ($scope.editPaymenthistoriesData.status == 0) {
                        $scope.paymenthistories[key][idx].status_show = 'NOT ACCEPTED';
                        $scope.paymenthistories[key][idx].status = 'NOT ACCEPTED';
                    } else {
                        $scope.paymenthistories[key][idx].status_show = 'PAID';
                        $scope.paymenthistories[key][idx].status = 'PAID';
                    }
                }

                var index = _.findLastIndex($scope.filterClientdata, {id: id.toString()});
                if ($scope.editPaymenthistoriesData.status == 0) {
                    $scope.filterClientdata.status_show = 'NOT ACCEPTED';
                    $scope.filterClientdata.status = 'NOT ACCEPTED';
                } else {
                    $scope.filterClientdata.status_show = 'PAID';
                    $scope.filterClientdata.status = 'PAID';
                }

                $scope.closeTarget('#popupPaymentChangeStatus');
                $scope.editPaymenthistoriesData = {};
                $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.saveWellFargoPlan = function (formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        ;
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.SaveWellFargoPlan($scope.WellFargoPlan).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupPaymentChangeStatusWellFargo')
                $scope.WellFargoPlan = {};
                $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.deletePaymenthistoriesData = {};
    $scope.confrimPaymenthistories = function (item) {
        $scope.deletePaymenthistoriesData = item;
        $scope.openByGetTemplate('confirmDeletePayment');
    }
    $scope.deletePaymenthistories = function () {
        var id = $scope.deletePaymenthistoriesData.id
        $ionicLoading.show({
            template: templateLoading
        });
        Paymenthistories.destroy(id).success(function (data) {
            $ionicLoading.hide();
            if (data.status) {
                var key = moment($scope.deletePaymenthistoriesData.created_date).format('MM/DD/YYYY');
                var idx = -1;
                if ($scope.paymenthistories[key])
                    idx = _.findIndex($scope.paymenthistories[key], {id: id});
                if (idx != -1) {
                    $scope.paymenthistories[key].splice(idx, 1);
                }
                if ($scope.paymenthistories[key].length == 0)
                    delete $scope.paymenthistories[key];
                var index = _.findLastIndex($scope.filterClientdata, {id: id.toString()});
                $scope.filterClientdata.splice(index, 1);
                $scope.deletePaymenthistoriesData = {};
                $scope.closeTarget('#popupPaymentDetail');
                $scope.closeTarget('#confirmDeletePayment');
                $scope.totalPaymenthistories--;
                $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!!!');
        });
    }

    //start fiter
    $scope.stuffdate = {};
    $scope.stuffstatus = {};
    $scope.stufftype = {};
    $scope.changeDate = function (node, ihvselected, tree) {
        $scope.lastChangedNode = node;
        if (ihvselected) {
            switch (node.level) {
                case "0":
                $scope.servicedatechecked = $scope.dates;
                break;
                case "1":
                var list = _.where($scope.dates, {
                    year: node.year
                });
                $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
                break;
                case "2":
                var list = _.where($scope.dates, {
                    year: node.year,
                    month: node.month
                });
                $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
                break;
                case "3":
                var list = _.where($scope.dates, {
                    year: node.year,
                    month: node.month,
                    date: node.date
                });
                $scope.servicedatechecked = $scope.mergeServicedatechecked(list, $scope.servicedatechecked);
                break;
            }
        } else {
            switch (node.level) {
                case "0":
                $scope.servicedatechecked = [];
                break;
                case "1":
                var list = _.where($scope.dates, {
                    year: node.year
                });
                $scope.removeServicedatechecked(list);
                break;
                case "2":
                var list = _.where($scope.dates, {
                    year: node.year,
                    month: node.month
                });
                $scope.removeServicedatechecked(list);
                break;
                case "3":
                var list = _.where($scope.dates, {
                    year: node.year,
                    month: node.month,
                    date: node.date
                });
                $scope.removeServicedatechecked(list);
                break;
            }
        }
    }

    $scope.changeStatus = function (node, ihvselected, tree) {
        $scope.lastChangedNode = node;
        if (ihvselected) {
            switch (node.level) {
                case "0":
                $scope.searchPaymenthistories.status = [];
                $scope.searchPaymenthistories.arStatusId = [];
                $scope.statues.forEach(function (item) {
                    $scope.searchPaymenthistories.status.push({"id": item.id, "name": item.status});
                    $scope.searchPaymenthistories.arStatusId.push(item.id);
                })
                break;
                case "1":
                var list = _.find($scope.statues, {
                    status: node.status
                });
                if (list) {
                    $scope.searchPaymenthistories.status.push({"id": list.id, "name": list.status});
                    $scope.searchPaymenthistories.arStatusId.push(list.id);
                }
                break;
            }
        } else {
            switch (node.level) {
                case "0":
                $scope.searchPaymenthistories.status = [];
                $scope.searchPaymenthistories.arStatusId = [];
                break;
                case "1":
                var index = _.findIndex($scope.searchPaymenthistories.status, {
                    name: node.status
                });
                if (index >= 0) {
                    $scope.searchPaymenthistories.status.splice(index, 1);
                    $scope.searchPaymenthistories.arStatusId.splice(index, 1);
                }
                break;
            }
        }
    }
    $scope.changeType = function (node, ihvselected, tree) {
        $scope.lastChangedNode = node;
        if (ihvselected) {
            switch (node.level) {
                case "0":
                $scope.searchPaymenthistories.paymentMethod = [];
                $scope.searchPaymenthistories.arrPaymentMethodId = [];
                $scope.paymenttypes.forEach(function (item) {
                    $scope.searchPaymenthistories.paymentMethod.push({"name": item.type});
                    $scope.searchPaymenthistories.arrPaymentMethodId.push(item.type);
                })
                break;
                case "1":
                var list = _.find($scope.paymenttypes, {
                    type: node.type
                });
                if (list) {
                    $scope.searchPaymenthistories.paymentMethod.push({"name": list.type});
                    $scope.searchPaymenthistories.arrPaymentMethodId.push(list.type);
                }
                break;
            }
        } else {
            switch (node.level) {
                case "0":
                $scope.searchPaymenthistories.paymentMethod = [];
                $scope.searchPaymenthistories.arrPaymentMethodId = [];
                break;
                case "1":
                var index = _.findIndex($scope.searchPaymenthistories.paymentMethod, {
                    name: node.type
                });
                if (index >= 0) {
                    $scope.searchPaymenthistories.paymentMethod.splice(index, 1);
                    $scope.searchPaymenthistories.arrPaymentMethodId.splice(index, 1);
                }
                break;
            }
        }
    }
    $scope.createStructTreeDate = function () {
        if ($scope.isbuildtree) {
            $scope.servicedatechecked = [];
            var years = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                    label: currentObject.year,
                    level: "1"
                });
            }), function (item, key, year) {
                return item.year;
            });
            years = _.sortBy(years, 'year');
            years = years.reverse();
            var months = $scope.uniqueMoth(_.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                    label: currentObject.month,
                    level: "2"
                });
            }));
            months = _.sortBy(months, 'month');
            months = months.reverse();
            $scope.uniqueDate(_.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "id", "year", "month", 'date'), {
                    label: currentObject.date,
                    level: "3"
                });
            }));
            $scope.uniqueDate2(_.map($scope.filterClientdata, function (currentObject) {
                return _.extend(_.pick(currentObject, "year", "month", 'date'), {
                    label: currentObject.date,
                    level: "3"
                });
            }));
            var month_fills = _.each(months, function (item) {
                var datetofmonth = _.where($scope.dates2, {
                    year: item.year,
                    month: item.month
                });
                item.children = _.sortBy(datetofmonth, 'date').reverse();
                return item;
            });
            var year_fills = _.each(years, function (item) {
                var cityofstate = _.where(month_fills, {
                    year: item.year
                });
                item.children = cityofstate;
                return item;
            });
            $scope.stuffdate = [{
                label: 'Select All',
                level: "0",
                children: year_fills
            }];
        }
    }
    $scope.createStructType = function () {
        // if ($scope.isbuildtree) {
        //     $scope.paymenttypechecked = [];
        //     var years = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
        //         return _.extend(_.pick(currentObject, "type"), {
        //             label: currentObject.type,
        //             level: "1"
        //         });
        //     }), function (item, key, type) {
        //         return item.type;
        //     });
        //     years = _.sortBy(years, 'type');
        //     console.log(years);
        //     // $scope.paymenttypechecked = years;
        //     $scope.paymenttypes = years;
        //     $scope.paymenttypes.forEach(function (item) {
        //         $scope.paymenttypechecked.push(item)
        //     })
        //     $scope.stufftype = [{
        //             label: 'Select All',
        //             level: "0",
        //             children: years
        //         }];
        // }
        $scope.paymenttypechecked = [];
        $scope.paymenttypes = $scope.arrPaymentMethod;
        $scope.paymenttypes.forEach(function (item) {
            $scope.paymenttypechecked.push(item)
        })
        var data = $scope.arrPaymentMethod;
        $scope.stufftype = [{
            label: 'Select All',
            level: "0",
            children: data
        }];

        $scope.paymenttypechecked.forEach(function (item) {
            //$scope.searchPaymenthistories.paymentMethod.push({"name": item.type});
            //$scope.searchPaymenthistories.arrPaymentMethodId.push(item.type);
        });
    }
    $scope.createStructTreeStatus = function () {
        // if ($scope.isbuildtree) {
        //     $scope.statuschecked = [];
        //     var years = _.uniq(_.map($scope.filterClientdata, function (currentObject) {
        //         return _.extend(_.pick(currentObject, "status"), {
        //             label: currentObject.status,
        //             level: "1"
        //         });
        //     }), function (item, key, status) {
        //         return item.status;
        //     });
        //     years = _.sortBy(years, 'status');
        //     // $scope.statuschecked = years;
        //     $scope.statues = years;
        //     $scope.statues.forEach(function (item) {
        //         $scope.statuschecked.push(item)
        //     })
        //     $scope.stuffstatus = [{
        //             label: 'Select All',
        //             level: "0",
        //             children: years
        //         }];
        // }
        $scope.statuschecked = [];
        $scope.statues = $scope.paymentStatus;
        $scope.statues.forEach(function (item) {
            $scope.statuschecked.push(item)
        })
        var data = $scope.paymentStatus;
        $scope.stuffstatus = [{
            label: 'Select All',
            level: "0",
            children: data
        }];
        $scope.statuschecked.forEach(function (item) {
            //$scope.searchPaymenthistories.status.push({"id": item.id, "name": item.status});
            //$scope.searchPaymenthistories.arStatusId.push(item.id);
        });
    }
    $scope.searchPaymentStatus = function () {
        var params = {search: ''};
        Paymenthistories.searchPaymentStatus(params).success(function (data) {
            $scope.paymentStatus = data;
            $scope.paymentStatus.forEach(function (elm) {
                elm.label = elm.name;
                elm.status = elm.name;
                elm.level = "1";
            });
            $scope.createStructType();
            $scope.createStructTreeStatus();
        })
    };
    // $scope.filterDate = function() {
    //     var data = $scope.filterdateCollection($scope.filterClientdata);
    //     data = $scope.filterstatusCollection(data);
    //     data = $scope.filtertypeCollection(data);
    //     $scope.paymenthistories = data;
    //     //$scope.order($scope.sortby)
    //     // $scope.repalaceres();
    // }
    // $scope.filterdateCollection = function(collection) {
    //     var result = [];
    //     if ($scope.servicedatechecked.length > 0) {
    //         $scope.checkdate = true;
    //         _.each($scope.servicedatechecked, function(item) {
    //             var item2 = _.findWhere(collection, {
    //                 id: item.id
    //             });
    //             if (item2) {
    //                 result.push(item2);
    //             }
    //             return item;
    //         });
    //         return result;
    //     } else {
    //         $scope.checkdate = false;
    //         return collection;
    //     }
    // }
    $scope.filterData = function () {
        // $scope.searchPaymenthistories.paymentMethod = [];
        // $scope.searchPaymenthistories.arrPaymentMethodId = [];
        // $scope.searchPaymenthistories.status = [];
        // $scope.searchPaymenthistories.arStatusId = [];
        $scope.searchPaymenthistories.current_page = 1;
        $scope.closeTarget('#popupPaymentFilter');
        // $scope.statuschecked.forEach(function (item) {
        //     $scope.searchPaymenthistories.status.push({"id": item.id, "name": item.status});
        //     $scope.searchPaymenthistories.arStatusId.push(item.id);
        // });
        // $scope.paymenttypechecked.forEach(function (item) {
        //     $scope.searchPaymenthistories.paymentMethod.push({"name": item.type});
        //     $scope.searchPaymenthistories.arrPaymentMethodId.push(item.type);
        // });
        $scope.getPaymenthistories();

        // var data = $scope.filterstatusCollection($scope.filterClientdata);
        // data = $scope.filtertypeCollection(data);
        // $scope.totalPaymenthistories = data.length;
        // var arrData = _.sortBy(data, 'created_date').reverse();
        // $scope.paymenthistories = _.groupBy(arrData, 'created_date');
        // closeTarget('#popupPaymentFilter');



    }
    $scope.filterType = function () {
        $scope.closeTarget('#popupPaymentFilter');
        var data = $scope.filtertypeCollection($scope.filterClientdata);
        data = $scope.filterstatusCollection(data);
        var arrData = _.sortBy(data, 'created_date').reverse();
        $scope.paymenthistories = _.groupBy(arrData, 'created_date');


    }
    $scope.filtertypeCollection = function (collection) {
        var result = [];
        if ($scope.paymenttypechecked.length > 0) {
            $scope.checktype = true;
            _.each($scope.paymenttypechecked, function (item) {
                var item2 = _.where(collection, {
                    type: item.type
                });
                if (item2) {
                    result = _.union(result, item2);
                }
                return item;
            });
            return result;
        } else {
            $scope.checktype = false;
            return [];
        }
    }
    $scope.filterStatus = function () {
        $scope.closeTarget('#popupPaymentFilterStatus');
        var data = $scope.filterstatusCollection($scope.filterClientdata);
        data = $scope.filtertypeCollection(data);
        $scope.paymenthistories = data;
        //$scope.order($scope.sortby)
        // $scope.repalaceres();
    }
    $scope.filterstatusCollection = function (collection) {
        var result = [];
        if ($scope.statuschecked.length > 0) {
            $scope.checkstatus = true;
            _.each($scope.statuschecked, function (item) {
                var item2 = _.where(collection, {
                    status: item.status
                });
                if (item2) {
                    result = _.union(result, item2);
                }
                return item;
            });
            return result;
        } else {
            $scope.checkstatus = false;
            return [];
        }
    }
    $scope.uniqueMoth = function (list) {
        return arrayUnion(list, [], function (item1, item2) {
            return item1.month == item2.month && item1.year == item2.year;
        });
    }
    $scope.uniqueDate = function (list) {
        $scope.dates = arrayUnion(list, [], function (item1, item2) {
            return item1.month == item2.month && item1.year == item2.year && item1.date == item2.date && item2.id == item1.id;
        });
    }
    $scope.uniqueDate2 = function (list) {
        $scope.dates2 = arrayUnion(list, [], function (item1, item2) {
            return item1.month == item2.month && item1.year == item2.year && item1.date == item2.date;
        });
    }
    $scope.mergeServicedatechecked = function (list, listcurr) {
        return arrayUnion(list, listcurr, function (item1, item2) {
            return item1.id == item2.id;
        });
    }
    $scope.removeServicedatechecked = function (list) {
        _.each(list, function (item) {
            var indexof = _.findIndex($scope.servicedatechecked, {
                id: item.id,
                year: item.year,
                month: item.month,
                date: item.date
            });
            if (indexof >= 0) {
                $scope.servicedatechecked.splice(indexof, 1);
            }
        });
    }



    $scope.filterPaymentForSearch = function (query) {
        var returnValue = {
            items: []
        };
        var params = {
            rows: 50,
            current_page: 1,
            search: query,
            paymenthistoriesDate: {},
        };
        $ionicLoading.show({template: templateLoading});
        Paymenthistories.getPaging(params).success(function (data) {
            $scope.rootDataPayment = data.data;
            $scope.rootDataPayment.forEach(function (item) {
                item.searchName = item.name + '-' + item.invoice_no + '-' + item.type + '-' + item.created_date;
            });
            $scope.rootDataPayment.forEach(function (item) {
                if (item.searchName.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                }
            });
            $timeout(function () {
                $ionicLoading.hide();
            }, 1000)
        });
        return returnValue;
    }
    $scope.selectPaymentFormSearch = function (callback) {
        $scope.getPaymentDetail(callback.item);
        $scope.initialPaymentForSearch = [];
    }
    $scope.modelPaymentForSearch = function (modelValue) {
        return
    }
    $scope.getPaymentDetail = function (data) {
        $scope.paymentDetail = data;
        $scope.openByGetTemplate('popupPaymentDetail');
    }
    $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);
    }


    if (page == 'payment.html')
        $scope.renderTemplateData();
    //end fiter
    // edit by haudao
    // $scope.fiterSearch = {};
    $scope.setValuePaymentStatusInput = function (id) {
        $scope.Input_value.paymentStatus = "";
        switch (id) {
            case '0':
            $scope.Input_value.paymentStatus = "NOT ACCEPTED";
            break;
            case '1':
            $scope.Input_value.paymentStatus = "PAID";
            break;
            case '2':
            $scope.Input_value.paymentStatus = "Accepted";
            break;
            case '3':
            $scope.Input_value.paymentStatus = "Deposited";
            break;
        }
    }

    $scope.getAllUsers = function () {
        if ($scope.allUser == undefined) {
            $scope.allUser = [];
            var params = {rows: 'All'};
            Users.getPaging(params).success(function(data) {
                _.each(data.data, function(val, index) {
                    nick_name = val.first_name + ' ' + val.last_name;
                    var _item = {
                        id: val.id,
                        screen_name: nick_name + ' - ' + val.positiontitles_name,
                        name: nick_name,
                        imgprofile: pathToPublic + val.image_pic,
                        email: val.email
                    }
                    $scope.allUser.push(_item);
                });
            });
        }
    }
    $scope.clearSearch = function () {
        $scope.searchPaymenthistories.search = '';
        $scope.getPaymenthistories();
    }
    $scope.keypress = function ($event, delegate) {
        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 (delegate) {
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                clearInterval($scope.myTime);
                $scope.getPaymenthistories();
                $ionicScrollDelegate.$getByHandle(delegate).resize();
            }
        }, 120);
    }
    $timeout(function () {
        $scope.classDevice = isiOs ? 'ios' : 'android';
        // console.log($scope.classDevice);
    }, 2000)
    $scope.resetFilter = function () {
        $scope.sortby = {};
        $scope.closeTarget('#popupPaymentFilter');
        $scope.getPaymenthistories();
        $timeout(function () {
            $(".box-expandable").removeClass('expand');
            $ionicScrollDelegate.$getByHandle('scrollPaymentFilter').resize();
            $ionicScrollDelegate.$getByHandle('scrollPaymentFilter').scrollTop(true);
        }, 1)
    }

    $scope.setValueForInput = function (id,type) {
        switch (type) {
            case 'datetype':
            if(id=='due'){
                $scope.Input_value.dateType = 'Due Date';
            }
            if(id=='invoice'){
                $scope.Input_value.dateType = 'Invoice Date';
            }
            if(id=='payment'){
                $scope.Input_value.dateType = 'Payment Date';
            }
            break;
            case 'jobStatus':
            if(id==''){
                $scope.Input_value.jobStatus = 'Select Job Status';
            }
            if(id=='installed'){
                $scope.Input_value.jobStatus = 'Installed';
            }
            if(id=='notyetinstalled'){
                $scope.Input_value.jobStatus = 'Not Yet Installed';
            }
            break;
            case 'statusPayment':
            if(parseInt(id)>0){
                $scope.Input_value.paymentStatus = _.where($scope.paymentStatusSelect, {
                    id: id
                })[0].name;
            }
            else{
                $scope.Input_value.paymentStatus = 'Select Status';
            }
            break;
        }
    }

    $scope.searchAutocomplete = function(query,type){
        var returnValue = {
            items: []
        };
        switch (type) {
            case 'estInv':
            if (query.length > 0) {
                var params = {
                    search: query
                };
                Paymenthistories.getEstimateInvoice(params).success(function(res) {
                    $scope.rootEstimateInvoiceData = res;
                    $scope.rootEstimateInvoiceData.forEach(function (item) {
                        if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                            if($scope.dataFilterPayment.arrinvoiceEstimateId && $scope.dataFilterPayment.arrinvoiceEstimateId.indexOf(item.id)<0){
                                returnValue.items.push(item);    
                            }
                        } 
                    });
                })
            } else {
                return returnValue;
            }
            break;

            case 'method':
            $scope.arrPaymentMethod.forEach(function (item) {
                if (item.label.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    if($scope.dataFilterPayment.arrPaymentMethodId && $scope.dataFilterPayment.arrPaymentMethodId.indexOf(item.label)<0){
                        returnValue.items.push(item);    
                    }
                } 
            });
            break;
            case 'invcreateduser':
            $scope.allUser.forEach(function (item) {
                if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    if($scope.dataFilterPayment.arrCreatedUserId && $scope.dataFilterPayment.arrCreatedUserId.indexOf(item.id)<0){
                        returnValue.items.push(item);    
                    }
                } 
            });
            break;
            case 'inveditduser':
            $scope.allUser.forEach(function (item) {
                if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    if($scope.dataFilterPayment.arrModifiedUserId && $scope.dataFilterPayment.arrModifiedUserId.indexOf(item.id)<0){
                        returnValue.items.push(item);    
                    }
                } 
            });
            break;
            case 'paymentuser':
            $scope.allUser.forEach(function (item) {
                if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    if($scope.dataFilterPayment.arrPaymentUserId && $scope.dataFilterPayment.arrPaymentUserId.indexOf(item.id)<0){
                        returnValue.items.push(item);    
                    }
                } 
            });
            break;
            case 'paymentstatus':
            $scope.paymentStatus.forEach(function (item) {
                if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    if($scope.dataFilterPayment.arStatusId && $scope.dataFilterPayment.arStatusId.indexOf(item.id)<0){
                        returnValue.items.push(item);    
                    }
                } 
            });
            break;

        }
        return returnValue;
    }


    $scope.clickOnItemAutocomplete = function(callback,type){
        switch (type) {
            case 'estInv':
            $scope.dataFilterPayment.arrinvoiceEstimateId.push(callback.item.id);
            break;
            case 'method':
            $scope.dataFilterPayment.arrPaymentMethodId.push(callback.item.label);
            break;
            case 'invcreateduser':
            $scope.dataFilterPayment.arrCreatedUserId.push(callback.item.id);
            break;
            case 'inveditduser':
            $scope.dataFilterPayment.arrModifiedUserId.push(callback.item.id);
            break;  
            case 'paymentuser':
            $scope.dataFilterPayment.arrPaymentUserId.push(callback.item.id);
            break; 
            case 'paymentstatus':
            $scope.dataFilterPayment.arStatusId.push(callback.item.id);
            break;  
        }
    }

    $scope.removeItemAutoComplete = function(callback,type){
        switch (type) {
            case 'estInv':
            var index = $scope.dataFilterPayment.arrinvoiceEstimateId.indexOf(callback.item.id);
            $scope.dataFilterPayment.arrinvoiceEstimateId.splice(index, 1);
            break;
            case 'method':
            var index = $scope.dataFilterPayment.paymentMethod.indexOf(callback.item.label);
            $scope.dataFilterPayment.paymentMethod.splice(index, 1);
            break;
            case 'invcreateduser':
            var index = $scope.dataFilterPayment.arrCreatedUserId.indexOf(callback.item.id);
            $scope.dataFilterPayment.arrCreatedUserId.splice(index, 1);
            break;
            case 'inveditduser':
            var index = $scope.dataFilterPayment.arrModifiedUserId.indexOf(callback.item.id);
            $scope.dataFilterPayment.arrModifiedUserId.splice(index, 1);
            break;
            case 'paymentuser':
            var index = $scope.dataFilterPayment.arrPaymentUserId.indexOf(callback.item.id);
            $scope.dataFilterPayment.arrPaymentUserId.splice(index, 1);
            break;
            case 'paymentstatus':
            var index = $scope.dataFilterPayment.arStatusId.indexOf(callback.item.id);
            $scope.dataFilterPayment.arStatusId.splice(index, 1);
            break;
        }
    }

    $scope.validateForm = function (formValidate) {
        var exitLoop = false;
        $ionicLoading.show({
            template: templateLoading
        });
        if (formValidate.$invalid) {
            console.log(formValidate);
            $ionicScrollDelegate.$getByHandle('scrollCustomer' + style).scrollTop();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $scope.submitFomFiter();
    }

    $scope.submitTypeFilter = function(action) {
        $scope.submitType = action ; 
    };

    $scope.downloadFile = function (urlFile) {
        $ionicLoading.show({
            template: templateLoading
        });
        var arrData = urlFile.split("/");
        var fileName = arrData[arrData.length - 1];
        var trustHosts = true;
        var options = {};
        if (isiOs) {
            var targetPath = cordova.file.syncedDataDirectory + 'RGD/' + fileName;
            $cordovaFile.createDir(cordova.file.syncedDataDirectory, "RGD", false).then(function (success) {
                console.log(success);
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            }, function (error) {
                console.log(error);
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            });
        } else {
            var targetPath = cordova.file.externalRootDirectory + 'RGD/' + fileName;
            $cordovaFile.createDir(cordova.file.externalRootDirectory, "RGD", false).then(function (success) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            }, function (error) {
                $scope.cordovaDownload(urlFile, targetPath, options, trustHosts);
            });
        }
    }
    $scope.cordovaDownload = function (urlFile, targetPath, options, trustHosts) {
        $cordovaFileTransfer.download(urlFile, targetPath, options, trustHosts).then(function (result) {
            $ionicLoading.hide();
            console.log(result);
            console.log('then');
            $cordovaToast.showLongTop('Download Successful!!! Target: ' + result.fullPath);
        }, function (err) {
            $ionicLoading.hide();
            console.log(err);
            console.log('err');
        }, function (progress) {
            console.log('progress');
        });
    }

    $scope.showImagePhone = function (url) {
        if (url) {
            if (url.indexOf('s3.amazonaws.com') > -1) {
                return url;
            } else {
                return url_site + '/' + url;
            }
        } else {
            return 'resources/images/thumnails/profile-default.png';
        }
    }

    $scope.getDataPaymentNoteByOrderId = function(order_id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Paymenthistories.getDataPaymentNoteByOrderId(order_id).success(function(data) {
            $scope.dataPaymentNote = data;
            $scope.getPaymentStatus();
        });
    }

    $scope.getPaymentStatus = function() {
        if($scope.paymentStatusSelect.length == 0){
            Paymenthistories.getPaymentStatus().success(function(data) {
                $ionicLoading.hide();
                $scope.paymentStatusSelect = data;
                $scope.openByGetTemplate('popupPaymentNote')
            });
        }
        else{
            $ionicLoading.hide();
            $scope.openByGetTemplate('popupPaymentNote')
        }
    }

    $scope.viewInvoiceEstimateLog = function(order_id,type) {
        $ionicLoading.show({
            template: templateLoading
        });
        if(type=='order'){
            $scope.logType = 'Invoice/ Estimate note';
        }
        else{
            $scope.logType = 'Payment note';
        }
        Paymenthistories.viewInvoiceEstimateLog(order_id,type).success(function(data) {
            $ionicLoading.hide();
            $scope.dataInvoiceEstimateLog = data;
            $scope.openByGetTemplate('paymentPopupNoteDetailmodal');
        });
    }

    $scope.savePaymentNote = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        if(!$scope.dataPaymentNote.payment_status){
            $scope.dataPaymentNote.payment_status = '';
        }
        Paymenthistories.savePaymentNote($scope.dataPaymentNote).success(function(data) {
            $ionicLoading.hide();
            if(data.status){
                $cordovaToast.showLongTop(data.msg);
                $scope.closeTarget('#popupPaymentNote')
                //$scope.getPaymenthistories();
            }else{
                $cordovaToast.showLongCenter(data.msg);
            }
        });
    }

    $scope.paymentStatusName = function(item,on) {
        if(item.type == 'Wells Fargo Plan'){
                var status = _.where($scope.status_payment_well_fargo, {
                    id: item.payment_status + ''
                });
                if (status.length > 0) {
                    return status[0].name;
                } else {
                    return '';
                }
            }else{
                if(on == 'form'){
                    return item.status_show;
                }else{
                    return item.pmtStatus;
                }
            }
    }

    $scope.getUserLogin = function () {
        return Login.getUserLogin().success(function (data) {
            if (data == false) {
                $scope.displayname = "Profile";
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                var index = _.findIndex(data.jsondata,{roletree_id:'92'});
                if(!data.jsondata[index].check){
                    $scope.displayname = "Profile";
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                }else{
                    $scope.showButtonFormFilter = data.jsondata[index].child[0].check;
                    $scope.showButtonEditNote = data.jsondata[index].child[1].check;
                    $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;
                    }  
                    $scope.getPaymenthistories();         
                } 
            }
        });
    }


})
