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

(function () {
    'use strict';

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

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('ResellerCommunications', {
                url: '/resellerCommunications',
                templateUrl: 'app/pages/resellerCommunications/list.html',
                title: 'Communication Revendeur',
                sidebarMeta: {
                    icon: 'ion-grid',
                    order: 800,
                },
                controller: function ($scope, $stateParams, $http, $state) {
                    if(!$scope.isLogged())
                        window.location.replace('/#/login');

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

                    $scope.comms        = [];
                    $scope.totalComms   = 0;
                    $scope.commsPerPage = 25;

                    $scope.pagination = {
                        current: 1
                    };
                    $scope.pageChanged = function(newPage) {
                        $scope.searchComm(newPage);
                    };

                    // Send search
                    $scope.searchComm = function (pageNumber) {
                        $('#Loaderdiv').show();
                        $('#divTable').hide();
                        $('#divEmpty').hide();
                        $('#msgError').hide();
                        console.log("getParamsSearch",getParamsSearch())
                        var url = $scope.url+"resellerCommunications?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.comms = response.data.data;
                                $scope.totalComms = response.data.total;
                                if($scope.comms.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.comms ={};
                            $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 getParamsSearch() {

                        var paramsSearch = {};
                        var codeClient    = {client_id      : $scope.codeClientMdl};
                        var dateStart     = {start          : $scope.simpleDateFormat($scope.startDateModel)};
                        var dateEnd       = {end            : $scope.simpleDateFormat($scope.endDateModel)};

                        if(!$scope.codeClientMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, codeClient)

                        if(!$scope.periodModel) {
                            if($scope.simpleDateFormat($scope.startDateModel) != null)
                                paramsSearch = angular.extend({},paramsSearch, dateStart)
                            if($scope.simpleDateFormat($scope.endDateModel) != null)
                                paramsSearch = angular.extend({},paramsSearch, dateEnd)
                        }

                        return paramsSearch;
                    }

                    $scope.checkCodeClient = function (val) {
                        $scope.codeClientMdl = val;
                    };
                    $scope.checkCodeClientBox = function (val) {
                        $scope.codeClientMdlBox = val;
                        if($scope.checkCodeClientBox==true) $('#codeClientMdl').val("");
                    };
                    $scope.checkChangeDate = function (val) {
                        $scope.periodModel = val;
                        if($scope.periodModel==true)
                        {$('#startDateModel').val("");
                            $('#endDateModel').val("");
                        }
                    };
                    $scope.checkChangeDateBox = function (val) {
                        $scope.periodModelBox = val;
                    };

                    $scope.checkStart = function (val) {
                        $scope.startDateModel = val;
                        var today = $scope.startDateModel;
                        var dd = today.getDate();
                        var mm = today.getMonth()+1; //January is 0!
                        var yyyy = today.getFullYear();
                        if(dd<10){
                            dd='0'+dd
                        }
                        if(mm<10){
                            mm='0'+mm
                        }

                        today = yyyy+'-'+mm+'-'+dd;
                        document.getElementById("endDateModel").setAttribute("min",today)
                    };
                    $scope.checkEnd = function (val) {
                        $scope.endDateModel = val;
                        var today = $scope.endDateModel;
                        var dd = today.getDate();
                        var mm = today.getMonth()+1; //January is 0!
                        var yyyy = today.getFullYear();
                        if(dd<10){
                            dd='0'+dd
                        }
                        if(mm<10){
                            mm='0'+mm
                        }

                        today = yyyy+'-'+mm+'-'+dd;
                        document.getElementById("startDateModel").setAttribute("max",today)
                    };


                }

            }).state('consultationResellerCommunication', {
            url: '/consultationCommunicationRevendeur',
            params: {id : null},
            templateUrl: 'app/pages/resellerCommunications/consultation.html',
            title: 'Consultation Communication Revendeur',
            controller: function ($scope, $stateParams, $http, $state) {
                if (!$scope.isLogged())
                    window.location.replace('/#/login');
                if($stateParams.id != null)
                    $scope.putCoockie('parmsID', $stateParams.id);
                $('#msgError').hide();
                $('#divBody').hide();

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

                $http({
                    method: 'GET',
                    url: url,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        "Authorization" : $scope.userSession()
                    }
                }).then(function successCallback(response) {
                    $('#Loaderdiv').hide();
                    if(response.status == 200) {
                        $('#divBody').show();
                        $('#msgError').hide();
                        $scope.comm = response.data;
                        if($scope.comm.deactivated == 1) $scope.deactivatedModel = true;
                        else $scope.deactivatedModel = false;
                        $scope.startDate = response.data.start_date != null?  new Date(response.data.start_date) : null;
                        $scope.endDate = response.data.end_date!=null? new Date(response.data.end_date): null;
                    } else {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#msgError').show();
                        $('#divBody').hide();
                    }
                }, function errorCallback(response) {
                    $scope.error_response = $scope.getErrorMessage(response);
                    $('#msgError').show();
                    $('#divBody').hide();
                });

                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();

                $scope.checkDeactivatedMdl = function(val) {
                    $scope.deactivatedModel = val ;
                }
            }
            }).state('updateResellerCommunication', {
            url: '/updateResellerCommunication',
            params: {id : null},
            templateUrl: 'app/pages/resellerCommunications/update.html',
            title: 'Modification Communication Revendeur',
            controller: function ($scope, $stateParams, $http, $state) {
                $('#msgBottom').hide();
                $('#LoaderdivBottom').hide();
                $('#msgError').hide();
                $('#divBody').hide();

                if (!$scope.isLogged())
                    window.location.replace('/#/login');

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

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

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

                    var data = {
                        deactivated: $scope.deactivatedModel== true? 1 : 0,
                        client_id :  $scope.codeClient,
                        start_date:  $scope.startDateModel,
                        end_date:    $scope.endDateModel,
                        title:       $scope.comm.title,
                        corps:       $scope.comm.corps,
                    };
                    $http({
                        method: 'PUT',
                        url: url,
                        data: JSON.stringify(data),
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        if(response.status == 200) {
                            window.location.replace('/#/resellerCommunications');
                        } else {
                            $scope.error_response = "Une erreur s'est produite, merci de réessayer.";
                            $('#msgBottom').hide();
                            $('#LoaderdivBottom').hide();
                        }
                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_update_reseller_communication = $scope.getErrorMessage(response);
                    });
                }

                function getComm() {
                    $('#LoaderdivBottom').show();
                    $http({
                        method: 'GET',
                        url: url,
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        $('#Loaderdiv').hide();
                        if(response.status == 200) {
                            $('#divBody').show();
                            $('#msgBottom').hide();
                            $('#LoaderdivBottom').hide();
                            $scope.comm = response.data;
                            if($scope.comm.deactivated == 1) $scope.deactivatedModel = true;
                            $scope.codeClient = response.data.client_id;
                            $scope.startDateModel = response.data.start_date != null?  new Date(response.data.start_date) : null;
                            $scope.endDateModel = response.data.end_date!=null? new Date(response.data.end_date): null;
                            initDates();
                        } else {
                            $scope.error_response = $scope.getErrorMessage(response);
                            $('#msgError').show();
                            $('#divBody').hide();
                        }
                    }, function errorCallback(response) {
                        $scope.error_response = $scope.getErrorMessage(response);
                        $('#msgError').show();
                        $('#divBody').hide();
                    });
                }

                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) {

                    });
                }

                function initStart() {
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("startDateModel").setAttribute("min", today)
                }

                function initEnd() {
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("endDateModel").setAttribute("min", today)
                }

                function initDates(){
                    if ($scope.startDateModel)
                        $scope.checkStart($scope.startDateModel)
                    if ($scope.endDateModel)
                        $scope.checkEnd($scope.endDateModel);

                    if (!$scope.startDateModel)
                        initStart();
                    if (!$scope.endDateModel)
                        initEnd();
                }

                getComm();
                getClients();

                $scope.checkCodeClient = function (val) {
                    if (val == '')
                        $scope.codeClient = null;
                    else
                        $scope.codeClient = val;
                };

                $scope.checkStart = function (val) {
                    $scope.startDateModel = val;
                    var today = null;
                    if ($scope.startDateModel)
                       today = $scope.startDateModel;
                    else
                       today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("endDateModel").setAttribute("min", today)
                };

                $scope.checkEnd = function (val) {
                    $scope.endDateModel = val;
                    var today = null;
                    if ($scope.endDateModel)
                        today = $scope.endDateModel;
                    else
                        today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("startDateModel").setAttribute("max", today)
                };

                $scope.checkDeactivatedMdl = function(val) {
                    $scope.deactivatedModel = val ;
                }
            }
            }).state('addResellerCommunication', {
            url: '/addResellerCommunication',
            params: {},
            templateUrl: 'app/pages/resellerCommunications/add.html',
            title: 'Ajout Communication Revendeur',
            controller: function ($scope, $stateParams, $http, $state) {
                $('#msgBottom').hide();
                $('#LoaderdivBottom').hide();
                $('#msgError').hide();

                if (!$scope.isLogged())
                    window.location.replace('/#/login');

                $scope.startDateModel = null;
                $scope.endDateModel = null;

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

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

                    var data = {
                        deactivated: $scope.deactivatedModel== true? 1 : 0,
                        client_id : $scope.codeClient,
                        start_date: $scope.startDateModel,
                        end_date:   $scope.endDateModel,
                        title:      $scope.title,
                        corps:      $scope.corps,
                    };
                    $http({
                        method: 'POST',
                        url: url,
                        data: JSON.stringify(data),
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {
                        if(response.status == 200) {
                            window.location.replace('/#/resellerCommunications');
                        } else {
                            $scope.error_response = "Une erreur s'est produite, merci de réessayer.";
                            $('#msgBottom').hide();
                            $('#LoaderdivBottom').hide();
                        }
                    }, function errorCallback(response) {
                        $('#msgBottom').show();
                        $('#LoaderdivBottom').hide();
                        $scope.error_add_reseller_communication = $scope.getErrorMessage(response);
                    });
                }

                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;
                            initDates();
                        }

                    }, function errorCallback(response) {

                    });
                }


                function initStart() {
                    console.log('initStart')
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("startDateModel").setAttribute("min", today)
                }

                function initEnd() {
                    console.log('initEnd')
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("endDateModel").setAttribute("min", today)
                }

                function initDates(){
                    if ($scope.startDateModel)
                        $scope.checkStart($scope.startDateModel)
                    if ($scope.endDateModel)
                        $scope.checkEnd($scope.endDateModel);

                    if (!$scope.startDateModel)
                        initStart();
                    if (!$scope.endDateModel)
                        initEnd();
                }

                getClients();

                $scope.checkCodeClient = function (val) {
                    if (val == '')
                        $scope.codeClient = null;
                    else
                        $scope.codeClient = val;
                };

                $scope.checkStart = function (val) {
                    $scope.startDateModel = val;
                    var today = null;
                    if ($scope.startDateModel)
                        today = $scope.startDateModel;
                    else
                        today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("endDateModel").setAttribute("min", today)
                };

                $scope.checkEnd = function (val) {
                    $scope.endDateModel = val;
                    var today = null;
                    if ($scope.endDateModel)
                        today = $scope.endDateModel;
                    else
                        today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) {
                        dd = '0' + dd
                    }
                    if (mm < 10) {
                        mm = '0' + mm
                    }

                    today = yyyy + '-' + mm + '-' + dd;
                    document.getElementById("startDateModel").setAttribute("max", today)
                };

                $scope.checkDeactivatedMdl = function(val) {
                    $scope.deactivatedModel = val ;
                }
            }
        });

    }

})();
