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

(function () {
    'use strict';

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

    /** @ngInject */
    function routeConfig($stateProvider) {
        $stateProvider
            .state('commandes', {
                url: '/commandes',
                templateUrl: 'app/pages/commandes/commandes.html',
                title: 'Commandes & Retours',
                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.commands          = [];
                    $scope.totalCommands     = 0;
                    $scope.commandsPerPage   = 25;

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

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

                        });
                    }

                    // Get channels
                    function getChannels() {
                        var url = $scope.url+"channels";
                        $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.channels = response.data;
                            }

                        }, function errorCallback(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;
                                console.log("clients",$scope.clients)
                            }

                        }, function errorCallback(response) {

                        });
                    }
                      function getStatuses () {

                        var url = $scope.baseUrl+"/api/admin/v1_0/statuses";
                        $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.statuses = 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.";
                        });
                    }

                    function getCommandTypes() {

                        var url = $scope.baseUrl+"/api/admin/v1_0/commandTypes";
                        $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.commandTypes = response.data;
                                console.log('commandTypes : ', $scope.commandTypes);
                            }
                            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.";
                        });
                    }

                    getChannels();
                    getClients();
                    getStatuses ();
                    getCommandTypes();

                    function getParamsSearch() {

                        var paramsSearch = {};
                        var commandType   = {type_id        : $scope.commandTypeModel};
                        var numberCommand = {number         : $scope.codeModel};
                        var status        = {status_id      : $scope.stateModel};
                        var channel       = {channel_id     : $scope.canalMdl};
                        var name          = {customer_name  : $scope.nameMdl};
                        var codeClient    = {client_id      : $scope.codeClientMdl};
                        var codeCMD       = {ERP_code       : $scope.codeCmdMdl};
                        var dateStart     = {start          : $scope.simpleDateFormat($scope.startDateModel)};
                        var dateEnd       = {end            : $scope.simpleDateFormat($scope.endDateModel)};

                        if(!$scope.commandTypeModelCheckbox)
                            paramsSearch = angular.extend({},paramsSearch, commandType)
                        if(!$scope.codeModelBox)
                            paramsSearch = angular.extend({},paramsSearch, numberCommand)
                        if(!$scope.stateModelBox)
                            paramsSearch = angular.extend({},paramsSearch, status)
                        if(!$scope.canalMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, channel)
                        if(!$scope.nameMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, name)
                        if(!$scope.codeClientMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, codeClient)

                        if(!$scope.codeCmdMdlBox)
                            paramsSearch = angular.extend({},paramsSearch, codeCMD)

                        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.checkCommandType = function (val) {
                        $scope.commandTypeModel = val;

                    };
                    $scope.checkCommandTypeBox = function (val) {
                        $scope.commandTypeModelCheckbox = val;
                        console.log('commandTypeModelCheckbox', $scope.commandTypeModelCheckbox);
                        if($scope.commandTypeModelCheckbox==true) {
                            $('#commandTypeModel').val("");
                        }
                        console.log('commandTypeModel', $scope.commandTypeModel);
                    };

                    $scope.checkCode = function (val) {
                        $scope.codeModel = val;
                    };
                    $scope.checkCodeBox = function (val) {
                        $scope.codeModelBox = val;
                        if($scope.codeModelBox==true) $('#codeModel').val("");
                    };
                    $scope.checkCanal = function (val) {
                        $scope.canalMdl = val;

                    };
                    $scope.checkCanalBox = function (val) {
                        $scope.canalMdlBox = val;
                        if($scope.canalMdlBox==true) $('#canalMdl').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.checkCodeClientBox==true) $('#codeClientMdl').val("");
                    };
                    $scope.checkStatus = function (val) {
                        $scope.stateModel = val;
                    };
                    $scope.checkStatusBox = function (val) {
                        $scope.stateModelBox = val;
                        if($scope.stateModelBox==true) $('#stateModel').val("");
                    };
                    $scope.checkCodeCMD = function (val) {
                        $scope.codeCmdMdl = val;
                    };
                    $scope.checkCodeCMDBox = function (val) {
                        $scope.codeCmdMdlBox = val;
                        if($scope.codeCmdMdlBox==true) $('#codeCmdMdl').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('consultationCommand', {
            url: '/consultationCommand',
            params: {id : null},
            templateUrl: 'app/pages/commandes/consultationCommand/consultationCommand.html',
            title: 'Commande',
            controller: function ($scope, $stateParams, $http, $state) {
                if (!$scope.isLogged())
                    window.location.replace('/#/login');

                $('#msgError').hide();
                $('#divTable').hide();
                $('#Loaderdiv').show();
                if($stateParams.id != null)
                    $scope.putCoockie('parmsID', $stateParams.id);

                var url = $scope.url+"commands/"+$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) {
                        $('#divTable').show();
                        $('#msgError').hide();
                        $scope.commandDetail = response.data;
                        console.log("detail",$scope.commandDetail)
                        $scope.clientName = '';
                        $scope.employeeName = '';
                        if($scope.commandDetail.individual != null) {
                            $scope.clientName = $scope.commandDetail.individual.last_name+' '+$scope.commandDetail.individual.first_name;
                        } else if($scope.commandDetail.reseller != null ) {
                            $scope.clientName =$scope.commandDetail.reseller.company.name;
                            $scope.employeeName =$scope.commandDetail.reseller.last_name+' '+$scope.commandDetail.reseller.first_name;
                        }
                    } 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();

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

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

                $scope.stateModel = parseInt($scope.getCoockie('parmsStatus'));
                var url = $scope.url + "commands/" + $scope.getCoockie('parmsID');

                $scope.updateCommand = function () {

                    var data = {
                        status_id : $scope.stateModel
                    };
                    $http({
                        method: 'PUT',
                        url: url,
                        params : data,
                        data :  $.param(data),
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8",
                            "Authorization" : $scope.userSession()
                        }
                    }).then(function successCallback(response) {

                        if(response.status == 200) {
                            window.location.replace('/#/commandes');
                        } else
                            $scope.command_error = "Une erreur s'est produite, merci de réessayer.";

                    }, function errorCallback(response) {
                        $scope.command_error = "Une erreur s'est produite, merci de réessayer.";

                    });
                }
                $scope.checkStatus = function (val) {
                    $scope.stateModel = val;
                };
            }
            });

    }

})();
