var products_pagesize = $('#products_pagesize');
angular.module('pricebookController', []).controller('pricebookCtrl', function($ionicHistory, $cordovaFile, $cordovaActionSheet, //
    $cordovaCamera, $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, //
    $ionicLoading, $ionicPopup, $scope, $http, $window, $interval, Login, Products, dataHtml) {
    searchPricebookHandle();

    function searchPricebookHandle() {
        toggleDelegateHandle('#pricebook_page', '.link-pricebook-search', '.pricebook-search');
        toggleDelegateHandle('#pricebook_page', '.pricebook-search .search-type .btn-close', '.pricebook-search');
        toggleDelegateHandle('#pricebook_page', '.pricebook-search .search-content .btn-close', '.pricebook-search');
        closeOutsideHandle('.link-pricebook-search, .pricebook-search', '.pricebook-search');
    }
    filterPricebookHandle();

    function filterPricebookHandle() {
        toggleDelegateHandle('#pricebook_page', '.link-pricebook-filter', '.pricebook-filter');
        toggleDelegateHandle('#pricebook_page', '.pricebook-filter .search-type .btn-close', '.pricebook-filter');
        toggleDelegateHandle('#pricebook_page', '.pricebook-filter .search-content .btn-close', '.pricebook-filter');
        closeOutsideHandle('.link-pricebook-filter, .pricebook-filter', '.pricebook-filter');
    }
    $scope.currentIdLogin = currentIdLogin;
    $scope.currentPage = 1;
    var pager = '25';
    // localStorage.getItem('products_pagesize')
    $scope.itemsPerPage = pager ? pager : 5;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.showpricebook = false;
    $scope.showProduct = 'active';
    $scope.productShow = 'Active';
    $scope.searchProducts = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: "",
        show: $scope.showpricebook,
        type: 'Entire Pricebook',
        showProduct : $scope.showProduct
    };
    $scope.checked = 1;
    $scope.AddProductData = {};
    $scope.AddProductData.taxable = 1;
    $scope.AddProductData.ontruck = 1;
    $scope.AddProductData.message_status = 0;
    $scope.editProductData = {};
    $scope.editProductData.SecondaryLevel = '';
    $scope.editProductData.category_id = '';
    $scope.showKit = false;
    $scope.Kitting_Window = {};
    $scope.Kitting_WindowData = {};
    $scope.searchtype = 'Entire Pricebook';
    $scope.autocompleteList = {};
    /*$scope.getUsers = function(){
        User.get().success(function(data){
            $scope.users= data;
        });
    }
    $scope.getUsers();
    */
    //role
    $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.check_init_product = false;
    $scope.checkLoadMore = false;
    $scope.dataHtml = {};
    
    $scope.renderTemplateData = function() {
        dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookMenuHeadermodal.tpl').success(function(results) {
            $scope.dataHtml.menuHeader = results;
            dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookContentmodal.tpl').success(function(results) {
                $scope.dataHtml.pricebookContent = results;
                dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupSearchmodal.tpl').success(function(results) {
                    $scope.dataHtml.searchPricebooks = results;
                    $timeout(function() {
                        setHeight("#main-content");
                    }, 1)
                    $scope.getUserLogin();
                });
            });
        });
    }
    $scope.openByGetTemplate = function(style) {
        $ionicLoading.show({ template: templateLoading });
        $timeout(function() {
            switch (style) {
                case 'appointmentToSchedule':
                dataHtml.getTemplate('templates/dashboard/schedules/shedulesPopupAppointmentToSchedulemodal.tpl').success(function(results) {
                    $scope.dataHtml.appointmentToSchedule = results;
                    $scope.showTarget('#appointmentToSchedule');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPricebookImport':
                dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupImportmodal.tpl').success(function(results) {
                    $scope.dataHtml.popupPricebookImport = results;
                    $scope.showTarget('#popupPricebookImport');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPricebookDelete':
                dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupDeletemodal.tpl').success(function(results) {
                    $scope.dataHtml.popupPricebookDelete = results;
                    $scope.showTarget('#popupPricebookDelete');
                    $ionicLoading.hide();
                });
                break;
                case 'popupPricebookDetail':
                dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupDetailmodal.tpl').success(function(results) {
                    $scope.dataHtml.popupPricebookDetail = results;
                    $scope.showTarget('#popupPricebookDetail');
                });
                break;
                case 'pricebookFilterPopup':
                dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookFiltermodal.tpl').success(function(results) {
                    $scope.dataHtml.pricebookFilterPopup = results;
                    $scope.showTarget('#pricebookFilterPopup');
                    $ionicLoading.hide();
                });
                break;
            }
        }, 500);
    }
    $scope.getProducts = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Products.getPaging($scope.searchProducts).success(function(data) {
            if (!startpage) $ionicLoading.hide();
            $scope.products = [];
            $scope.products = data.data;
            $ionicScrollDelegate.$getByHandle('scrollPricebookContent').scrollTop(true);
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchProducts.rows;
            products_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
            // $scope.repalaceres();
            !$scope.check_init_product ? $interval($scope.checkLogin, time_refresh) : '';
            request_notify_get_chat = true;
            $scope.check_init_product = true;
            $timeout(function() {
                if (data.data.length != 0) $scope.checkLoadMore = true;
            }, 5000);
            $scope.getWarranty();
            $scope.closeTarget(".pricebook-search");
            $("#searchInput").blur();
        });
    };
    $scope.showsInActiveProduct = function (showProduct) {
        $scope.searchProducts.showProduct = showProduct;
        switch(showProduct){
            case 'all':
            $scope.productShow = 'All';
            break;
            case 'active':
            $scope.productShow = 'Active';
            break;
            case 'inactive':
            $scope.productShow = 'Deactivated';
            break;
        }

        $scope.searchProducts.current_page = 1;
        $scope.closeTarget('#pricebookFilterPopup');
        $scope.getProducts();
    }
    $scope.searchChanged = function() {
        $scope.Kitting_Window = {};
        $scope.Kitting_WindowData = {};
    }
    $scope.resetKitting_Window_from = function() {
        $scope.Input_value.manufacturer = 'Null';
        $ionicLoading.show({ template: templateLoading });
        $timeout(function() {
            dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupAddmodal.tpl').success(function(results) {
                $scope.dataHtml.popupPricebookAdd = results;
                $scope.showTarget('#popupPricebookAdd');
                $scope.Kitting_Window = {};
                $scope.Kitting_WindowData = {};
                $scope.showKit = false;
                $scope.TertiaryLevelData = [];
                $scope.SecondaryLevelData = [];
                $ionicLoading.hide();
            });
        }, 500)
    }
    $scope.openkit = function() {
        $ionicLoading.show({ template: templateLoading });
        dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupKittingFormmodal.tpl').success(function(results) {
            $scope.dataHtml.popupPricebookKittingWindow = results;
            $ionicLoading.hide();
            $timeout(function() {
                // document.getElementById('formKittingForm').reset();
                // $scope.Kitting_Window = {};
                // $scope.Kitting_WindowData = {};
                $ionicScrollDelegate.$getByHandle('scrollKittingForm').scrollTop();
                $scope.showTarget('#popupPricebookKittingWindow');
            }, 500);
        })

        // $scope.showKit = false;
        // $scope.callbackfrom = id;
        // $('.ivh-treeview-twistie-collapsed').parent().parent().find('.none').slideUp();
        // $('.ivh-treeview-twistie-collapsed').html('(+)');
        // setTimeout(function() {
        //     $('#popupKittingWindow').parent().parent().find('.close-title-button').click(function() {
        //         openPopup($scope.callbackfrom);
        //     })
        // }, 500);
    }
    $scope.saveKitting_Window = function() {
        $scope.Kitting_WindowData = $scope.Kitting_Window;
        $scope.closeTarget('#popupPricebookKittingWindow');
        console.log($scope.Kitting_WindowData);
    }
    $scope.showKitting_Window = function(showKit) {
        // if (showKit) {
        //     $('.ivh-treeview-twistie-collapsed').parent().parent().find('.none').slideDown();
        //     $('.ivh-treeview-twistie-collapsed').html('(-)');
        // } else {
        //     $('.ivh-treeview-twistie-collapsed').parent().parent().find('.none').slideUp();
        //     $('.ivh-treeview-twistie-collapsed').html('(+)');
        // }
    }
    $scope.getProductsClass = function() {
        $ionicLoading.show({
            template: templateLoading
        })
        Products.getProductsClass().success(function(data) {
            if (!startpage) $ionicLoading.hide();
            $scope.ProductClassData = data;
            $scope.getProducts();
        });
    }
    $scope.getProductAvailabilities = function() {
        Products.getProductAvailabilities().success(function(data) {
            $scope.productavailabilitySelect = data.data;
            $scope.getManufacturers();
        });
    }
    $scope.getManufacturers = function() {
        Products.getManufacturers().success(function(data) {
            $scope.manufacturers = data;
            $scope.getProductsClass();
        });
    }
    //$scope.getProductsClass();
    $scope.disableSecondaryLevel = true;
    $scope.getSecondaryLevel = function(id) {
        $scope.setValueProductClassInput(id);
        Products.getSecondaryLevel(id).success(function(data) {
            $scope.SecondaryLevelData = data;
            if (data.length > 0) {
                $scope.disableSecondaryLevel = false;
            } else {
                $scope.disableSecondaryLevel = true;
            }
        });
    }
    $scope.disableTertiaryLevel = true;
    $scope.getTertiaryLevel = function(id) {
        $scope.setValueSecondaryLevelInput(id);
        Products.getTertiaryLevel(id).success(function(data) {
            $scope.TertiaryLevelData = data;
            if (data.length > 0) {
                $scope.disableTertiaryLevel = false;
            } else {
                $scope.AddProductData.category_id = '';
                $scope.editProductData.category_id = '';
                $scope.disableTertiaryLevel = true;
            }
        });
    }
    $scope.getWarranty = function() {
        $ionicLoading.show({ template: templateLoading });
        Products.getWarranty().success(function(data) {
            $ionicLoading.hide();
            startpage = false;
            $scope.Warrantydata = data;
        });
    }

    $scope.getDataProduct = function(id) {
        $ionicLoading.show({
            template: templateLoading
        });
        $timeout(function() {
            dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupUpdatemodal.tpl').success(function(results) {
                $scope.dataHtml.popupPricebookEdit = results;
                $scope.showTarget('#popupPricebookEdit');
            });
        }, 500);
        $scope.Kitting_Window = {};
        $scope.Kitting_WindowData = {};
        $scope.getDataId = id;
        $scope.disableSecondaryLevel = true;
        $scope.disableSecondaryLevel = true;
        Products.getDataProduct(id, 'edit').success(function(data) {
            if (data.Tertiary.length > 0) {
                $scope.disableTertiaryLevel = false;
            }
            if (data.Secondary.length > 0) {
                $scope.disableSecondaryLevel = false;
            }
            if ($scope.getDataId != '') {
                // $scope.ProductClassData = data.Product_Class;
                if ($scope.editProductData.SecondaryLevel != data.data.SecondaryLevel) {
                    $scope.SecondaryLevelData = data.Secondary;
                }
                if ($scope.editProductData.category_id != data.data.category_id) {
                    $scope.TertiaryLevelData = data.Tertiary;
                }
            }
            $scope.Kitting_Window = data.data.kittingwindow;
            $scope.Kitting_WindowData = data.data.kittingwindow;
            $scope.kittingwindowexpand = data.kittingwindowexpand;
            $scope.showKit = false;
            // $('.ivh-treeview-twistie-collapsed').parent().parent().find('.none').slideUp();
            // $('.ivh-treeview-twistie-collapsed').html('(+)');
            if ($scope.kittingwindowexpand.length != 0) {
                for (var i = 0; i < $scope.kittingwindowexpand.length; i++) {
                    $('.' + $scope.kittingwindowexpand[i]).slideDown();
                    $('.' + $scope.kittingwindowexpand[i]).parent().find('.ivh-treeview-twistie-collapsed').html('(-)');
                }
            }
            setTimeout(function() {
                $scope.$apply(function(val) {
                    data.data.message_status = parseInt(data.data.message_status);
                    $scope.editProductData = data.data;
                    $scope.editProductData.availability = String($scope.editProductData.availability);
                    $scope.setValueProductClassInput($scope.editProductData.Product_Class);
                    $scope.setValueSecondaryLevelInput($scope.editProductData.SecondaryLevel);
                    $scope.setValueTertiaryLevelInput($scope.editProductData.category_id);
                    $scope.setValueWarrantyInput($scope.editProductData.warranty_id);
                    $scope.setValueManufacturerInput($scope.editProductData.manufacturer_id);
                    $scope.setValueAvailabilitiesInput($scope.editProductData.availability);
                    $scope.FileUpoad = '';
                    $scope.imageURI = '';
                    $ionicLoading.hide();
                });
            }, 500);
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        })
    }
    $scope.showsInActivePricebook = function(show) {
        $scope.searchProducts.show = show;
        $scope.getProducts();
    }
    $scope.createPricebook = function(file) {
        $scope.AddProductData.Kitting_Window = $scope.Kitting_WindowData;
        if ($scope.AddProductData.category_id == undefined || $scope.AddProductData.category_id == '') {
            $scope.AddProductData.category_id = $scope.SecondaryLevel;
        }
        $scope.AddProductData.discontinueddate = $('#frmAddPricebook input[name="discontinueddate"]').val();
        $scope.AddProductData.mobiApp = true;
        $scope.AddProductData.Kitting_Window =  $scope.AddProductData.Kitting_Window ? JSON.stringify($scope.AddProductData.Kitting_Window):null;
        var options = {
            fileName: 'cordovaImage.jpg',
            fileKey: "file",
            params: $scope.AddProductData,
            mimeType: 'image/jpeg',
            chunkedMode: false
        };
        Login.checkLogin().success(function(data) {
            if (data.status) {
                $cordovaFileTransfer.upload(url_server + 'products/createPricebook', $scope.FileUpoad, options).then(function(e) {
                    var results = JSON.parse(e.response);
                    $ionicLoading.hide();
                    if (results.status) {
                        $scope.getProducts();
                        $scope.closeTarget('#popupPricebookAdd');
                        $scope.AddProductData = {};
                        $scope.AddProductData.message_status = 0;
                        $scope.AddProductData.message = '';
                        $scope.Input_value = {};
                        $scope.disableTertiaryLevel = true;
                        $scope.disableSecondaryLevel = true;
                        $scope.FileUpoad = '';
                        $scope.imageURI = '';
                        $scope.Kitting_Window = {};
                        $scope.Kitting_WindowData = {};
                        $cordovaToast.showLongTop(results.msg);
                    } else {
                        $cordovaToast.showLongTop(results.msg);
                    }
                }, function(err) {
                    console.log(err);
                    $ionicLoading.hide();
                }, function(progress) {
                    $ionicLoading.show({
                        template: templateLoading
                    });
                });
            } else {
                $cordovaToast.showLongTop('Can not create pricebook');
            }
        });
    }
    $scope.EditPricebook = function(file) {
        $scope.editProductData.Kitting_Window = $scope.Kitting_WindowData;
        if ($scope.editProductData.category_id == undefined || $scope.editProductData.category_id == '') {
            $scope.editProductData.category_id = $scope.editProductData.SecondaryLevel;
        }
        $scope.editProductData.discontinueddate = $('#frmEditPricebook input[name="discontinueddate"]').val();
        $scope.editProductData.mobiApp = true;
        $scope.editProductData.Kitting_Window =  $scope.editProductData.Kitting_Window ? JSON.stringify($scope.editProductData.Kitting_Window):null;
        var success = true;
        if ($scope.FileUpoad.length < 1) {
            $ionicLoading.show({
                template: templateLoading
            });
            Products.EditPricebook($scope.editProductData).success(function(data) {
                $ionicLoading.hide();
                if (data.status) {
                    $scope.refreshPricebook();
                }
            })
        } else {
            var options = {
                fileName: 'cordovaImage.jpg',
                fileKey: "file",
                params: $scope.editProductData,
                mimeType: 'image/jpeg',
                chunkedMode: false
            };
            $cordovaFileTransfer.upload(url_server + 'products/EditPricebook', $scope.FileUpoad, options).then(function(e) {
                $ionicLoading.hide();
                var results = JSON.parse(e.response);
                if (results.status) {
                    $scope.refreshPricebook();
                }
            }, function(err) {
                console.log(err);
                $ionicLoading.hide();
            }, function(progress) {
                $ionicLoading.show({
                    template: templateLoading
                });
            });
        }
        // if (success) {
        //     $scope.closeTarget('#popupPricebookEdit')
        //     $scope.refreshPricebook($scope.editProductData);
        //     $scope.editProductData = {};
        //     $scope.FileUpoad = '';
        //     $scope.imageURI = '';
        //     $scope.disableTertiaryLevel = true;
        //     $scope.disableSecondaryLevel = true;
        //     $cordovaToast.showLongTop('Updated successful!!!!');
        // }
    }
    $scope.refreshPricebook = function() {
        var data = $scope.editProductData;
        var idx = _.findLastIndex($scope.products, { id: parseInt(data.id) });
        if (idx != -1) {
            $scope.products[idx].name = data.name;
            $scope.products[idx].part = data.part;
            $scope.products[idx].retail = data.Retail;
            $scope.products[idx].customer_aquisition = data.customer_aquisition;
            $scope.products[idx].contractor = data.Contractor;
            $scope.products[idx].walkin = data.Walk_In;
            $scope.products[idx].availabilty = data.availabilty;
        }
        if ($scope.productDetail) {
            $scope.productDetail.name = data.name;
            $scope.productDetail.part = data.part;
            $scope.productDetail.Retail = data.Retail;
            $scope.productDetail.Customer_Aquisition = data.customer_aquisition;
            $scope.productDetail.Contractor = data.Contractor;
            $scope.productDetail.Walk_In = data.Walk_In;
            $scope.productDetail.availabilty = data.availabilty;
        }
        $scope.closeTarget('#popupPricebookEdit');
        $scope.editProductData = {};
        $scope.FileUpoad = '';
        $scope.imageURI = '';
        $scope.disableTertiaryLevel = true;
        $scope.disableSecondaryLevel = true;
        $scope.Kitting_Window = {};
        $scope.Kitting_WindowData = {};
        $cordovaToast.showLongTop('Updated successful!!!!');

    }
    $scope.uploadFilePricebook = function(file) {
        $('.tblloader_import').show();
        Products.uploadFilePricebook(file).success(function(data) {
            Products.import(data).success(function(data) {
                if (data.status) {
                    $scope.getProducts();
                    $cordovaToast.showLongTop(data.msg);
                } else {
                    $scope.data_import_eror = data.data;
                    if ($scope.data_import_eror.length > 0) {
                        openPopup('#import_error');
                    }
                    $cordovaToast.showLongTop(data.msg);
                    $scope.url_file = data.url;
                    $scope.Total_rows = data.Total_rows;
                    $scope.Valid_rows = data.Valid_rows;
                    $scope.Invalid_rows = data.Invalid_rows;
                }
                $('.tblloader_import').hide();
            });
        });
    }
    $scope.Import_anyway = function() {
        $('.tblloader_import_error').show();
        Products.Import_anyway($scope.url_file).success(function(data) {
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
            $('.tblloader_import_error').hide();
            closePopupById('import_error');
        });
    }
    $scope.requiredfloat = function(value) {
        if (value.length == 0) {
            value = 0;
        } else {
            var item_length = value.toString().split('.').length;
            value = value.toString().replace(/[^0-9-.]/g, '');
            if (item_length > 1 && value.toString().split('.')[1] != '' || item_length > 2) {
                value = parseFloat(parseFloat(value).toFixed(2));
            }
            if (item_length == 1) {
                value = parseFloat(value);
            }
        }
        if (isNaN(value) == true) {
            value = 0;
        }
        return value;
    };
    $scope.change_number = function(value, action) {}
    $scope.sizeChanged = function() {
        $scope.searchProducts.rows = $scope.entryLimit;
        products_pagesize.val($scope.searchProducts.rows);
        localStorage.setItem('products_pagesize', $scope.searchProducts.rows);
        $scope.searchProducts.current_page = 1;
        $scope.getProducts();
    }
    $scope.pageChanged = function() {
        //console.log($scope.currentPage);
        $scope.searchProducts.current_page = $scope.currentPage;
        $scope.getProducts();
    };
    //$scope.getProducts();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addProductsData = {};
    $scope.createProducts = function() {
        Products.save($scope.addProductsData).success(function(data) {
            $scope.addProductsData = {};
            $scope.getProducts();
            if (data.status) {
                $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 Errror!!!');
        })
    }
    $scope.editProductsData = {};
    $scope.editProducts = function(id) {
        $('.loader').show();
        Products.show(id).success(function(data) {
            $('.loader').hide();
            $scope.editProductsData = data;
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        })
    }
    $scope.productDetail = {};
    $scope.getProductDetail = function(id) {
        $scope.openByGetTemplate('popupPricebookDetail');
        Products.getDataProduct(id, 'edit').success(function(data) {
            $ionicLoading.hide();
            $scope.productDetail = data.data;
            $scope.TertiaryLevelData = data.Tertiary;
            $scope.SecondaryLevelData = data.Secondary;
            $timeout(function() {
                $scope.setValueProductClassInput($scope.productDetail.Product_Class);
                $scope.setValueSecondaryLevelInput($scope.productDetail.SecondaryLevel);
                $scope.setValueTertiaryLevelInput($scope.productDetail.category_id);
                $scope.setValueWarrantyInput($scope.productDetail.warranty_id);
            }, 500);
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Errror!!!');
        })
    }

    $scope.updateProducts = function() {
        var id = $scope.editProductsData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Products.update(id, $scope.editProductsData).success(function(data) {
            $ionicLoading.hide();
            $scope.getProducts();
            if (data.status) {
                $scope.editProductsData = {};
                $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 Errror!!!');
        })
    }
    $scope.deleteProductsData = {};
    // $scope.deleteProductsData = {};
    $scope.confrimProducts = function(item) {
        $scope.deleteProductsData.id = item.id;
        $scope.deleteProductsData.name = item.name;
        $scope.openByGetTemplate('popupPricebookDelete');
    }
    $scope.deleteProducts = function() {
        var id = $scope.deleteProductsData.id;
        $ionicLoading.show({ template: templateLoading });
        Products.check_order(id.toString()).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                var idx = _.findLastIndex($scope.products, { id: parseInt(id) });
                $scope.products.splice(idx, 1);
                $scope.closeTarget("#popupPricebookDetail");
                $scope.closeTarget("#popupPricebookDelete");
                $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 Errror!!!');
        })
    }
    $scope.deleteProducts_items = function(id, confirm) {
        Products.destroy(id).success(function(data) {
            $scope.deleteProductsData = {};
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
                confirm.switchStateDialog("close");
            } else {
                $cordovaToast.showLongTop(data.msg);
                confirm.switchStateDialog("close");
            }
            $scope.getProducts();
        });
    }
    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            //current_ext = data.extension_phone;
            if (data == false) {
                localStorage.setItem("login_status", "0");
                redirectTo('index.html');
            } else {
                var index = _.findIndex(data.jsondata,{roletree_id:'87'});
                if(data.jsondata[index].check){
                    if($scope.roleName == $scope.isAdmin || $scope.roleName == $scope.isStrategicDevelopment){
                        $scope.NumCol = 2;
                    }else{
                        $scope.NumCol = 1;
                    }
                    $scope.viewSearch = data.jsondata[index].child[0].check;
                    $scope.hideForUser = data.jsondata[index].child[1].check;
                    $scope.actionCol = data.jsondata[index].child[2].check;
                    $scope.editShow = data.jsondata[index].child[2].check;
                    $scope.deleteShow = data.jsondata[index].child[3].check;

                    current_ext = data.extension_phone;
                    $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.getProductAvailabilities();
                }else{
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                }
            }
        });
    }
    // $scope.getProductsClass();
    // $scope.getUserLogin();
    $scope.logout = function() {
        return Login.logout().success(function(data) {
            $window.location.href = url_login;
        });
    }
    // $scope.checkLogin = function() {
    //         // console.log('ate');
    //         return Login.checkLogin().success(function(data) {
    //             if (data.status == false) {
    //                 // $window.location.href = url_login;
    //             } else {
    //                 $scope.getUserLogin();
    //             }
    //         });
    //     }
    // $scope.checkLogin();
    // stopTime = $interval($scope.checkLogin, time_refresh);
    $scope.repalaceres = function(data) {
        setTimeout(function() {
            $scope.$apply(function(val) {
                if (val) {
                    $('#tableProducts').tableRespondsive({
                        paging: true,
                        pagingArg: {
                            totalRow: 105,
                            rowPerPage: 50,
                            currentPage: 2
                        }
                    });
                    $('#tableProducts .customer-phone-action .icon').toggleShow('.option-pop-1', {
                        effect: 'fade',
                        outcollapse: true
                    });
                    // for slideToggle
                    $('.ivh-treeview-twistie-collapsed').unbind();
                    $('.ivh-treeview-twistie-collapsed').click(function() {
                        if ($(this).text() == '(+)') {
                            $(this).parent().parent().find('.none').slideToggle();
                        } else {
                            $(this).parent().parent().find('.none').slideUp();
                        }
                        $(this).text() == '(+)' ? $(this).html('(-)') : $(this).html('(+)');
                    });
                    $('#document .tblloader').hide();
                    $('.content .row').show();
                }
            });
        }, 1);
    }
    $scope.hideUpdateButtonAndDeleteIcon = function() {
        switch ($scope.roleName) {
            //saleman
            case $scope.isSalesman:
            $scope.NumCol = 1;
            return true;
            break;
            //fieldinstaller
            case $scope.isFieldinstaller:
            $scope.NumCol = 1;
            return true;
            break;
            //admin
            case $scope.isAdmin:
            $scope.NumCol = 2;
            return false;
            break;
            //manager
            case $scope.isManager:
            $scope.NumCol = 1;
            return true;
            break;
            //isReporter
            case $scope.isReporter:
            $scope.NumCol = 1;
            return true;
            break;
            //isScheduler
            case $scope.isWarehouse:
            $scope.NumCol = 1;
            return true;
            break;
        }
    }

    // edit by haudao
    $scope.validateForm = function(formValidate,file, style) {
        var exitLoop = false;
        if (formValidate.$invalid) {
            $ionicScrollDelegate.$getByHandle('scrollPricebook' + style).scrollTop();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            // console.log(formValidate.$error.required[0].$name);
            // angular.forEach(formValidate.$error, function(item) {
            //     if (!exitLoop) {
            //         var id = item[0].$name;
            //         // console.log(id);
            //         $location.hash(id); //set the location hash
            //         var handle = $ionicScrollDelegate.$getByHandle('scrollPricebook' + style);
            //         handle.anchorScroll(true);
            //         exitLoop = true;
            //         $timeout(function() {
            //             // console.log(handle.getScrollPosition());
            //             var top = handle.getScrollPosition().top - 170;
            //             // console.log(top);
            //             handle.scrollTo(0, top, true);
            //             $cordovaToast.showLongTop('Please fill all the required information.!!!');
            //         }, 1000);
            //     }
            // })
            return;
        };
        if (style == 'Add') {
            if (!$scope.FileUpoad) {
                // $location.hash('imageURI'); //set the location hash
                // var handle = $ionicScrollDelegate.$getByHandle('scrollPricebook' + style);
                // handle.anchorScroll(true);
                $ionicScrollDelegate.$getByHandle('scrollPricebook' + style).scrollTop();
                $cordovaToast.showLongTop('Please fill all the required information.!!!');
                return;
            }
            $scope.createPricebook(file);
        } else {
            $scope.EditPricebook(file);
        }
    }
    $scope.Input_value = {};
    $scope.setValueProductClassInput = function(id) {
        $scope.Input_value.productClass = "";
        var index = _.findLastIndex($scope.ProductClassData, {
            id: id
        });
        if (index >= 0) $scope.Input_value.productClass = $scope.ProductClassData[index].name;
    }
    $scope.setValueSecondaryLevelInput = function(id) {
        $scope.Input_value.secondaryLevel = "";
        var index = _.findLastIndex($scope.SecondaryLevelData, {
            id: id
        });
        if (index >= 0) $scope.Input_value.secondaryLevel = $scope.SecondaryLevelData[index].name;
    }
    $scope.setValueTertiaryLevelInput = function(id) {
        $scope.Input_value.tertiaryLevel = "";
        var index = _.findLastIndex($scope.TertiaryLevelData, {
            id: id
        });
        if (index >= 0) $scope.Input_value.tertiaryLevel = $scope.TertiaryLevelData[index].name;
    }
    $scope.setValueWarrantyInput = function(id) {
        $scope.Input_value.warranty = "";
        var index = _.findLastIndex($scope.Warrantydata, {
            id: id
        });
        if (index >= 0) $scope.Input_value.warranty = $scope.Warrantydata[index].name;
    }
    $scope.setValueManufacturerInput = function(id) {
        var index = _.findLastIndex($scope.manufacturers, {
            id: id
        });
        if (index >= 0){
            $scope.Input_value.manufacturer = $scope.manufacturers[index].name;
        } else{
            $scope.Input_value.manufacturer = "Null";
        }
    }
    $scope.setValueAvailabilitiesInput = function(id) {
        $scope.Input_value.availability = "";
        var index = _.findLastIndex($scope.productavailabilitySelect, {
            id: id
        });
        if (index >= 0){
            $scope.Input_value.availability = $scope.productavailabilitySelect[index].name;
        }else{
            $scope.Input_value.availability = 'Select';
        }
    }
    $scope.LoadMorePriceBook = function() {
        if (!$scope.checkLoadMore) return;
        $scope.searchProducts.current_page++;
        Products.getPaging($scope.searchProducts).success(function(data) {
            if (data.data.length < $scope.itemsPerPage) $scope.checkLoadMore = false;
            data.data.forEach(function(item) {
                if ($scope.products.indexOf(item) < 0) $scope.products.push(item);
            })
        })
        $timeout(function() {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }, 2000);
    };
    // $scope.search = {};
    // $scope.clearSearch = function() {
    //     $scope.searchProducts.search = '';
    //     $scope.getProducts();
    // }
    // $scope.keypress = function(delegate) {
    //     var keysByCode = [9, 16, 17, 18, 20, 27, 32, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 144];
    //     if ($scope.searchProducts.search.keyCode >= 112 && $scope.searchProducts.search.keyCode <= 123) return;
    //     if (keysByCode.indexOf($scope.searchProducts.search.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) {
    //                 $scope.SearchChange();
    //                 clearInterval($scope.myTime);
    //                 $ionicScrollDelegate.$getByHandle(delegate).resize();
    //             }
    //         }, 100);
    //     }
    // $scope.SearchChange = function() {
    //     $scope.searchProducts.current_page = 1;
    //     $scope.checkLoadMore = false;
    //     $scope.getProducts();
    // }

    $scope.openActionSheet = function() {
        var options = {
            // title: 'What do you want with this image?',
            buttonLabels: ['Camera', 'Photo'],
            addCancelButtonWithLabel: 'Cancel',
            androidEnableCancelButton: true,
        };
        $cordovaActionSheet.show(options).then(function(index) {
            if (index == 1) {
                $scope.takePicture();
            } else if (index == 2) {
                $scope.selectPicture();
            }
        });
    }
    $scope.imageURI = '';
    $scope.takePicture = function() {
        var options = {
            quality: 100,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            // allowEdit: true,
            // targetWidth: 500,
            // targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };
        $cordovaCamera.getPicture(options).then(function(imageData) {
            $ionicLoading.show({ template: templateLoading });
            $timeout(function() {
                $ionicLoading.hide();
            }, 2000);
            // var imageUrl = "data:image/jpeg;base64," + imageData;
            console.log(imageData);
            $scope.imageURI = imageData;
            $scope.FileUpoad = imageData;
        }, function(err) {
            console.log(err);
            $cordovaToast.showLongTop(err);
        });
    }
    $scope.selectPicture = function() {
        var options = {
            maximumImagesCount: 1,
            width: 0,
            height: 0,
            quality: 100
        };
        $cordovaImagePicker.getPictures(options).then(function(results) {
            $ionicLoading.show({ template: templateLoading });
            $timeout(function() {
                $ionicLoading.hide();
            }, 2000);
            console.log(results[0]);
            $scope.FileUpoad = results[0];
            $scope.imageURI = $scope.FileUpoad ;
            // window.plugins.Base64.encodeFile($scope.FileUpoad, function(base64) {
            //     $scope.imageURI = base64;
            // });
        }, function(err) {
            console.log(err);
            $cordovaToast.showLongTop(err);
        });
    }
    $scope.resetFormAddPricebook = function() {
        $scope.AddProductData = {};
        $scope.Input_value = {};
        $scope.FileUpoad = '';
        $scope.imageURI = '';
    }
    $scope.filterPricebookForSearch = function(query) {
        var returnValue = {
            items: []
        };
        var params = {
            rows: 50,
            current_page: 1,
            search: query,
            show: $scope.showpricebook,
            type: 'Entire Pricebook'

        };
        $('#temp-autocompletetemp-autocomplete .none-result').css('display','none');
        $scope.coundown = 10;
        if ($scope.myTime != null)
            clearInterval($scope.myTime);
        $scope.myTime = setInterval(function () {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
                clearInterval($scope.myTime);
                $ionicLoading.show({ template: templateLoading });
                Products.getPaging(params).success(function(data) {
                    $scope.rootDataPricebook = data.data;
                    $scope.rootDataPricebook.forEach(function(item) {
                        returnValue.items.push(item);
                    });
                    $ionicLoading.hide();
                    if(returnValue.items.length > 0){
                        $('#temp-autocomplete .none-result').css('display','none');
                    }
                    else{
                        $('#temp-autocomplete .none-result').css('display','block');
                    }
                });
            }
        }, 100);

        return returnValue;
    }
    $scope.selectPricebookFormSearch = function(callback) {
        $scope.getProductDetail(callback.item.id);
        $scope.initialPricebookForSearch = [];
    }
    $scope.modelPricebookForSearch = function(modelValue) {
        return
    }
    $scope.openAutocomplete = function(className) {
        dataHtml.getTemplate('templates/dashboard/pricebooks/pricebookPopupSearchmodal.tpl').success(function(results) { $scope.dataHtml.searchPricebooks = results; });
        $timeout(function() {
            var ionAutocompleteElement = document.getElementsByClassName(className);
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
            angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
            $timeout(function() {
                angular.element('.backdrop').removeClass('visible').removeClass('active');
            }, 1000);
        }, 500)

    }
    if (page == "pricebook.html") $scope.renderTemplateData();
    // end edit
})
