﻿angular.module("app.importsControllers", [])

    .controller("importsAdvancedController", ["$scope", "$interval", "importAdvancedService", "serverFileService", "importDataService", "$filter", "localStorageService",
        function ($scope, $interval, importAdvancedService, serverFileService, importDataService, $filter, localStorageService) {

            document.title = "Import/Export Advanced";

            $scope.ajaxInProgress = false;

            $scope.entities = [
                { id: 1, name: "Customers", entitiesTypeId: 1 },
                { id: 2, name: "Vendors", entitiesTypeId: 2 },
                { id: 3, name: "Parts", entitiesTypeId: 3 },
                { id: 4, name: "Units", entitiesTypeId: 27 },
                { id: 5, name: "Parts Class", entitiesTypeId: 22 },
                { id: 6, name: "Parts Families", entitiesTypeId: 23 },
                { id: 7, name: "Parts Brands", entitiesTypeId: 21 },
                { id: 8, name: "Parts Groups", entitiesTypeId: 20 },
                { id: 9, name: "Customer Contacts", entitiesTypeId: 5 },
                { id: 10, name: "Vendor Contacts", entitiesTypeId: 6 },
                { id: 11, name: "Part Alias (Vendor)", entitiesTypeId: 33 },
                { id: 12, name: "Part Alias (Customer)", entitiesTypeId: 109 },
                { id: 13, name: "Customer Sites", entitiesTypeId: 132 },
                { id: 14, name: "GL Chart Of Accounts", entitiesTypeId: 10 },
                { id: 15, name: "Accounts Families", entitiesTypeId: 26 },
                { id: 16, name: "Balance Sheet", entitiesTypeId: 113 },
                { id: 17, name: "Balance Sheet Heading", entitiesTypeId: 112 },
                { id: 18, name: "Trial Balance", entitiesTypeId: 111 },
                { id: 19, name: "Trial Balance Heading", entitiesTypeId: 110 },
                { id: 20, name: "Cash Flow", entitiesTypeId: 114 },
                { id: 21, name: "Account Group", entitiesTypeId: 114 },
                { id: 22, name: "Shipments", entitiesTypeId: 52 },
                { id: 23, name: "Sales Representatives", entitiesTypeId: 17 },
                { id: 24, name: "Tax Components", entitiesTypeId: 42 },
                { id: 25, name: "Taxes", entitiesTypeId: 41 },
                { id: 26, name: "Payments Terms", entitiesTypeId: 14 },
                { id: 27, name: "User Groups", entitiesTypeId: 65 },
                { id: 28, name: "Users", entitiesTypeId: 64 },
                { id: 29, name: "Banks", entitiesTypeId: 7 },
                { id: 30, name: "Cashier", entitiesTypeId: 9 },
                { id: 31, name: "Branches", entitiesTypeId: 51 },
                { id: 32, name: "Warehouses", entitiesTypeId: 12 },
                { id: 33, name: "Warehouse Bins", entitiesTypeId: null },
                { id: 34, name: "Default Accounts", entitiesTypeId: null },
                { id: 35, name: "Apparel", entitiesTypeId: 55 },
                { id: 36, name: "Parts Kits", entitiesTypeId: 55 },
                { id: 37, name: "Parts Barcode", entitiesTypeId: null },
                { id: 38, name: "Customer Special Prices", entitiesTypeId: null }
            ];

            $scope.entitySelected = $scope.entities[0];
            $scope.dataToimportSel = {
                entitySel: 1,
                file: '',
                entityFields: []
            };

            $scope.resultsImport;

            $scope.loadServices = function () {
                $scope.initializeTabs();

            };

            $scope.initializeTabs = function () {
                var intervalTabs = $interval(function () {
                    if ($("#formTab_detail_custom").length > 0) {
                        $("#formTab_detail_custom").tabs();
                        $interval.cancel(intervalTabs);
                    }
                }, 100);
            };

            $scope.downloadData = function (exportData) {
                $scope.ajaxInProgress = true;

                importAdvancedService.downloadData($scope.entitySelected, exportData).then(function (results) {
                    $scope.ajaxInProgress = false;
                    if (!results.data.error) {
                        serverFileService.serveFileBlob("temp", results.data.data.filePath).then(function (resultsFd) {
                            var blob = new Blob([resultsFd.data], { type: "application/octet-stream" });
                            saveAs(blob, results.data.data.name);
                        });
                    } else {
                        $scope.showMessageG("Information", results.data.description + "...", results.data.errorValue);
                    }
                });
            };

            $scope.updEntity = function (e) {

                if ($scope.entitySelected.id != $scope.dataToimportSel.entitySel) {
                    $scope.entitySelected = {};
                    $scope.dataToimportSel = {
                        entitySel: $scope.dataToimportSel.entitySel,
                        file: '',
                        fileinServer: '',
                        entityFields: [],
                        fileCols: [],
                    };
                    $scope.resultsImport = {};
                }

                if (typeof ($scope.dataToimportSel.entitySel) != 'undefined') {
                    $scope.entitySelected = $filter('filter')($scope.entities, { id: $scope.dataToimportSel.entitySel })[0];
                }
                else {
                    $scope.entitySelected = $scope.entities[0];
                }
            };

            $scope.upload = function (ind, element) {
                $scope.ajaxInProgress = true;
                var data = new FormData();
                var files = element[0].files;
                if (files.length > 0) {
                    data.append("UploadedImage", files[0]);
                    $scope.dataToimportSel.file = files[0].name;
                    importDataService.uploadFile(data).then(function (results) {
                        $scope.ajaxInProgress = false;
                        $scope.dataToimportSel.fileinServer = results.data;
                        setTimeout(function () {
                            $scope.$apply();
                        }, 200);
                        $scope.getColumnsMap();
                    });
                    $('[data-upload-file]')[0].value = "";
                }
            };

            $scope.getColumnsMap = function () {
                $scope.ajaxInProgressCols = true;
                importAdvancedService.getPreviewColumns($scope.entitySelected, $scope.dataToimportSel.fileinServer).then(function (results) {
                    if (!results.data.error) {
                        $scope.dataToimportSel.fileCols = results.data.data.fileCols;
                        $scope.dataToimportSel.entityFields = results.data.data.entityFields;
                        $scope.initializeMapColumns();
                    } else {
                        $scope.showMessageG("Information", results.data.description + "...", results.data.errorValue);
                    }
                    $scope.ajaxInProgressCols = false;
                });
            };

            $scope.initializeMapColumns = function () {
                for (var i = 0; i < $scope.dataToimportSel.entityFields.length; i++) {
                    var existInFile = $filter("filter")($scope.dataToimportSel.fileCols, { name: $scope.dataToimportSel.entityFields[i].name }, true);
                    if (existInFile.length > 0) {
                        $scope.dataToimportSel.entityFields[i].nameMap = existInFile[0];
                    } else {
                        var noImport = $filter("filter")($scope.dataToimportSel.fileCols, { exclude: true });
                        if (noImport.length > 0) {
                            $scope.dataToimportSel.entityFields[i].nameMap = noImport[0];
                        }
                    }
                }
            };

            $scope.importData = function () {
                $scope.ajaxInProgress = true;

                $scope.resultsImport = [];
                $("#importExportAdvancedProgress").html("Import in progress, please wait!");
                $("#processingFinalCogs").html("");

                $("#formTab_detail_custom").tabs("option", "active", 3);

                var authData = localStorageService.get('authorizationData');
                $scope.dataToimportSel.connectionId = $.connection.hub.id;
                $scope.dataToimportSel.access_token = authData.userData.access_token;

                importAdvancedService.importData($scope.dataToimportSel).then(function (results) {

                    if (results.data.error) {
                        $scope.showMessageG("Information", results.data.description + "...", results.data.errorValue);
                    }

                    if (!results.data.error) {
                        $scope.resultsImport = results.data;
                    } else {
                        $("#importExportAdvancedProgress").html("");
                        $("#processingFinalCogs").html("");
                    }

                    $scope.ajaxInProgress = false;
                });
            };

            $scope.$on('importExportAdvancedProgress', function (event, args) {
                var textHtml = "";

                if (args.entityTypeId == $scope.entitySelected.id) {
                    textHtml = "Processing " + args.countDoc + " of " + args.total + " " + args.typeDoc + "!";

                    if (args.userConn.connectionId == $.connection.hub.id) {
                        $("#importExportAdvancedProgress").html(textHtml);
                    }
                    else if (args.userConn.connectionId != $.connection.hub.id) {
                        var textFinal = args.userConn.Name + " " + args.userConn.LastName + " is processing Import/Export. </br>" + textHtml + "</br> Please wait until the process is done.";
                        $("#processingFinalCogs").html(textFinal);
                    }
                }

                if (args.countDoc == args.total || args.entityTypeId != $scope.entitySelected.id) {
                    $("#importExportAdvancedProgress").html("");
                    $("#processingFinalCogs").html("");
                }

            });

            $scope.loadServices();

        }
    ])

    ;