(function () {
    global.dashModule
        .controller('validateQuestionnaireCtrl', ['$scope', '$', '$http', '$translate', 'Upload', 'utilsService', validateQuestionnaireCtrl])
        .directive('validateQuestionnaire', [validateQuestionnaireDirective]);

    function validateQuestionnaireDirective() {
        return {
            restrict: 'E',
            templateUrl: 'orders/html/validateQuestionnaireTemplate'
        };
    }

    function validateQuestionnaireCtrl($scope, $, $http, $translate, Upload, utilsService) {
        $scope.customerDocuments = [];
        $scope.getDocumentsAndQuestionnaireComments = getDocumentsAndQuestionnaireComments;
        $scope.getValidationStatus = getValidationStatus;
        $scope.validateQuestionaire = validateQuestionaire;
        $scope.uploadFile = uploadFile;
        $scope.needsUplaod = needsUplaod;
        $scope.isQuestionaireInvalid = {};
        $scope.isValidationDialogVisible = {
            validated : {},
            invalid : {}
        };
        $scope.showHideValidationDialog = showHideValidationDialog;
        $scope.showInvalidTextbox = showInvalidTextbox;
        $scope.waitingResponseFromCustomer = {};
        $scope.getInvalidReasonsHeader = getInvalidReasonsHeader;
        $scope.questionnaireCommentsExist = false;
        const step = $scope.$parent.step;
        const idOrder = step.idOrder;
        const idProcessStep = step.idProcessStep;
        const stepInfo = {
            idOrder,
            idProcess: step.idProcess
        };

        function getDocumentsAndQuestionnaireComments() {
            getCustomerDocuments();
            getQuestionnaireComments();
        }

        function getCustomerDocuments() {
            const params = $.param({
                idOrder,
                documentType: 'orderQuestionaire'
            });

            $http({
                method: 'POST',
                data: params,
                url: 'v2/orders/api/getOrderDocumentsPerType'
            }).then(setCustomerDocuments, utilsService.onHttpError);
        }

        function showHideValidationDialog(fctParams) {
            if(!$scope.waitingResponseFromCustomer[fctParams.idDocument]) {
                $scope.$evalAsync(() => {
                    $scope.isValidationDialogVisible[fctParams.validationStatus][fctParams.idDocument] = !$scope.isValidationDialogVisible[fctParams.validationStatus][fctParams.idDocument];
                });
            }
        }

        function checkIfAllValid() {
            let allValid = true;
            Object.keys($scope.customerDocuments).forEach(key => {
                const packageDocuments = $scope.customerDocuments[key];
                packageDocuments.forEach((doc) => {
                    if (doc.validation !== 'validated') {
                        allValid = false;
                    }
                    $scope.waitingResponseFromCustomer[doc.idDocument] = doc.validation !== 'not-validated';
                });
            });

            stepInfo.isNextButtonDisabled = !allValid;
            utilsService.executeRegisteredFunction('isNextBtnDisabled', stepInfo);
        }

        function setCustomerDocuments(response) {
            if (response.data && response.data.documents) {
                $scope.customerDocuments = response.data.documents;
                checkIfAllValid();
            }
        }

        function getValidationStatus(status, documentValidation) {
            return status === documentValidation;
        }

        function validateQuestionaire(fctParams) {
            const params = $.param({
                idOrder,
                idPackage: fctParams.idPackage,
                idDocument: fctParams.idDocument,
                idProcessStep,
                validationStatus: fctParams.validationStatus,
                invalidQuestionaireReason: $scope.invalidQuestionaireReason
            });

            if (!$scope.waitingResponseFromCustomer[fctParams.idDocument]) {
                $http({
                    method: 'POST',
                    data: params,
                    url: 'orders/api/validateQuestionaire'
                }).then(displayMessage, utilsService.onHttpError);
            }
        }

        function displayMessage(response) {
            if (typeof response.data.messages !== 'undefined') {
                response.data.messages.forEach((messageObj) => {
                    const translatedMessage = $translate.instant('orders.messages.' + messageObj.message);
                    utilsService.displayMessage(messageObj.code, translatedMessage);

                    if (messageObj.code === 'success') {
                        $scope.invalidQuestionaireReason = '';
                        $scope.isQuestionaireInvalid = {};
                        getDocumentsAndQuestionnaireComments();
                    }

                    if (messageObj.message === 'REASON_EMPTY') {
                        $('#invalid-questionaire-comment').focus();
                    }
                });
            }
        }

        function needsUplaod(validation) {
            return validation === 'invalid';
        }

        function uploadFile(file, idDocument, idPackage) {
            Upload.upload({
                url: 'orders/api/reUploadQuestionaire',
                method: 'POST',
                file: file,
                data: {
                    idPackage,
                    idOrder,
                    idDocument
                }
            }).then(displayMessage, utilsService.onHttpError);
        }

        function showInvalidTextbox(idDocument) {
            $scope.isQuestionaireInvalid[idDocument] = (!$scope.isQuestionaireInvalid[idDocument] && !$scope.waitingResponseFromCustomer[idDocument]);
        }

        function getQuestionnaireComments() {
            const params = $.param({
                idOrder,
                idProcessStep,
                commentType: 'invalidQuestionnaireComment'
            });

            $http({
                method: 'POST',
                url: 'v2/orders/api/getCommentsByType',
                data: params
            }).then(setQuestionnaireComments, utilsService.onHttpError);
        }

        function setQuestionnaireComments(response) {
            if (typeof response.data !== 'undefined') {
                if (response.data.messages) {
                    displayMessage(response);
                }
                $scope.invalidQuestionaireComments = response.data;
                $scope.questionnaireCommentsExist = $scope.invalidQuestionaireComments.length > 0;
            }
        }

        function getInvalidReasonsHeader() {
            return $translate.instant('orders.tables.extra.INVALID_REASONS');
        }
    }
})();
