/**
 * Created by majid on 14/01/2017.
 */
(function () {
    'use strict';

    angular.module('BlurAdmin.pages.catalogue.groupProduits', [])
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('catalogue.groupProduits', {
                url: '/groupeProduits',
                templateUrl: 'app/pages/catalogue/groupeProduits/groupeProduits.html',
                title: 'Sous Familles',
                sidebarMeta: {
                    icon: 'ion-android-home',
                    order: 200,
                },
                controller: function ($scope, $stateParams, $http) {
                    if(!$scope.isLogged())
                        window.location.replace('/#/login');

                    $scope.groups = [];
                    $scope.totalGroups = 0;
                    $scope.groupsPerPage = 25;
                    $scope.pageChanged = function(newPage) {
                        loadGroups(newPage);
                    };

                    $('#Loaderdiv').hide();
                    $('#divTable').hide();
                    $('#divEmpty').hide();
                    $('#msgError').hide();
                    function getCategories() {
                        var url = $scope.url+"categories";
                        $http({
                            method: 'GET',
                            url: url,
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {

                            if(response.status == 200) {
                                $scope.categories = response.data;
                                $scope.CatMdl = $scope.categories[0].id ;
                            } else
                                $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                        }, function errorCallback(response) {
                            $scope.response_error = response.data.message;
                        });
                    }
                    getCategories();
                    $scope.searchCommand = function (pageNumber) {
                        console.log('getParamsSearch()',getParamsSearch())
                        $('#Loaderdiv').show();
                        $('#divTable').hide();
                        $('#divEmpty').hide();
                        $('#msgError').hide();
                        var url = $scope.url+"groups?pagination_per_page=25&page="+pageNumber;
                        $http({
                            method: 'GET',
                            url: url,
                            params : getParamsSearch(),
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {
                            $('#Loaderdiv').hide();
                            $('#divTable').show();
                            if(response.status == 200) {
                                $scope.groups = response.data.data;
                                $scope.totalGroups = response.data.total;
                                if($scope.groups.length < 1){
                                    $('#divTable').hide();
                                    $('#divEmpty').show();
                                    $('#msgError').hide();
                                } else {
                                    $('#divTable').show();
                                    $('#divEmpty').hide();
                                    $('#msgError').hide();
                                }

                            } else {
                                $scope.error_response = $scope.getErrorMessage(response);
                                $('#divTab').hide();
                                $('#msgError').show();
                            }

                        }, function errorCallback(response) {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTab').hide();
                            $('#Loaderdiv').hide();
                            $('#msgError').show();

                        });
                    }
                    function loadGroups(pageNumber) {

                        var url = $scope.url+"groups?pagination_per_page=25&page="+pageNumber;
                        $http({
                            method: 'GET',
                            url: url,
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {
                            $('#Loaderdiv').hide();
                            if(response.status == 200) {
                                $scope.groups = response.data.data;
                                $scope.totalGroups = response.data.total;
                                $('#divTab').show();

                            } else {
                                $scope.error_response = $scope.getErrorMessage(response);
                                $('#divTab').hide();
                                $('#msgError').show();
                            }

                        }, function errorCallback(response) {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTab').hide();
                            $('#Loaderdiv').hide();
                            $('#msgError').show();

                        });
                    };
                    //loadGroups($scope.pagination.currentSsFamille);
                    // désactiver groupe produit
                    $scope.dactivatedGroup = function (id, isDeactivated) {
                        var url = $scope.url+"groups/"+id;
                        $('#msgError').hide();
                        $scope.group_data = {
                            deactivated  : isDeactivated
                        };
                        $http({
                            method: 'PUT',
                            url: url,
                            params :  $scope.group_data,
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {

                            if(response.status == 200)
                                loadGroups($scope.pagination.current);
                              else  {
                                $scope.error_response = $scope.getErrorMessage(response);
                                $('#msgError').show();
                            }


                            $('#msgTop').show()
                        }, function errorCallback(response) {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#msgError').show();
                        });
                    }
                    // Hide message
                    $scope.hideMsg = function () {
                        $('#msgTop').hide();
                    }
                    function calculateGroupLength(){
                            $scope.groupList = $scope.groups;
                    };
                    $scope.$watch($scope.groups, calculateGroupLength);
                    $scope.checkFamille = function (val) {
                        $scope.familleModel = val;
                    };
                    $scope.checkfamilleBox = function (val) {
                        $scope.familleModelCheckbox = val;
                        if($scope.familleModelCheckbox==true) $('#familleModel').val("");
                    };
                    function getParamsSearch() {

                        var paramsSearch = {};
                        var famille    = {category_id      : $scope.familleModel};
                        if(!$scope.familleModelCheckbox)
                            paramsSearch = angular.extend({},paramsSearch,famille)
                        return paramsSearch;
                    }
                }
            }).state('consultationGroup', {
            url: '/consultationGroup',
            params: {id : null},
            templateUrl: 'app/pages/catalogue/groupeProduits/consultationGroup/consultationGroup.html',
            controller: function ($scope, $stateParams, $http, $state) {
                if (!$scope.isLogged())
                    window.location.replace('/#/login');

                $('#msgError').hide();
                $('#divBody').hide();
                if($stateParams.id != null)
                    $scope.putCoockie('parmsID', $stateParams.id);
                $scope.isEmptyList = true;
                var groupId = $scope.getCoockie('parmsID');
                var url = $scope.url+"groups/"+$scope.getCoockie('parmsID');

                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Authorization" : $scope.userSession()
                    }
                }).then(function successCallback(response) {
                    if(response.status == 200) {
                        $('#msgError').hide();
                        $('#divBody').show();
                        $scope.detailGroup    = response.data;
                        $scope.prods          = $scope.detailGroup.products;
                        if($scope.prods.length > 0)
                            $scope.isEmptyList = false;
                        else
                            $scope.isEmptyList = true;

                        $scope.clients         = $scope.detailGroup.clients;
                        $scope.descriptionShortMdl  = $scope.detailGroup.description_short;
                        $scope.descriptionLongMdl = $scope.detailGroup.description_detailled;
                        $scope.catMdl = 0;

                    } else {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#msgError').show();
                        $('#divBody').hide();
                    }

                }, function errorCallback(response) {
                    $scope.error_response = $scope.getErrorMessage(response);
                    $('#msgError').show();
                    $('#divBody').hide();
                });
            }

            }).state('updateGroup', {
            url: '/updateGroup',
            params: {id: null},
            templateUrl: 'app/pages/catalogue/groupeProduits/updateGroup/updateGroup.html',
            controller: function ($scope, $stateParams, $http, $state) {
                if (!$scope.isLogged())
                    window.location.replace('/#/login');

                if($stateParams.id != null)
                    $scope.putCoockie('parmsID', $stateParams.id);

                $('#msgTop').hide();
                $('#Loaderdiv').hide();
                $('#msgError').hide();
                $('#divBody').hide();
                // prepare external references
                $scope.references = [];

                // add row
                $scope.addItem = function () {
                    $scope.references.push(
                        {
                            client_id : null,
                            client_name : " ",
                            visible : true
                        })
                }

                var url = $scope.url+"groups/"+$scope.getCoockie('parmsID');

                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Authorization" : $scope.userSession()
                    }
                }).then(function successCallback(response) {
                    if(response.status == 200) {
                        $scope.detailGroup    = response.data;

                        $scope.pictureMDL               = { name : $scope.detailGroup.picture};
                        $scope.previewImage             = "assets/pictures/"+$scope.detailGroup.picture;
                      //  $scope.pictures                 =$scope.detailGroup.pictures;

                        for(var i = 0; i< $scope.detailGroup.clients.length ;i++) {
                            $scope.references.push(
                                {
                                    client_id : $scope.detailGroup.clients[i].pivot.client_id,
                                    client_name : $scope.detailGroup.clients[i].pivot.reference_name,
                                    visible : true
                                })
                        }
                        $('#msgError').hide();
                        $('#divBody').show();
                    } else {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#msgError').show();
                        $('#divBody').hide();
                    }


                }, function errorCallback(response) {
                    $scope.error_response = $scope.getErrorMessage(response);
                    $('#msgError').show();
                    $('#divBody').hide();
                });
                // Get categories
                function getCategories() {
                    var url = $scope.url+"categories";
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200) {
                            $scope.categories = response.data;
                            //$scope.CatMdl = $scope.categories[0].id ;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $scope.response_error = response.data.message;
                    });
                }
                getCategories();


                // Get clients
                function getClients() {
                    var url = $scope.url+"clients";
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200) {
                            $scope.clients = response.data;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $scope.response_error = response.data.message;
                    });
                }
                getClients();

                // Put groupe
                $scope.updateGroup = function () {
                    $('#msgTop').hide();
                    $('#Loaderdiv').show();
                    prepareReferences();
                   // console.log("pictures", $scope.pictures)
                    $scope.pictures=[];
                    if($scope.filesArray && $scope.filesArray.length>0) {
                        for (var i = 0; i < $scope.filesArray.length; i++) {
                            $scope.pictures.push(
                                {
                                    url: $scope.filesArray[i].name
                                })
                        }
                    }
                    var picture;
                    if($scope.pictureMDL.name!==null) picture=$scope.pictureMDL.name.toString();

                    var group_data = {
                        deactivated                     : $scope.detailGroup.deactivated,
                        visible_individual              : $scope.detailGroup.visible_individual,
                        name                            : $scope.detailGroup.name,
                        description_detailled           : $scope.detailGroup.description_detailled,
                        description_short               : $scope.detailGroup.description_short,
                        category_id                     : $scope.detailGroup.category_id,
                        picture                         : picture,
                        external_references             : $scope.referencesExt,
                        pictures                        : $scope.pictures
                    };



                    var url = $scope.url+"groups/"+$scope.getCoockie('parmsID');
                    $http({
                        method: 'PUT',
                        url: url,
                        //data :  $.param(group_data),
                        data :  JSON.stringify(group_data),
                        headers: {
                            //"Content-Type": "application/x-www-form-urlencoded",
                            "Content-Type": "application/json",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200){
                            $scope.response_success = "Groupe bien ajoutée.";
                            window.location.replace('/#/catalogue/groupeProduits');
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                        $('#Loaderdiv').hide();
                    }, function errorCallback(response) {
                        $('#Loaderdiv').hide();
                        $('#msgTop').show();
                        $scope.error_update =$scope.getErrorMessage(response);
                    });
                }

                // remove row
                $scope.removeReference = function (item) {
                    var index = $scope.references.indexOf(item);
                    $scope.references[index].visible = false;
                    //$scope.references.splice(index, 1);
                }
                function prepareReferences() {
                    $scope.referencesExt = [];
                    for (var i = 0; i<$scope.references.length; i++){
                        if($scope.references[i].visible)
                          $scope.referencesExt.push({client_id : parseInt($scope.references[i].client_id),reference_name : $scope.references[i].client_name})
                    }
                }
                $scope.checkDeactivate = function() {
                    if ($scope.detailGroup.deactivated == 0)
                        $scope.detailGroup.deactivated = 1;
                    else
                        $scope.detailGroup.deactivated = 0;
                }
                $scope.checkVisible = function() {
                    if ($scope.detailGroup.visible_individual == 0)
                        $scope.detailGroup.visible_individual = 1;
                    else
                        $scope.detailGroup.visible_individual = 0;
                }
                $scope.checkPic = function(val) {
                    $scope.pictureMDL = val ;
                }
                $scope.checkPictures = function(val) {
                    $scope.filesArray = val ;
                }
            }

          }).state('addGroup', {
            url: '/addGroup',
            templateUrl: 'app/pages/catalogue/groupeProduits/addGroup/addGroup.html',
            title: 'Ajouter groupe produit',
            controller: function ($scope, $stateParams, $http, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');

                $('#msgTop').hide();
                $('#Loaderdiv').hide();

                $scope.detailGroup = {deactivated: 0,
                                      visible_individual: 0,
                                      name: null,
                                      description_detailled: null,
                                      description_short: null,
                                      category_id: null};
                $scope.pictures = [];
                $scope.references = [];

                // add row
                $scope.addItem = function () {
                    $scope.references.push(
                        {
                            client_id : null,
                            client_name : null,
                            visible : true
                        })
                }
                // remove row
                $scope.removeReference = function (item) {
                    var index = $scope.references.indexOf(item);
                    $scope.references[index].visible = false;
                    //$scope.references.splice(index, 1);
                }
                // Get categories
                function getCategories() {
                    var url = $scope.url+"categories";
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200) {
                            $scope.categories = response.data;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $scope.response_error = response.data.message;
                    });
                }
                getCategories();

                // Get clients
                function getClients() {
                    var url = $scope.url+"clients";
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200) {
                            $scope.clients = response.data;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $scope.response_error = response.data.message;
                    });
                }
                getClients();
                // Post groupe
                $scope.addGroup = function () {
                    $('#msgTop').hide();
                    $('#Loaderdiv').show();
                    prepareReferences();
                   if ($scope.filesArray)
                       for(var i = 0; i< $scope.filesArray.length ;i++) {
                            $scope.pictures.push(
                                {
                                   url : $scope.filesArray[i].name
                              })
                        }
                    $scope.group_data = {
                        deactivated                     : $scope.detailGroup.deactivated,
                        visible_individual              : $scope.detailGroup.visible_individual,
                        name                            : $scope.detailGroup.name,
                        description_detailled           : $scope.detailGroup.description_detailled,
                        description_short               : $scope.detailGroup.description_short,
                        category_id                     : $scope.detailGroup.category_id,
                        external_references             : $scope.referencesExt,
                        pictures                        : $scope.pictures
                    };
                    if($scope.pictureMDL != null) {
                        var picParams = {picture             : $scope.pictureMDL.name.toString()};
                        $scope.group_data = angular.extend({},$scope.group_data, picParams)
                    }

                    var url = $scope.url+"groups";

                    $http({
                        method: 'POST',
                        url: url,
                        data :  JSON.stringify($scope.group_data),
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200){
                            $scope.response_success = "Groupe bien ajoutée.";
                            window.location.replace('/#/catalogue/groupeProduits');
                        } else
                            $scope.error_add = $scope.getErrorMessage(response);
                        $('#msgTop').hide();
                        $('#Loaderdiv').hide();

                    }, function errorCallback(response) {
                        $scope.error_add = $scope.getErrorMessage(response);
                        $('#msgTop').show();
                        $('#Loaderdiv').hide();
                    });
                }
                // prepare external references
                  function prepareReferences() {

                    $scope.referencesExt = [];
                    for (var i = 0; i<$scope.references.length; i++){
                        if($scope.references[i].visible)
                          $scope.referencesExt.push({client_id : $scope.references[i].client_id,reference_name : $scope.references[i].client_name})
                    }
                }

                $scope.checkDeactivate = function() {
                    if ($scope.detailGroup.deactivated == 0)
                        $scope.detailGroup.deactivated = 1;
                    else
                        $scope.detailGroup.deactivated = 0;
                }
                $scope.checkVisible = function() {
                    if ($scope.detailGroup.visible_individual == 0)
                        $scope.detailGroup.visible_individual = 1;
                    else
                        $scope.detailGroup.visible_individual = 0;
                }
                $scope.checkPic = function(val) {
                    $scope.pictureMDL = val ;
                }
                $scope.checkPictures = function(val) {
                    $scope.filesArray = val ;
                }
            }
        });
    }

})();
