(function () {
    global.dashModule
        .controller('shopPackagesCtrl', ['$scope', '$http', '$', 'utilsService', shopPackagesController])
        .directive('shopPackages', [shopPackagesDirective]);

    function shopPackagesDirective() {
        return {
            restrict: 'E',
            templateUrl: 'shop/html/shopPackagesTemplate'
        };
    }

    function shopPackagesController($scope, $http, $, utilsService) {
        $scope.getShopPackages = getShopPackages;
        $scope.getComemrcialLeads = getComemrcialLeads;
        $scope.selectCommercialLead = selectCommercialLead;
        $scope.isComemrcialLeadSelected = isComemrcialLeadSelected;
        $scope.commercialLeads = [];
        $scope.shopPackages = [];
        $scope.idCommercialLead = 0;
        $scope.commercialLeadName = '';

        function getComemrcialLeads(){
            $http({
                method: 'POST',
                url: 'shop/api/getAllCommercialLeads'
            }).then(setCommercialLeads, utilsService.onHttpError);
        }

        function setCommercialLeads(response){
            if (response.data.length > 0) {
                $scope.commercialLeads = response.data;
                selectCommercialLead($scope.commercialLeads[0]);
            }
        }

        function selectCommercialLead(comemrcialLead){
            $scope.idCommercialLead = comemrcialLead.idCommercialLead;
            $scope.commercialLeadName = comemrcialLead.commercialLeadName;
            getShopPackages();
        }

        function isComemrcialLeadSelected(idCommercialLead){
            return $scope.idCommercialLead === idCommercialLead ? 'selected-cl' : '';
        }

        function getShopPackages() {
            const params = $.param({
                idCommercialLead: $scope.idCommercialLead,
                search: global.getParameterByName('search') || ''
            });
            $http({
                method: 'POST',
                url: 'shop/api/getShopPackages',
                data: params
            }).then(setShopPackages, utilsService.onHttpError);
        }

        function setShopPackages(response) {
            $scope.shopPackages = response.data.length > 0 ? response.data : [];
        }
    }
})();
