/**
 * Created by majid on 29/01/2017.
 */

(function () {
    'use strict';

    angular.module('BlurAdmin.pages.utilisateurs.revendeurs', [])
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('utilisateurs.revendeurs', {
                url: '/revendeurs',
                templateUrl: 'app/pages/utilisateurs/revendeurs/revendeurs.html',
                title: 'Revendeurs',
                sidebarMeta: {
                    icon: 'glyphicon-th-list',
                    order: 200,
                },
                controller: function ($scope, $stateParams, $http, $state) {
                    if(!$scope.isLogged())
                        window.location.replace('/#/login');

                    $('#Loaderdiv').hide();
                    $('#divTable').hide();
                    $('#divEmpty').hide();
                    $('#msgError').hide()

                    $scope.revendeurs          = [];
                    $scope.totalRevendeurs     = 0;
                    $scope.revendeursPerPage   = 25;
                    $scope.pageChanged = function(newPage) {
                        getRevendeurs(newPage);
                    };
                    $scope.searchCommand = function (pageNumber) {
                        $('#Loaderdiv').show();
                        $('#divTable').hide();
                        $('#divEmpty').hide();
                        $('#msgError').hide();
                        console.log("getParamsSearch",getParamsSearch())
                        var url = $scope.url+"resellerCompanies?pagination_per_page=25&page="+pageNumber;
                        $http({
                            method: 'GET',
                            url: url,
                            params : getParamsSearch(),
                            headers: {
                                "Content-Type": "application/json;charset=UTF-8",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {
                            $('#Loaderdiv').hide();
                            $('#divTable').show();
                            if(response.status == 200) {
                                $scope.totalRevendeurs = response.data.total;
                                $scope.revendeurs = response.data.data;
                                if($scope.revendeurs.length < 1){
                                    $('#divTable').hide();
                                    $('#divEmpty').show();
                                    $('#msgError').hide();
                                } else {
                                    $('#divTable').show();
                                    $('#divEmpty').hide();
                                    $('#msgError').hide();
                                }

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

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

                        });
                    }
                    function getRevendeurs(pageNumber) {
                        var url = $scope.url+"resellerCompanies?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.totalRevendeurs = response.data.total;
                                $scope.revendeurs = response.data.data;
                                $('#divTable').show();
                                $('#msgError').hide();
                            } else {
                                $scope.error_response = $scope.getErrorMessage(response);
                                $('#divTable').hide();
                                $('#msgError').show();
                            }

                        }, function errorCallback(response) {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#Loaderdiv').hide();
                            $('#divTable').hide();
                            $('#msgError').show();
                        });
                    }
                    function getClients() {
                        var url = $scope.url+"clients";
                        $http({
                            method: 'GET',
                            url: url,
                            headers: {
                                "Content-Type": "application/json;charset=UTF-8",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {

                            if(response.status == 200) {
                                $scope.clients = response.data;
                            }

                        }, function errorCallback(response) {

                        });
                    }
                    getClients();
                    function getStatuses () {

                        var url = $scope.baseUrl+"/api/users/individuals/v1_0/towns";
                        $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.towns = response.data;
                            else
                                $scope.reror_status = "Une erreur s'est produite, merci de réessayer.";

                        }, function errorCallback(response) {
                            $scope.reror_status = "Une erreur s'est produite, merci de réessayer.";
                        });
                    }
                    $scope.deactivateRevendeur = function (id, val) {
                        $('#msgError').hide();
                        $scope.reseller_data_deactive = {
                            company: {
                                deactivated  : val
                            }
                        };
                        var url = $scope.url+"resellerCompanies/"+id;
                        $http({
                            method  : 'PUT',
                            url     : url,
                            data  :  $.param($scope.reseller_data_deactive),
                            headers : {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization" : $scope.userSession()
                            }
                        }).then(function successCallback(response) {

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

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

                        var paramsSearch = {};

                        var status        = {town      : $scope.stateModel};
                        var name          = {name  : $scope.nameMdl};
                        var codeClient    = {client_id      : $scope.codeClientMdl};

                        if(!$scope.stateModelBox)
                            paramsSearch = angular.extend({},paramsSearch, status)

                        if(!$scope.nameMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, name)
                        if(!$scope.codeClientMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, codeClient)
                        return paramsSearch;
                    }
                    //getRevendeurs($scope.pagination.currentRevendeurs);
                    $scope.checkCode = function (val) {
                        $scope.codeModel = val;
                    };
                    $scope.checkCodeBox = function (val) {
                        $scope.codeModelBox = val;
                        if($scope.codeModelBox==true) $('#codeModel').val("");
                    };
                    $scope.checkName = function (val) {
                        $scope.nameMdl = val;
                    };
                    $scope.checkNameBox = function (val) {
                        $scope.nameMdlBox = val;
                        if($scope.nameMdlBox==true) $('#nameMdl').val("");
                    };
                    $scope.checkCodeClient = function (val) {
                        $scope.codeClientMdl = val;
                    };
                    $scope.checkCodeClientBox = function (val) {
                        $scope.codeClientMdlBox = val;
                        if($scope.codeClientMdlBox==true) $('#codeClientMdl').val("");
                    };
                    $scope.checkStatus = function (val) {
                        $scope.stateModel = val;
                    };
                    $scope.checkStatusBox = function (val) {
                        $scope.stateModelBox = val;
                        if($scope.stateModelBox==true) $('#stateModel').val("");
                    };

                }

            }).state('consultationRevendeur', {
            url: '/consultationRevendeur',
            params: {id : null},
            templateUrl    : 'app/pages/utilisateurs/revendeurs/consultationRevendeur/consultationRevendeur.html',
            title: 'Consultation Revendeurs',
            controller: function ($scope, $http, $stateParams, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');

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

                $('#Loaderdiv').show();
                $('#divTable').hide();
                $('#msgError').hide();
                function getRevendeur() {
                    var url = $scope.url+"resellerCompanies/"+$scope.getCoockie('parmsID');
                    $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) {
                            $('#divTable').show();
                            $('#msgError').hide();
                            $scope.detailRevendeur = response.data;
                            $scope.remisesRevendeur = $scope.detailRevendeur.discounts;
                            $scope.favorisRevendeur = $scope.detailRevendeur.favourites;
                            $scope.adressesLivraisonRevendeur= $scope.detailRevendeur.delivery_addresses;
                            $scope.resellersByCompanie = response.data.resellers;
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTable').hide();
                            $('#msgError').show();
                        }
                    }, function errorCallback(response) {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#Loaderdiv').hide();
                        $('#divTable').hide();
                        $('#msgError').show();
                    });
                }
                getRevendeur();
            }
        }).state('addRevendeur', {
            url: '/addRevendeur',
            params: {id : null},
            templateUrl    : 'app/pages/utilisateurs/revendeurs/addRevendeur/addRevendeur.html',
            title: 'Ajouter Revendeur',
            controller: function ($scope, $http, $stateParams, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');
                $('#msgBottom').hide();
                $('#LoaderdivBottom').hide();
                // add row
                $scope.remisesItems = [];
                $scope.adressesLivraisonRevendeur = [];
                $scope.revendeurInfo = { };

                // add row
                $scope.addItem = function () {
                    $scope.remisesItems.push(
                        {
                            id : null,
                            rate : null,
                            visible : true
                        })
                };
                $scope.utilisateurs = [];

                // add row
                $scope.addUser = function () {
                    $scope.utilisateurs.push(
                        {
                            nom_user : null,
                            prenom_user :null,
                            gsm_user : null,
                            login_user: null,
                            pass_user: null
                        })

                };
                $scope.removeUser = function (item) {
                    var index = $scope.utilisateurs.indexOf(item);
                    $scope.utilisateurs[index].visible = true;
                    //$scope.references.splice(index, 1);
                }
                // remove row
                $scope.removeRemise = function (item) {
                    var index = $scope.remisesItems.indexOf(item);
                    $scope.remisesItems[index].visible = false;
                    //$scope.remisesItems.splice(index, 1);
                }

                // add row
                $scope.addAddressItem = function () {
                    $scope.adressesLivraisonRevendeur.push(
                        {
                            id : null,
                            visible : true
                        })
                };
                // remove row
                $scope.removeAddressItem = function (item) {
                    console.log('item: '+ item);
                    var index = $scope.adressesLivraisonRevendeur.indexOf(item);
                    console.log('item: '+ item);
                    $scope.adressesLivraisonRevendeur[index].visible = false;
                }

                $scope.addRevendeur = function () {
                    $('#msgBottom').hide();
                    $('#LoaderdivBottom').show();
                    prepareUsers();
                     if($scope.postalMdl){
                        var postalcode=$scope.postalMdl.toString();
                    }
                    else  var postalcode=$scope.postalMdl;
                    $scope.reseller_data = {
                        company      :
                        { client_code  : $scope.client_code,
                          name         : $scope.revendeurInfo.name,
                        //zip_code : postalcode,
                          town         : $scope.revendeurInfo.town,
                          email        : $scope.revendeurInfo.email,
                          deactivated  : $scope.booleanToInteger($scope.deactivated)
                        },
                        discounts    : prepareDiscounts(),
                        delivery_addresses: prepareDeliveryAddresses(),
                        resellers    : $scope.users
                    };
                    var url = $scope.url+"resellerCompanies";
                    $http({
                        method: 'POST',
                        url: url,
                        data :  $.param($scope.reseller_data),
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#msgBottom').hide();
                        $('#LoaderdivBottom').hide();
                        if(response.status == 200)
                            window.location.replace('/#/utilisateurs/revendeurs');
                        else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_add_revendeur = $scope.getErrorMessage(response);
                    });
                }
                function prepareUsers() {

                    $scope.users = [];
                    for (var i = 0; i<$scope.utilisateurs.length; i++){
                        if(!$scope.utilisateurs[i].visible)
                            $scope.users.push({last_name : $scope.utilisateurs[i].nom_user,first_name : $scope.utilisateurs[i].prenom_user,mobile : $scope.utilisateurs[i].gsm_user,user:{login : $scope.utilisateurs[i].login_user,password: $scope.utilisateurs[i].pass_user}})
                    }
                }
                // 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;
                            //$scope.cltMdl  = $scope.clients[0].id;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {

                        $scope.response_error = response.data.message;
                    });
                }

                // Get remises
                function getRemises() {
                    var url = $scope.url+"discounts";
                    $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.remises = response.data;
                            $scope.remiseMdl = response.data.id;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {

                        $scope.response_error = response.data.message;
                    });
                }
                function prepareDiscounts() {
                    $scope.discounts_data = [];
                    for(var i = 0; i<$scope.remisesItems.length;i++) {
                        if($scope.remisesItems[i].visible) {
                            $scope.discounts_data.push(
                                {
                                    discount_id : parseInt($scope.remisesItems[i].id),
                                    rate        : $scope.remisesItems[i].rate.toString()
                                });
                        }
                    }
                    return $scope.discounts_data;
                }
                function prepareDeliveryAddresses() {
                    var preparedDeliveryAddresses = [];
                    for(var i = 0; i<$scope.adressesLivraisonRevendeur.length;i++) {
                        if($scope.adressesLivraisonRevendeur[i].visible) {
                            preparedDeliveryAddresses.push(
                                {
                                    id : parseInt($scope.adressesLivraisonRevendeur[i].id),
                                    deactivated : $scope.booleanToInteger($scope.adressesLivraisonRevendeur[i].deactivated),
                                    code : $scope.adressesLivraisonRevendeur[i].code,
                                    by_default : $scope.booleanToInteger($scope.adressesLivraisonRevendeur[i].by_default),
                                    first_name : $scope.adressesLivraisonRevendeur[i].first_name,
                                    last_name : $scope.adressesLivraisonRevendeur[i].last_name,
                                    phone : $scope.adressesLivraisonRevendeur[i].phone,
                                    address : $scope.adressesLivraisonRevendeur[i].address,
                                    address_followup : $scope.adressesLivraisonRevendeur[i].address_followup,
                                    town : $scope.adressesLivraisonRevendeur[i].town
                                });
                        }
                    }

                    return preparedDeliveryAddresses;
                }
                getClients();
                getRemises();
            }
        }).state('updateRevendeur', {
            url: '/updateRevendeur',
            params: {id : null},
            templateUrl    : 'app/pages/utilisateurs/revendeurs/updateRevendeur/updateRevendeur.html',
            title: 'Consultation Revendeurs',
            controller: function ($scope, $http, $stateParams, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');
                if($stateParams.id != null)
                    $scope.putCoockie('parmsID', $stateParams.id);

                $('#Loaderdiv').show();
                $('#divTable').hide();
                $('#msgBottom').hide();
                $('#LoaderdivBottom').hide();
                $('#msgError').hide();
                // add row
                $scope.remisesItems = [];
                $scope.adressesLivraisonRevendeur = [];
                $scope.selectedFavoris = [];

                // add row
                $scope.addItem = function () {
                    $scope.remisesItems.push(
                        {
                            id : null,
                            ERP_group_code : null,
                            rate : null,
                            visible : true
                        })
                };
                // remove row
                $scope.removeRemise = function (item) {
                    var index = $scope.remisesItems.indexOf(item);
                    $scope.remisesItems[index].visible = false;
                    //$scope.remisesItems.splice(index, 1);
                }

                // add row
                $scope.addAddressItem = function () {
                    $scope.adressesLivraisonRevendeur.push(
                        {
                            id : null,
                            visible : true
                        })
                };
                // remove row
                $scope.removeAddressItem = function (item) {
                    var index = $scope.adressesLivraisonRevendeur.indexOf(item);
                    $scope.adressesLivraisonRevendeur[index].visible = false;
                }

                function getRevendeur() {
                    var url = $scope.url+"resellerCompanies/"+$scope.getCoockie('parmsID');
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#Loaderdiv').hide();
                        $('#divTable').show();
                        $('#msgError').hide();
                        console.log('detail',response.data)
                        if(response.status == 200){
                            $scope.detailRevendeur = response.data;
                            $scope.deactivated = $scope.detailRevendeur.deactivated == 1;
                            $scope.idMdl=$scope.detailRevendeur.id;
                            var discounts = $scope.detailRevendeur.discounts;
                            for(var i =0 ; i<discounts.length; i++){
                                $scope.remisesItems.push(
                                    {
                                        id : discounts[i].id,
                                        ERP_group_code : discounts[i].id,
                                        rate :  discounts[i].pivot.rate,
                                        visible : true
                                    });
                            }
                            $scope.favorisRevendeur = $scope.detailRevendeur.favourites;
                            for(var i = 0; i < $scope.favorisRevendeur.length ; i++) {
                                $scope.selectedFavoris.push({
                                    id          : $scope.favorisRevendeur[i].id,
                                    product_id   : $scope.favorisRevendeur[i].product_id,
                                    isChecked : $scope.favorisRevendeur[i].deactivated == 0
                                });
                            }
                            var deliveryAddressses = $scope.detailRevendeur.delivery_addresses;
                            for(var i =0 ; i<deliveryAddressses.length; i++){
                                $scope.adressesLivraisonRevendeur.push(
                                    {
                                        id : deliveryAddressses[i].id,
                                        deactivated : deliveryAddressses[i].deactivated  == 1,
                                        code : deliveryAddressses[i].code,
                                        by_default : deliveryAddressses[i].by_default  == 1,
                                        first_name : deliveryAddressses[i].first_name,
                                        last_name : deliveryAddressses[i].last_name,
                                        phone : deliveryAddressses[i].phone,
                                        address : deliveryAddressses[i].address,
                                        address_followup : deliveryAddressses[i].address_followup,
                                        town : deliveryAddressses[i].town,
                                        visible : true
                                    });
                            }
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTable').hide();
                            $('#msgError').show();
                        }

                    }, function errorCallback(response) {

                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#divTable').hide();
                        $('#msgError').show();
                        $('#Loaderdiv').hide();
                    });
                }
                // Get remises
                function getRemises() {
                    var url = $scope.url+"discounts";
                    $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.remises = response.data;
                            $scope.remiseMdl = response.data.id;
                        } else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {

                        $scope.response_error = response.data.message;
                    });
                }
                getRevendeur();
                getRemises();

                $scope.updateRevendeur = function () {
                    $('#msgBottom').hide();
                    $('#LoaderdivBottom').show();
                    prepareDiscounts();

                    $scope.reseller_data_up = {
                        company: {
                            client_code: $scope.detailRevendeur.client.ERP_code,
                            name: $scope.detailRevendeur.name,
                            email: $scope.detailRevendeur.email,
                            town: $scope.detailRevendeur.town,
                            deactivated  : $scope.booleanToInteger($scope.detailRevendeur.deactivated)
                        },
                        discounts    : prepareDiscounts(),
                        favourites   : prepareFavoris(),
                        delivery_addresses: prepareDeliveryAddresses()
                    };
                    console.log('$scope.reseller_data_up',$scope.reseller_data_up)
                    var url = $scope.url+"resellerCompanies/"+$scope.getCoockie('parmsID');
                    $http({
                        method: 'PUT',
                        url: url,
                        data :  $.param($scope.reseller_data_up),
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#msgBottom').hide();
                        $('#LoaderdivBottom').hide();
                        if(response.status == 200)
                            window.location.replace('/#/utilisateurs/revendeurs');
                        else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_update_revendeur = $scope.getErrorMessage(response);
                    });
                }
                function prepareDiscounts() {
                    $scope.discounts_data = [];
                    for(var i = 0; i<$scope.remisesItems.length;i++) {
                        if($scope.remisesItems[i].visible) {
                            $scope.discounts_data.push(
                                {
                                    discount_id : parseInt($scope.remisesItems[i].id),
                                    rate        : $scope.remisesItems[i].rate.toString()
                                });
                        }
                    }
                    return $scope.discounts_data;
                }

                function prepareDeliveryAddresses() {
                    var preparedDeliveryAddresses = [];
                    for(var i = 0; i<$scope.adressesLivraisonRevendeur.length;i++) {
                        if($scope.adressesLivraisonRevendeur[i].visible) {
                            preparedDeliveryAddresses.push(
                                {
                                    id : parseInt($scope.adressesLivraisonRevendeur[i].id),
                                    deactivated : $scope.booleanToInteger($scope.adressesLivraisonRevendeur[i].deactivated),
                                    code : $scope.adressesLivraisonRevendeur[i].code,
                                    by_default : $scope.booleanToInteger($scope.adressesLivraisonRevendeur[i].by_default),
                                    first_name : $scope.adressesLivraisonRevendeur[i].first_name,
                                    last_name : $scope.adressesLivraisonRevendeur[i].last_name,
                                    phone : $scope.adressesLivraisonRevendeur[i].phone,
                                    address : $scope.adressesLivraisonRevendeur[i].address,
                                    address_followup : $scope.adressesLivraisonRevendeur[i].address_followup,
                                    town : $scope.adressesLivraisonRevendeur[i].town
                                });
                        }
                    }

                    return preparedDeliveryAddresses;
                }

                // prepare Favourites
                function prepareFavoris() {
                    $scope.preparedFavoris = [];
                    for(var i =0;i < $scope.selectedFavoris.length; i++) {
                        if( $scope.selectedFavoris[i].isChecked != null){
                            $scope.preparedFavoris.push({
                                id          : $scope.selectedFavoris[i].id,
                                cliend_id  : $scope.selectedFavoris[i].cliend_id,
                                product_id  : $scope.selectedFavoris[i].product_id,
                                deactivated  : $scope.selectedFavoris[i].isChecked? 0 : 1
                            });
                        }
                    }
                    return $scope.preparedFavoris;
                }
                // 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();

                $scope.checkDeactivated = function(val) {
                    $scope.detailRevendeur.deactivated = val? 1 : 0;
                }

                $scope.checkDeliveryAddressByDefaut= function(index, val) {
                    if (val == 1) {
                        var i = 0;
                        while (i<$scope.adressesLivraisonRevendeur.length) {
                            if (i != index)
                                $scope.adressesLivraisonRevendeur[i].by_default = false;
                            i++;
                        }
                    }
                }
            }
        }).state('users', {
            url: '/utilisateurs',
            params: {id : null},
            templateUrl: 'app/pages/utilisateurs/revendeurs/updateRevendeur/users/users.html',

            controller: function ($scope, $stateParams, $http, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');
                if($stateParams.id != null)
                    $scope.putCoockie('id', $stateParams.id);
                $('#Loaderdiv').show();
                $('#divTable').hide();
                $('#msgTop').hide();
                $('#msgError').hide();
                function getRevendeur() {
                    var url = $scope.url+"resellerCompanies/"+$scope.getCoockie('id');
                    $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) {
                            $('#divTable').show();
                            $('#msgError').hide();
                            $scope.detailRevendeurs = response.data.resellers;
                            $scope.companieId = response.data.id;
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTable').hide();
                            $('#msgError').show();
                        }
                    }, function errorCallback(response) {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#Loaderdiv').hide();
                        $('#divTable').hide();
                        $('#msgError').show();
                    });
                }
                getRevendeur();
                $scope.deactivateUser = function (id, val) {
                    $('#msgError').hide();
                    $scope.reseller_data_deactive = {

                        deactivated: val

                    };
                    var url = $scope.url+"resellers/"+id;
                    $http({
                        method: 'PUT',
                        url: url,
                        data :  $.param($scope.reseller_data_deactive),
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#msgBottom').hide();
                        $('#LoaderdivBottom').hide();
                        if(response.status == 200)
                            getRevendeur();
                        else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_add_revendeur = $scope.getErrorMessage(response);
                    });
                }

                $scope.deleteUser = function(id){
                    console.log("users",id)
                    var url = $scope.url+"resellers/"+id;
                    $http({
                        method: 'DELETE',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#Loaderdiv').hide();

                        if(response.status == 200) {
                            window.location.reload();
                            $('#divTable').show();
                            $('#msgError').hide();
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTable').hide();
                            $('#msgError').show();
                        }
                    }, function errorCallback(response) {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#Loaderdiv').hide();
                        $('#divTable').hide();
                        $('#msgError').show();
                    });
                }

            }

        }).state('addUserToCompanie', {
            url: '/addUserToCompanie',
            params: {idCompanie : null},
            templateUrl: 'app/pages/utilisateurs/revendeurs/updateRevendeur/users/addUserToCompanie.html',

            controller: function ($scope, $stateParams, $http, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');

                if($stateParams.idCompanie != null)
                    $scope.putCoockie('idCompanie', $stateParams.idCompanie);
                $('#Loaderdiv').show();
                $('#divTable').hide();
                $('#msgTop').hide();
                $('#msgError').hide();
                $scope.addUserToCompanie = function () {
                    $('#msgBottom').hide();
                    $('#LoaderdivBottom').show();

                    $scope.reseller_data = {
                        company_id: $scope.getCoockie('idCompanie'),
                        user: {
                        login: $scope.loginMdl,
                            password: $scope.passwordMdl
                    },
                    first_name: $scope.prenomMdl,
                        last_name: $scope.nameMdl,
                        mobile: $scope.mobileMdl,
                        price_visibility:$scope.booleanToInteger($scope.visiblePrice)
                    };
                    var url = $scope.url+"resellers";
                    $http({
                        method: 'POST',
                        url: url,
                        data :  $.param($scope.reseller_data),
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#msgBottom').hide();
                        $('#LoaderdivBottom').hide();
                        if(response.status == 200)
                            window.location.replace('/#/utilisateurs');
                        else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_add_revendeur = $scope.getErrorMessage(response);
                    });
                }
                $scope.checkVisible = function(val) {
                    $scope.visiblePrice = val ;
                }

            }

        }).state('updateUser', {
            url: '/updateUser',
            params: {idUser : null},
            templateUrl: 'app/pages/utilisateurs/revendeurs/updateRevendeur/users/updateUser.html',

            controller: function ($scope, $stateParams, $http, $state) {
                if(!$scope.isLogged())
                    window.location.replace('/#/login');

                if($stateParams.idUser != null)
                    $scope.putCoockie('idUser', $stateParams.idUser);
                $('#Loaderdiv').show();
                $('#divTable').hide();
                $('#msgTop').hide();
                $('#msgError').hide();
                function getUser() {
                    var url = $scope.url+"resellers/"+$scope.getCoockie('idUser');
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#Loaderdiv').hide();
                        $('#divTable').show();
                        $('#msgError').hide();
                        if(response.status == 200){
                            $scope.detailRevendeur = response.data;
                            $scope.nameMdl         = $scope.detailRevendeur.last_name ;
                            $scope.prenomMdl       = $scope.detailRevendeur.first_name ;
                            $scope.mobileMdl         = $scope.detailRevendeur.mobile ;
                            $scope.loginMdl        = $scope.detailRevendeur.user.email ;
                            $scope.passwordMdl        = $scope.detailRevendeur.user.password ;
                            //$scope.visiblePrice      =$scope.booleanToInteger(detailRevendeur.price_visibility);
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#divTable').hide();
                            $('#msgError').show();
                        }

                    }, function errorCallback(response) {

                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#divTable').hide();
                        $('#msgError').show();
                        $('#Loaderdiv').hide();
                    });
                }
                getUser();
                $scope.updateUser = function () {
                    $('#msgBottom').hide();
                    $('#LoaderdivBottom').show();

                    $scope.reseller_data = {
                        user: {
                            login: $scope.loginMdl,
                            password: $scope.passwordMdl
                        },
                        first_name: $scope.prenomMdl,
                        last_name: $scope.nameMdl,
                        mobile: $scope.mobileMdl,
                        price_visibility: $scope.booleanToInteger($scope.visiblePrice)
                    };
                    var url = $scope.url+"resellers/"+$scope.getCoockie('idUser');
                    $http({
                        method: 'PUT',
                        url: url,
                        data :  $.param($scope.reseller_data),
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#msgBottom').hide();
                        $('#LoaderdivBottom').hide();
                        if(response.status == 200)
                            window.location.replace('/#/utilisateurs');
                        else
                            $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_add_revendeur = $scope.getErrorMessage(response);
                    });
                }
                $scope.checkVisible = function(val) {
                    $scope.visiblePrice = val ;
                }
            }

        });
    }

})();
