var app = angular.module('main', ['ngRoute']);
/* ------------------
    Routes
--------------------*/
app.config(function($routeProvider) {
  $routeProvider.when('/', {
    resolve: {
      check: function($location, user) {
        $location.path('/dashboard');
      }
    },
  }).when('/logout', {
    resolve: {
      deadResolve: function($location, user) {
        user.clearData();
        $location.path('/');
      }
    }
  }).when('/login', {
    resolve: {
      check: function($http, $location, user) {
        $http.get("../../../particuliers/api/admin/check").then(function(response) {
          if (response.data != 1) {
            $location.path('/register');
          }
        });
      }
    },
    templateUrl: './pages/login.html',
    controller: 'loginCtrl'
  }).when('/register', {
    resolve: {
      check: function($http, $location, user) {
        $http.get("../../../particuliers/api/admin/check").then(function(response) {
          if (response.data == 1) {
            $location.path('/login');
          }
        });
      }
    },
    templateUrl: './pages/register.html',
    controller: 'loginCtrl'
  }).when('/forgotpassword', {
    templateUrl: './pages/forgot-password.html',
    controller: 'loginCtrl'
  }).when('/dashboard', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/dashboard.html',
    controller: 'dashboardCtrl'
  }).when('/clients', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/clients.html',
    controller: 'clientsCtrl',
  }).when('/client/add', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/client-add.html',
    controller: 'clientsCtrl',
  }).when('/client/edit/:clientId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/client-edit.html',
    controller: 'clientsCtrl',
  }).when('/client/delete/:clientId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/client-delete.html',
    controller: 'clientsCtrl',
  }).when('/providers', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/providers.html',
    controller: 'providersCtrl',
  }).when('/provider/add', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/provider-add.html',
    controller: 'providersCtrl',
  }).when('/provider/edit/:providerId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/provider-edit.html',
    controller: 'providersCtrl',
  }).when('/provider/delete/:providerId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/provider-delete.html',
    controller: 'providersCtrl',
  }).when('/products', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/products.html',
    controller: 'productsCtrl',
  }).when('/stocks', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/stocks.html',
    controller: 'stocksCtrl',
  }).when('/product/add', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/product-add.html',
    controller: 'productsCtrl',
  }).when('/product/edit/:productId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/product-edit.html',
    controller: 'productsCtrl',
  }).when('/product/delete/:productId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/product-delete.html',
    controller: 'productsCtrl',
  }).when('/product/:productId/prices', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/prices.html',
    controller: 'pricesCtrl',
  }).when('/product/:productId/customs', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/customs.html',
    controller: 'customsCtrl',
  }).when('/orders', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/orders.html',
    controller: 'ordersCtrl',
  }).when('/orders/exports', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/export.html',
    controller: 'ordersCtrl',
  }).when('/order/:orderId', {
    resolve: {
      check: function($location, user) {
        if (!user.isUserLoggedIn()) {
          $location.path('/login');
        }
      }
    },
    templateUrl: './pages/order.html',
    controller: 'ordersCtrl',
  }).otherwise({
    resolve: {
      deadResolve: function($location) {
        $location.path('/404');
      }
    },
    templateUrl: './pages/404.html',
  })
});
app.service('user', function() {
  var id;
  var username;
  var loggedin = false;
  this.isUserLoggedIn = function() {
    if (!!localStorage.getItem('login')) {
      loggedin = true;
      var data = JSON.parse(localStorage.getItem('login'));
      username = data.username;
      id = data.id;
    }
    return loggedin;
  };
  this.saveData = function(data) {
    id = data.id;
    username = data.username;
    loggedin = true;
    localStorage.setItem('login', JSON.stringify({
      id: id,
      username: username
    }));
  };
  this.clearData = function() {
    localStorage.removeItem('login');
    id = "";
    username = "";
    loggedin = false;
  }
})
app.controller('initCtrl', function() {
  var init = function() {
    var $shadow_film = $('.shadow-film'),
      $mobile_menu_handler = $('.mobile-menu-handler'),
      $mobile_menu = $('#mobile-menu'),
      $side_list_handler = $('.dropdown.interactive'),
      $mobile_account_options_handler = $('.mobile-account-options-handler'),
      $account_options_menu = $('#account-options-menu'),
      $db_sidemenu_handler = $('.db-side-menu-handler'),
      $dashboard_options_menu = $('#dashboard-options-menu');
    $mobile_menu_handler.on('click', {
      id: '#mobile-menu'
    }, showSideMenu);
    $mobile_menu.children('.svg-plus').on('click', {
      id: '#mobile-menu'
    }, showSideMenu);
    $mobile_account_options_handler.on('click', {
      id: '#account-options-menu'
    }, showSideMenu);
    $account_options_menu.children('.svg-plus').on('click', {
      id: '#account-options-menu'
    }, showSideMenu);
    $db_sidemenu_handler.on('click', {
      id: '#dashboard-options-menu'
    }, showSideMenu);
    $dashboard_options_menu.children('.svg-plus').on('click', {
      id: '#dashboard-options-menu'
    }, showSideMenu);

    function showSideMenu(e) {
      var $menu = $(e.data.id);
      toggleVisibility($menu);
      toggleVisibility($shadow_film);
    }

    function toggleVisibility(togglableItem) {
      if (togglableItem.hasClass('closed')) {
        togglableItem.removeClass('closed').addClass('open');
      } else {
        togglableItem.removeClass('open').addClass('closed');
      }
    }
    $side_list_handler.children('.dropdown-item.interactive').on('click', toggleInnerMenu).children('a').click(function(e) {
      e.preventDefault();
    });

    function toggleInnerMenu(e) {
      var $this = $(this);
      $this.toggleClass('active').children('.inner-dropdown').slideToggle(600);
    }
  };
  init();
});
/* ------------------
    Login
--------------------*/
app.controller('loginCtrl', function($scope, $http, $location, user) {
  if (localStorage.getItem('login')) {
    $scope.user = JSON.parse(localStorage.getItem('login'));
  }
  $scope.reset = function() {
    if ($scope.resetForm.$valid) {
      var email = $scope.email;
      $http({
        url: '../../../particuliers/api/admin/reset',
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "email": email
        }
      }).then(function(response) {
        if (response.data.notice) {
          $scope.alertError = response.data.notice.text;
        } else {
          $scope.alertError = response.data.error.text;
        }
      })
    }
  }
  $scope.login = function() {
    if ($scope.loginForm.$valid) {
      var username = $scope.username;
      var password = $scope.password;
      $http({
        url: '../../../particuliers/api/admin/login',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "username": username,
          "password": password
        }
      }).then(function(response) {
        if (response.data.username) {
          user.saveData(response.data);
          $location.path('/');
        } else if (response.data.notice) {
          $scope.alertError = response.data.notice.text;
        } else {
          $scope.alertError = response.data.error.text;
        }
      })
    }
  }
  $scope.register = function() {
    if ($scope.registerForm.$valid) {
      var username = $scope.username;
      var email = $scope.email;
      var password = $scope.password;
      $http({
        url: '../../../particuliers/api/admin/add',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "username": username,
          "email": email,
          "password": password
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/login');
        } else {
          $scope.alertError = response.data.error.text;
        }
      })
    }
  }
});
/* ------------------
    Dashboard
--------------------*/
app.controller('dashboardCtrl', function($scope, $http, user) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  $http.get("../../../particuliers/api/dashboard").then(function(response) {
    $scope.stats = response.data;
  });
});
/* ------------------
    Client
--------------------*/
app.controller('clientsCtrl', function($scope, $http, user, $location, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  $http.get("../../../particuliers/api/clients").then(function(response) {
    $scope.clients = response.data;
    $scope.currentPage = 0;
    $scope.pageSize = 5;
    $scope.numberOfPages = function() {
      return Math.ceil($scope.clients.length / $scope.pageSize);
    }
  });
  if ($routeParams.clientId) {
    var clientId = $routeParams.clientId
    $http.get("../../../particuliers/api/client/" + clientId).then(function(response) {
      $scope.client = response.data;
      $scope.username = $scope.client.username;
      $scope.companyName = $scope.client.companyName;
      $scope.email = $scope.client.email;
      $scope.phone = $scope.client.phone;
      $scope.street = $scope.client.street;
      $scope.city = $scope.client.city;
      $scope.postalCode = $scope.client.postalCode;
      $scope.country = $scope.client.country;
    });
  }
  $scope.addClient = function() {
    if ($scope.addForm.$valid) {
      var username = $scope.username;
      var password = $scope.password;
      var companyName = $scope.companyName;
      var email = $scope.email;
      var phone = $scope.phone;
      var street = $scope.street;
      var postalCode = $scope.postalCode;
      var city = $scope.city;
      var country = $scope.country;
      $http({
        url: '../../../particuliers/api/client/add',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "username": username,
          "password": password,
          "companyName": companyName,
          "email": email,
          "phone": phone,
          "street": street,
          "postalCode": postalCode,
          "city": city,
          "country": country
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/clients');
        } else {
          $scope.addAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.activateClient = function(clientId) {
      $http({
        url: '../../../particuliers/api/client/activate/' + clientId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isActive": 1
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.clients.findIndex(item => item.clientId === clientId);
			$scope.clients[index].isActive = 1;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.desactivateClient = function(clientId) {
      $http({
        url: '../../../particuliers/api/client/activate/' + clientId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isActive": 0
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.clients.findIndex(item => item.clientId === clientId);
			$scope.clients[index].isActive = 0;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.editClient = function() {
    if ($scope.editForm.$valid) {
      var username = $scope.username;
      var companyName = $scope.companyName;
      var email = $scope.email;
      var phone = $scope.phone;
      var street = $scope.street;
      var postalCode = $scope.postalCode;
      var city = $scope.city;
      var country = $scope.country;
      $http({
        url: '../../../particuliers/api/client/update/' + clientId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "username": username,
          "companyName": companyName,
          "email": email,
          "phone": phone,
          "street": street,
          "postalCode": postalCode,
          "city": city,
          "country": country
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/clients');
        } else {
          $scope.editAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.deleteClient = function() {
    $http({
      url: '../../../particuliers/api/client/delete/' + clientId,
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(function(response) {
      if (response.data.notice) {
        $location.path('/clients');
      } else {
        $scope.deleteAlertError = response.data.error.text;
      }
    })
  }
});
/* ------------------
    Provider
--------------------*/
app.controller('providersCtrl', function($scope, $http, user, $location, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  $http.get("../../../particuliers/api/providers").then(function(response) {
    $scope.providers = response.data;
    $scope.currentPage = 0;
    $scope.pageSize = 5;
    $scope.numberOfPages = function() {
      return Math.ceil($scope.providers.length / $scope.pageSize);
    }
  });
  if ($routeParams.providerId) {
    var providerId = $routeParams.providerId
    $http.get("../../../particuliers/api/provider/" + providerId).then(function(response) {
      $scope.provider = response.data;
      $scope.name = $scope.provider.name;
      $scope.city = $scope.provider.city;
      $scope.country = $scope.provider.country;
    });
  }
  $scope.addProvider = function() {
    if ($scope.addForm.$valid) {
      var name = $scope.name;
      var city = $scope.city;
      var country = $scope.country;
      $http({
        url: '../../../particuliers/api/provider/add',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "name": name,
          "city": city,
          "country": country
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/providers');
        } else {
          $scope.addAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.editProvider = function() {
    if ($scope.editForm.$valid) {
      var name = $scope.name;
      var city = $scope.city;
      var country = $scope.country;
      $http({
        url: '../../../particuliers/api/provider/update/' + providerId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "name": name,
          "city": city,
          "country": country
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/providers');
        } else {
          $scope.editAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.deleteProvider = function() {
    $http({
      url: '../../../particuliers/api/provider/delete/' + providerId,
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(function(response) {
      if (response.data.notice) {
        $location.path('/providers');
      } else {
        $scope.deleteAlertError = response.data.error.text;
      }
    })
  }
});
/* ------------------
    Stock
--------------------*/
app.controller('stocksCtrl', function($scope, $http, user, $location, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
	$http.get("../../../particuliers/api/stocks").then(function(response) {
		$scope.stocks = response.data;
	});
});
/* ------------------
    Product
--------------------*/
app.controller('productsCtrl', function($scope, $http, user, $location, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
	var productId = $routeParams.productId;
  if ($routeParams.productId) {
		$http.get("../../../particuliers/api/providers").then(function(response) {
		  $scope.providers = response.data;
		  $http.get("../../../particuliers/api/product/" + productId).then(function(response) {
		    $scope.product = response.data;
				var index = $scope.providers.findIndex(item => item.providerId === $scope.product.providerId);
		    $scope.code = $scope.product.code;
		    $scope.designation = $scope.product.designation;
		    $scope.description = $scope.product.description;
		    $scope.category = $scope.product.category;
		    $scope.price = parseFloat($scope.product.price);
				$scope.tags = $scope.product.tags;
				$scope.provider = $scope.providers[index];
		  });
		});
  }else{
		$http.get("../../../particuliers/api/providers").then(function(response) {
		  $scope.providers = response.data;
		});
		$http.get("../../../particuliers/api/products").then(function(response) {
		  $scope.products = response.data;
		  $scope.currentPage = 0;
		  $scope.pageSize = 5;
		  $scope.numberOfPages = function() {
		    return Math.ceil($scope.products.length / $scope.pageSize);
		  }
		});
	}
  $scope.addProduct = function() {
    if ($scope.addForm.$valid) {
      var code = $scope.code;
      var designation = $scope.designation;
      var description = $scope.description;
      var category = $scope.category;
      var price = $scope.price;
      var providerId = $scope.provider.providerId;
      var tags = $scope.tags;
      $http({
        url: '../../../particuliers/api/product/add',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "code": code,
          "designation": designation,
          "description": description,
          "category": category,
          "price": price,
          "providerId": providerId,
		  "tags": tags
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/products');
        } else {
          $scope.addAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.editProduct = function() {
    if ($scope.editForm.$valid) {
      var code = $scope.code;
      var designation = $scope.designation;
      var description = $scope.description;
      var category = $scope.category;
      var price = $scope.price;
      var providerId = $scope.provider.providerId;
      var tags = $scope.tags;
      $http({
        url: '../../../particuliers/api/product/update/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "code": code,
          "designation": designation,
          "description": description,
          "category": category,
          "price": price,
          "providerId": providerId,
		  "tags": tags
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/products');
        } else {
          $scope.editAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.enableProduct = function(productId) {
      $http({
        url: '../../../particuliers/api/product/activate/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isActive": 1
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.products.findIndex(item => item.productId === productId);
			$scope.products[index].isActive = 1;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.disableProduct = function(productId) {
      $http({
        url: '../../../particuliers/api/product/activate/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isActive": 0
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.products.findIndex(item => item.productId === productId);
			$scope.products[index].isActive = 0;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.featuredProduct = function(productId) {
      $http({
        url: '../../../particuliers/api/product/featured/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isFeatured": 1
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.products.findIndex(item => item.productId === productId);
			$scope.products[index].isFeatured = 1;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.disfeaturedProduct = function(productId) {
      $http({
        url: '../../../particuliers/api/product/featured/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "isFeatured": 0
        }
      }).then(function(response) {
        if (response.data.notice) {
			var index = $scope.products.findIndex(item => item.productId === productId);
			$scope.products[index].isFeatured = 0;
        } else {
          console.log(response.data.error.text);
        }
      })
  }
  $scope.deleteProduct = function() {
    $http({
      url: '../../../particuliers/api/product/delete/' + productId,
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(function(response) {
      if (response.data.notice) {
        $location.path('/products');
      } else {
        $scope.deleteAlertError = response.data.error.text;
      }
    })
  }
});
/* ------------------
    Price
--------------------*/
app.controller('pricesCtrl', function($scope, $http, user, $location, $routeParams, $route) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  var productId = $routeParams.productId
  $http.get("../../../particuliers/api/prices/" + productId).then(function(response) {
    $scope.prices = response.data;
  });
  $http.get("../../../particuliers/api/clients").then(function(response) {
    $scope.clients = response.data;
    $scope.client = $scope.clients[0];
    $scope.getCompanyName = function(clientId) {
      var index = $scope.clients.findIndex(item => item.clientId === clientId);
      return $scope.clients[index].companyName;
    }
  });
  $scope.addPrice = function() {
    if ($scope.addForm.$valid) {
      var clientId = $scope.client.clientId;
      var specialPrice = $scope.specialPrice;
      $http({
        url: '../../../particuliers/api/price/add',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "productId": productId,
          "clientId": clientId,
          "specialPrice": specialPrice
        }
      }).then(function(response) {
        if (response.data.notice) {
          $route.reload();
        } else {
          $scope.addAlertError = response.data.error.text;
        }
      })
    }
  }
  $scope.deletePrice = function(clientId) {
    $http({
      url: '../../../particuliers/api/price/delete/' + productId + '/' + clientId,
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(function(response) {
      if (response.data.notice) {
        $route.reload();
      } else {
        $scope.deleteAlertError = response.data.error.text;
      }
    })
  }
});
/* ------------------
    Customs
--------------------*/
app.controller('customsCtrl', function($scope, $http, user, $location, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  var productId = $routeParams.productId
  $http.get("../../../particuliers/api/custom/" + productId).then(function(response) {
    $scope.custom = response.data;
    $scope.description = $scope.custom.description;
    $scope.commodityCode = $scope.custom.commodityCode;
    $scope.statisticalCode = $scope.custom.statisticalCode;
    $scope.grossMass = parseFloat($scope.custom.grossMass);
    $scope.netMass = parseFloat($scope.custom.netMass);
    $scope.permitObligation = $scope.custom.permitObligation;
    $scope.commercialGood = $scope.custom.commercialGood;
    $scope.customsClearanceType = $scope.custom.customsClearanceType;
    $scope.nonCustomsLawObligation = $scope.custom.nonCustomsLawObligation;
    $scope.statisticalValue = parseFloat($scope.custom.statisticalValue);
    $scope.preference = $scope.custom.preference;
    $scope.vatCode = $scope.custom.vatCode;
    $scope.packagingType = $scope.custom.packagingType;
    $scope.packagingReferenceNumber = $scope.custom.packagingReferenceNumber;
    $scope.originCountry = $scope.custom.originCountry;
  });
  $scope.editCustom = function() {
    if ($scope.editForm.$valid) {
      var description = $scope.description;
      var commodityCode = $scope.commodityCode;
      var statisticalCode = $scope.statisticalCode;
      var grossMass = $scope.grossMass;
      var netMass = $scope.netMass;
      var permitObligation = $scope.permitObligation;
      var commercialGood = $scope.commercialGood;
      var customsClearanceType = $scope.customsClearanceType;
      var nonCustomsLawObligation = $scope.nonCustomsLawObligation;
      var statisticalValue = $scope.statisticalValue;
      var preference = $scope.preference;
      var vatCode = $scope.vatCode;
      var packagingType = $scope.packagingType;
      var packagingReferenceNumber = $scope.packagingReferenceNumber;
      var originCountry = $scope.originCountry;
      $http({
        url: '../../../particuliers/api/custom/update/' + productId,
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          "description": description,
          "commodityCode": commodityCode,
          "statisticalCode": statisticalCode,
          "grossMass": grossMass,
          "netMass": netMass,
          "permitObligation": permitObligation,
          "commercialGood": commercialGood,
          "customsClearanceType": customsClearanceType,
          "nonCustomsLawObligation": nonCustomsLawObligation,
          "statisticalValue": statisticalValue,
          "preference": preference,
          "vatCode": vatCode,
          "packagingType": packagingType,
          "packagingReferenceNumber": packagingReferenceNumber,
          "originCountry": originCountry
        }
      }).then(function(response) {
        if (response.data.notice) {
          $location.path('/products');
        } else {
          $scope.addAlertError = response.data.error.text;
        }
      })
    }
  }
});
/* ------------------
    Orders
--------------------*/
app.controller('ordersCtrl', function($scope, $http, user, $routeParams) {
  $scope.user = JSON.parse(localStorage.getItem('login'));
  $http.get("../../../particuliers/api/orders").then(function(response) {
    $scope.orders = response.data.sort(function(a, b){return b.orderId-a.orderId});
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.numberOfPages = function() {
      return Math.ceil($scope.orders.length / $scope.pageSize);
    }
		if ($routeParams.orderId) {
			$scope.orderId = $routeParams.orderId;
			var orderId = $routeParams.orderId;
			$scope.order =$scope.orders.filter(function(n) {
				return n.orderId == orderId;
			})[0];
			$scope.date = new Date($scope.order.date);
			$scope.totalHT = 0;
			$scope.base2 = 0;
			$scope.tva2 = 0;
			$scope.base7 = 0;
			$scope.tva7 = 0;
			$scope.totalTVA = 0;
			$scope.totalTTC = 0;
			$http.get("../../../particuliers/api/articles/" + orderId + "/admin").then(function(response) {
				$scope.articles = response.data;
				angular.forEach($scope.articles, function(value, index) {
					$scope.totalTTC += value.price * value.quantity;
					//$scope.totalHT += value.price * value.quantity;
					if (value.tva == 5.5) {
						$scope.base2 += value.price * value.quantity/(1 + value.tva/100);
					}
					if (value.tva == 20) {
						$scope.base7 += value.price * value.quantity/(1 + value.tva/100);
					}
				})
				$scope.tva2 += ($scope.base2 * 5.5) / 100;
				$scope.tva7 += ($scope.base7 * 20) / 100;
				$scope.totalTVA = $scope.tva2 + $scope.tva7;
				$scope.totalHT = $scope.totalTTC - $scope.tva2 - $scope.tva7;
				$scope.totalFrancs = NumberToLetter(Math.floor($scope.totalTTC));
				$scope.totalCentimes = NumberToLetter(parseInt($scope.totalTTC.toFixed(2).toString().split(".")[1]));
					$scope.getArticlesCount = function(providerName) {
						var articles = $scope.articles;
						var count = 0;
						for (var k in articles) {
							if (articles[k].providerName == providerName) {
								count++;
							}
						}
						return count;
					}
			});
		}
  });
  $http.get("../../../particuliers/api/exports").then(function(response) {
    $scope.exports = response.data;
  });
  $http.get("../../../particuliers/api/exports2").then(function(response) {
    $scope.exports2 = response.data;
  });
  $http.get("../../../particuliers/api/products").then(function(response) {
    $scope.products = response.data;
  });
  $http.get("../../../particuliers/api/customs").then(function(response) {
    $scope.customs = response.data;
  });
  $scope.purchaseOrder = function(orderId) {
	  
	  if ($("#order:nth-child(2) tbody tr").length == 0) {
//	   	$("#order:nth-child(2)").hide();

		$("#dashboard-options-menu").css("display", "none");
		$(".dashboard-body").css("display", "none");
		$(".shadow-film").css("display", "none");
		$("#invoice").css("display", "block");
		$("#invoice").css("height", "31.7cm");

	} else {
			   $("#order:nth-child(2)").show();

		 $("#order:nth-child(2)").css("margin-top", "6cm");
		$("#invoice").css("height", "63.7cm");

	} 
	
//windows.print();
$('#invoice').printThis();
/*
	 var pdf = new jsPDF('p', 'mm', 'a4');
  var options = {
       pagesplit: true
  };
  $('#invoice').show();
if ($("#order:nth-child(2) tbody tr").length == 0) {
	   $("#order:nth-child(2)").hide();
	  $("#invoice").css("height", "22.2cm");

	} else {
			   $("#order:nth-child(2)").show();

		 $("#order:nth-child(2)").css("margin-top", "6cm");
		$("#invoice").css("height", "44.4cm");

	} 

pdf.addHTML($('#invoice').first(), options, function() {
        pdf.save("Facture_"+$scope.date.getFullYear()+"-"+orderId+".pdf");
		$('#invoice').hide();


    });	  
	*/
  }
  $scope.purchaseOrder2 = function(orderId, providerName) {
	 $scope.providerName =  providerName;
	if ($("#purchase #order:nth-child(2) tbody tr").length == 0) {
	   $("#purchase #order:nth-child(2)").hide();
	  $("#purchase").css("height", "31.7cm");

	} else {
			   $("#purchase #order:nth-child(2)").show();

		 $("#purchase #order:nth-child(2)").css("margin-top", "6cm");
		$("#purchase").css("height", "63.7cm");

	} 
	
$('#purchase').printThis();
/*var pdf = new jsPDF('p', 'mm', 'a4');
	var options = {
       pagesplit: true
  };
  $('#purchase').show();
if ($("#purchase #order:nth-child(2) tbody tr").length == 0) {
	   $("#purchase #order:nth-child(2)").hide();
	  $("#purchase").css("height", "22.2cm");

	} else {
			   $("#order:nth-child(2)").show();

		 $("#purchase #order:nth-child(2)").css("margin-top", "6cm");
		$("#purchase").css("height", "44.4cm");

	} 

pdf.addHTML($('#purchase').first(), options,  function() {
        pdf.save('Bon_de_commande_'+$scope.date.getFullYear()+'-'+orderId+'-'+ providerName + '.pdf');
		$('#purchase').hide();


    });*/
  }
  $.fn.pickList = function(options) {
    var opts = $.extend({}, $.fn.pickList.defaults, options);
    this.fill = function() {
      var option = '';
      var test = this.getValues();
      var test2 = this.getValues2();
      $.each(opts.data, function(key, val) {
        var options = test.filter(function(n) {
          return n.articleId === val.articleId;
        });
        var options2 = test2.filter(function(n) {
          return n.articleId === val.articleId;
        });
        if (options == 0 && options2 == 0) {
          option += '<option originCountry="' + val.custom.originCountry + '" description="' + val.custom.description + '" commodityCode="' + val.custom.commodityCode + '" statisticalCode="' + val.custom.statisticalCode + '" grossMass="' + val.custom.grossMass + '" netMass="' + val.custom.netMass + '" permitObligation="' + val.custom.permitObligation + '" nonCustomsLawObligation="' + val.custom.nonCustomsLawObligation + '" customsClearanceType="' + val.custom.customsClearanceType + '" commercialGood="' + val.custom.commercialGood + '" statisticalValue="' + val.custom.statisticalValue + '" preference="' + val.custom.preference + '" packagingType="' + val.custom.packagingType + '" packagingReferenceNumber="' + val.custom.packagingReferenceNumber + '" vatCode="' + val.custom.vatCode + '" articleId=' + val.articleId + ' quantity=' + val.quantity + ' designation=' + val.designation + '>' + val.designation + '(' + val.quantity + ')</option>';
        }
      });
      $('#pickData').empty();
      $('#pickData').append(option);
    };
    this.controll = function() {
      var pickThis = this;
      $("#pAdd").on('click', function() {
        var p = $("#pickData option:selected");
        p.clone().appendTo("#pickListResult");
        p.remove();
        $scope.getWeight();
      });
      $("#pAdd2").on('click', function() {
        var p = $("#pickData option:selected");
        p.clone().appendTo("#pickListResult2");
        p.remove();
        $scope.getWeight2();
      });
      $("#pAddAll").on('click', function() {
        var p = $("#pickData option");
        p.clone().appendTo("#pickListResult");
        p.remove();
        $scope.getWeight();
      });
      $("#pAddAll2").on('click', function() {
        var p = $("#pickData option");
        p.clone().appendTo("#pickListResult2");
        p.remove();
        $scope.getWeight2();
      });
      $("#pRemove").on('click', function() {
        var p = $("#pickListResult option:selected");
        p.clone().appendTo("#pickData");
        p.remove();
        $scope.getWeight();
      });
      $("#pRemove2").on('click', function() {
        var p = $("#pickListResult2 option:selected");
        p.clone().appendTo("#pickData");
        p.remove();
        $scope.getWeight2();
      });
      $("#pRemoveAll").on('click', function() {
        var p = $("#pickListResult option");
        p.clone().appendTo("#pickData");
        p.remove();
        $scope.getWeight();
      });
      $("#pRemoveAll2").on('click', function() {
        var p = $("#pickListResult2 option");
        p.clone().appendTo("#pickData");
        p.remove();
        $scope.getWeight2();
      });
    };
    this.getValues = function() {
      var objResult = [];
      $("#pickListResult option").each(function() {
        objResult.push({
          articleId: this.getAttribute('articleId'),
          description: this.getAttribute('description'),
          commodityCode: this.getAttribute('commodityCode'),
          statisticalCode: this.getAttribute('statisticalCode'),
          grossMass: this.getAttribute('grossMass'),
          netMass: this.getAttribute('netMass'),
          permitObligation: this.getAttribute('permitObligation'),
          commercialGood: this.getAttribute('commercialGood'),
          customsClearanceType: this.getAttribute('customsClearanceType'),
          nonCustomsLawObligation: this.getAttribute('nonCustomsLawObligation'),
          statisticalValue: this.getAttribute('statisticalValue'),
          preference: this.getAttribute('preference'),
          vatCode: this.getAttribute('vatCode'),
          packagingType: this.getAttribute('packagingType'),
          packagingReferenceNumber: this.getAttribute('packagingReferenceNumber'),
          originCountry: this.getAttribute('originCountry'),
          quantity: this.getAttribute('quantity')
        });
      });
      return objResult;
    };
    this.getValues2 = function() {
      var objResult = [];
      $("#pickListResult2 option").each(function() {
        objResult.push({
          articleId: this.getAttribute('articleId'),
          description: this.getAttribute('description'),
          commodityCode: this.getAttribute('commodityCode'),
          statisticalCode: this.getAttribute('statisticalCode'),
          grossMass: this.getAttribute('grossMass'),
          netMass: this.getAttribute('netMass'),
          permitObligation: this.getAttribute('permitObligation'),
          commercialGood: this.getAttribute('commercialGood'),
          customsClearanceType: this.getAttribute('customsClearanceType'),
          nonCustomsLawObligation: this.getAttribute('nonCustomsLawObligation'),
          statisticalValue: this.getAttribute('statisticalValue'),
          preference: this.getAttribute('preference'),
          vatCode: this.getAttribute('vatCode'),
          packagingType: this.getAttribute('packagingType'),
          packagingReferenceNumber: this.getAttribute('packagingReferenceNumber'),
          originCountry: this.getAttribute('originCountry'),
          quantity: this.getAttribute('quantity')
        });
      });
      return objResult;
    };
    this.init = function() {
      this.fill();
      this.controll();
    };
    this.init();
    return this;
  };
  var pick;
  $('.datepicker').datepicker();
  $("#weight").val(0);
  $("#weight2").val(0);
  $scope.exchangeRate = 1;
  $scope.getWeight = function() {
    var x = 0;
    $("#pickListResult option").each(function() {
      if(this.getAttribute('grossMass')!="undefined"){
      	x += parseFloat(this.getAttribute('quantity') * this.getAttribute('grossMass'));
      }
    });
    $("#weight").val(x.toFixed(2));
  };
  $scope.getWeight2 = function() {
    var x = 0;
    $("#pickListResult2 option").each(function() {
      if(this.getAttribute('grossMass')!="undefined"){
      	x += parseFloat(this.getAttribute('quantity') * this.getAttribute('grossMass'));
      }
    });
    $("#weight2").val(x.toFixed(2));
  };
  $scope.loadOrder = function(orderId) {
    $("li a").removeClass('secondary');
    $(event.target).addClass('secondary');
    var exp = $scope.exports.filter(function(n) {
      return n.orderId === orderId;
    });
    var articles = exp[0]['articles'];
    $(articles).each(function(index) {
      var product = $scope.products.filter(function(n) {
        return n.designation === articles[index].designation;
      });
      if (typeof(product[0]) == 'undefined') {
        alert("cmd n°"+articles[index].orderId +" - "+articles[index].designation + " n'a pas été introduit dans la déclaration douanière");
        articles[index].custom = "inconnu";
      } else {
        var custom = $scope.customs.filter(function(n) {
          return n.productId === product[0].productId;
        });
        articles[index].custom = custom[0];
      }
      
    });
    pick = $("#pickList").pickList({
      data: articles
    });
  }
  $scope.loadOrder2 = function(providerName) {
    $("li a").removeClass('secondary');
    $(event.target).addClass('secondary');
    var exp = $scope.exports2.filter(function(n) {
      return n.providerName === providerName;
    });
    var articles = exp[0]['articles'];
    $(articles).each(function(index) {
      var product = $scope.products.filter(function(n) {
        return n.designation === articles[index].designation;
      });
      if (typeof(product[0]) == 'undefined') {
        alert("cmd n°"+articles[index].orderId +" - "+articles[index].designation + " n'a pas été introduit dans la déclaration douanière");
        articles[index].custom = "inconnu";
      } else {
        var custom = $scope.customs.filter(function(n) {
          return n.productId === product[0].productId;
        });
        articles[index].custom = custom[0];
      }
    });
    pick = $("#pickList").pickList({
      data: articles
    });
  }
  $scope.exporterXml = function(vehiculeId) {
    var exchangeRate = $scope.exchangeRate;
    var items = "";
    var articles = [];
    var orders = [];
    var listItems2 = [];
    if (vehiculeId == 1) {
      var transportationNumber = $scope.transportationNumber;
      var listItems = pick.getValues();
    } else {
      var transportationNumber = $scope.transportationNumber2;
      var listItems = pick.getValues2();
    }
    $(listItems).each(function() {
      if (this.description != 'undefined') {
        articles.push(parseInt(this.articleId));
        var index = orders.indexOf(this.commodityCode + '-' + this.statisticalCode);
    	
        if (index == -1) {
          orders.push(this.commodityCode + '-' + this.statisticalCode);
          listItems2.push(this);
          listItems2[listItems2.length-1].grossMass = parseFloat(this.quantity * this.grossMass);
          listItems2[listItems2.length-1].netMass = parseFloat(this.quantity * this.netMass);
          listItems2[listItems2.length-1].statisticalValue = parseFloat(this.quantity * this.statisticalValue);
          listItems2[listItems2.length-1].packagingType = [listItems2[listItems2.length-1].packagingType];
          listItems2[listItems2.length-1].packagingReferenceNumber = [listItems2[listItems2.length-1].packagingReferenceNumber];
          listItems2[listItems2.length-1].quantity = [listItems2[listItems2.length-1].quantity];
        } else {
          //listItems2[index].quantity = parseInt(listItems2[index].quantity) + parseInt(this.quantity);
          listItems2[index].grossMass = parseFloat(listItems2[index].grossMass) + parseFloat(this.quantity * this.grossMass);
          listItems2[index].netMass = parseFloat(listItems2[index].netMass) + parseFloat(this.quantity * this.netMass);
          listItems2[index].statisticalValue = parseFloat(listItems2[index].statisticalValue) + parseFloat(this.quantity * this.statisticalValue);
          var index2 = listItems2[index].packagingReferenceNumber.indexOf(this.packagingReferenceNumber);
          if(index2 == -1) {
          	listItems2[index].quantity.push(parseInt(this.quantity));
          	listItems2[index].packagingReferenceNumber.push(this.packagingReferenceNumber);
          	listItems2[index].packagingType.push(this.packagingType);
          } else {
          	listItems2[index].quantity[index2] = parseInt(listItems2[index].quantity[index2]) + parseInt(this.quantity);
          }
        }
      }
    });
    $(listItems2).each(function(index) {
    	var packaging = "";
      if (this.preference == 0) {
        documentReferenceNumber = "";
        documentType = "";
        issueDate = "";
      } else {
        documentReferenceNumber = '<documentReferenceNumber>' + $scope.documentReferenceNumber + '</documentReferenceNumber>';
        documentType = 862 //Déclaration d'origine
        issueDate = '<issueDate class="com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl">' + '<year>' + parseInt($scope.issueDate.substr(6, 4)) + '</year>' + '<month>' + parseInt($scope.issueDate.substr(0, 2)) + '</month>' + '<day>' + parseInt($scope.issueDate.substr(3, 2)) + '</day>' + '<timezone>-2147483648</timezone>' + '<hour>-2147483648</hour>' + '<minute>-2147483648</minute>' + '<second>-2147483648</second>' + '</issueDate>';
      }
      if (this.permitObligation == 0) {
        permit = "";
      } else {
        permit = '<permit><PermitType><permitType>2</permitType><permitAuthority>1</permitAuthority><permitNumber>402507</permitNumber></PermitType></permit>';
      }
      $(listItems2[index].packagingReferenceNumber).each(function(i){
    		packaging += '<PackagingType>' + '<packagingType>' + listItems2[index].packagingType[i] + '</packagingType>' + '<quantity>' + listItems2[index].quantity[i] + '</quantity>' + '<packagingReferenceNumber>' + listItems2[index].packagingReferenceNumber[i] + '</packagingReferenceNumber>' + '</PackagingType>';
			});
      //items += '<GoodsItemType>' + '<traderItemID>' + index + '</traderItemID>' + '<description>' + this.description + '</description>' + '<commodityCode>' + this.commodityCode + '</commodityCode>' + '<statisticalCode>' + this.statisticalCode + '</statisticalCode>' + '<grossMass>' +  parseFloat(this.grossMass * this.quantity).toFixed(2) + '</grossMass>' + '<netMass>' + parseFloat(this.netMass * this.quantity).toFixed(2) + '</netMass>' + '<permitObligation>' + this.permitObligation + '</permitObligation>' + '<nonCustomsLawObligation>' + this.nonCustomsLawObligation + '</nonCustomsLawObligation>' + '<statistic>' + '<customsClearanceType>' + this.customsClearanceType + '</customsClearanceType>' + '<commercialGood>' + this.commercialGood + '</commercialGood>' + '<statisticalValue>' + Math.floor(this.statisticalValue * exchangeRate * this.quantity) + '</statisticalValue>' + '<repair>0</repair>' + '</statistic>' + '<origin>' + '<originCountry>' + this.originCountry + '</originCountry>' + '<preference>' + this.preference + '</preference>' + '</origin>' + '<packaging>' + '<PackagingType>' + '<packagingType>' + this.packagingType + '</packagingType>' + '<quantity>' + this.quantity + '</quantity>' + '<packagingReferenceNumber>' + this.packagingReferenceNumber + '</packagingReferenceNumber>' + '</PackagingType>' + '</packaging>' + '<producedDocument>' + '<ProducedDocumentType>' + '<documentType>' + documentType + '</documentType>' + documentReferenceNumber + issueDate + '</ProducedDocumentType>' + '</producedDocument>' + '<valuation>' + '<netDuty>0</netDuty>' + '<vatValue>' + parseInt(Math.floor(this.statisticalValue * exchangeRate * this.quantity) + 5) + '</vatValue>' + '<vatCode>' + this.vatCode + '</vatCode>' + '</valuation>' + '</GoodsItemType>';
      //items += '<GoodsItemType>' + '<traderItemID>' + index + '</traderItemID>' + '<description>' + this.description + '</description>' + '<commodityCode>' + this.commodityCode + '</commodityCode>' + '<statisticalCode>' + this.statisticalCode + '</statisticalCode>' + '<grossMass>' +  parseFloat(this.grossMass).toFixed(2) + '</grossMass>' + '<netMass>' + parseFloat(this.netMass).toFixed(2) + '</netMass>' + '<permitObligation>' + this.permitObligation + '</permitObligation>' + '<nonCustomsLawObligation>' + this.nonCustomsLawObligation + '</nonCustomsLawObligation>' + '<statistic>' + '<customsClearanceType>' + this.customsClearanceType + '</customsClearanceType>' + '<commercialGood>' + this.commercialGood + '</commercialGood>' + '<statisticalValue>' + Math.floor(this.statisticalValue * exchangeRate) + '</statisticalValue>' + '<repair>0</repair>' + '</statistic>' + '<origin>' + '<originCountry>' + this.originCountry + '</originCountry>' + '<preference>' + this.preference + '</preference>' + '</origin>' + '<packaging>' + '<PackagingType>' + '<packagingType>' + this.packagingType + '</packagingType>' + '<quantity>' + this.quantity + '</quantity>' + '<packagingReferenceNumber>' + this.packagingReferenceNumber + '</packagingReferenceNumber>' + '</PackagingType>' + '</packaging>' + '<producedDocument>' + '<ProducedDocumentType>' + '<documentType>' + documentType + '</documentType>' + documentReferenceNumber + issueDate + '</ProducedDocumentType>' + '</producedDocument>' + '<valuation>' + '<netDuty>0</netDuty>' + '<vatValue>' + parseInt(Math.floor(this.statisticalValue * exchangeRate) + 5) + '</vatValue>' + '<vatCode>' + this.vatCode + '</vatCode>' + '</valuation>' + '</GoodsItemType>';
			items += '<GoodsItemType>' + '<traderItemID>' + index + '</traderItemID>' + '<description>' + this.description + '</description>' + '<commodityCode>' + this.commodityCode + '</commodityCode>' + '<statisticalCode>' + this.statisticalCode + '</statisticalCode>' + '<grossMass>' +  parseFloat(this.grossMass).toFixed(2) + '</grossMass>' + '<netMass>' + parseFloat(this.netMass).toFixed(2) + '</netMass>' + '<permitObligation>' + this.permitObligation + '</permitObligation>' + '<nonCustomsLawObligation>' + this.nonCustomsLawObligation + '</nonCustomsLawObligation>' + '<statistic>' + '<customsClearanceType>' + this.customsClearanceType + '</customsClearanceType>' + '<commercialGood>' + this.commercialGood + '</commercialGood>' + '<statisticalValue>' + Math.floor(this.statisticalValue * exchangeRate) + '</statisticalValue>' + '<repair>0</repair>' + '</statistic>' + '<origin>' + '<originCountry>' + this.originCountry + '</originCountry>' + '<preference>' + this.preference + '</preference>' + '</origin>' + '<packaging>' + packaging + '</packaging>' + permit + '<producedDocument>' + '<ProducedDocumentType>' + '<documentType>' + documentType + '</documentType>' + documentReferenceNumber + issueDate + '</ProducedDocumentType>' + '</producedDocument>' + '<valuation>' + '<netDuty>0</netDuty>' + '<vatValue>' + parseInt(Math.floor(this.statisticalValue * exchangeRate) + 2) + '</vatValue>' + '<vatCode>' + this.vatCode + '</vatCode>' + '</valuation>' + '</GoodsItemType>';

    });
    items = items.replace(/\<statisticalCode><\/statisticalCode\>/g, "");
    items = items.replace(/\<documentType><\/documentType\>/g, "");
    items = items.replace(/\<ProducedDocumentType><\/ProducedDocumentType\>/g, "");
    items = items.replace(/\<producedDocument><\/producedDocument\>/g, "");
    var xml = '<EdecWeb version="4.0" createdDate="2019-12-09 23:44:02.71 UTC">'+
    			'<goodsDeclarationType>'+
    				'<serviceType>1</serviceType>'+
    				'<declarationType>1</declarationType>' + 
    				'<language>fr</language>' + 
    				'<dispatchCountry>FR</dispatchCountry>' + 
    				'<transportMeans>' + 
    					'<transportMode>3</transportMode>' + 
    					'<transportationType>1</transportationType>' + 
    					'<transportationCountry>FR</transportationCountry>' + 
    					'<transportationNumber>' + transportationNumber + '</transportationNumber>' + 
    				'</transportMeans>' + 
    				'<transportInContainer>0</transportInContainer>' + 
    				'<previousDocument/>' + 
    				'<importer>' +
						'<name>Le Palmier Sàrl</name>' +
						'<postalCode>1214</postalCode>' +
						'<city>Vernier</city>' +
						'<country>CH</country>' +
						'<traderIdentificationNumber>CHE485765573</traderIdentificationNumber>' +
    				'</importer>' + 
    				'<consignee>' + 
						'<name>Le Palmier Sàrl</name>' +
						'<postalCode>1214</postalCode>' +
						'<city>Vernier</city>' +
						'<country>CH</country>' +
						'<traderIdentificationNumber>CHE485765573</traderIdentificationNumber>' +
    				'</consignee>' + 
    				'<declarant>' + 
    					'<traderIdentificationNumber></traderIdentificationNumber>' + 
    					'<name>Le Palmier sarl</name>' + 
    					'<street>Route de Peney 51</street>' + 
    					'<postalCode>1214</postalCode>' + 
    					'<city>Vernier</city>' + 
    					'<country>CH</country>' + 
    				'</declarant>' + 
    				'<business>' + 
    					'<customsAccount>0</customsAccount>' + 
    					'<vatAccount>0</vatAccount>' + 
    					'<vatSuffix>0</vatSuffix>' + 
    					'<invoiceCurrencyType>2</invoiceCurrencyType>' + 
    				'</business>' + 
    			'<goodsItem>' + items + '</goodsItem>' + 
    		'</goodsDeclarationType>' + 
    	'</EdecWeb>';
    xmlData = vkbeautify.xml(xml);
	 $http({
      url: '../../../particuliers/api/orders/update',
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        "articles": articles
      }
    }).then(function(response) {
      if (response.data.notice) {
        var textFileAsBlob = new Blob([xmlData], {
          type: 'text/plain'
        });
        var fileNameToSaveAs = "douane.xml";
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        if (window.webkitURL != null) {
          // Chrome allows the link to be clicked without actually adding it to the DOM.
          downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        } else {
          // Firefox requires the link to be added to the DOM before it can be clicked.
          downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
          downloadLink.onclick = destroyClickedElement;
          downloadLink.style.display = "none";
          document.body.appendChild(downloadLink);
        }
        downloadLink.click();
        if (vehiculeId == 1) {
          $("#pickListResult").empty();
        } else {
          $("#pickListResult2").empty();
        }
        $http.get("../../../particuliers/api/exports").then(function(response) {
          $scope.exports = response.data;
        });
        $http.get("../../../particuliers/api/exports2").then(function(response) {
          $scope.exports2 = response.data;
        });
      } else {
        alert(response.data.error.text);
      }
    })
  }
});
function destroyClickedElement(event) {
  // remove the link from the DOM
  document.body.removeChild(event.target);
}

function createShiftArr(step) {
  var space = '    ';
  if (isNaN(parseInt(step))) { // argument is string
    space = step;
  } else { // argument is integer
    switch (step) {
      case 1:
        space = ' ';
        break;
      case 2:
        space = '  ';
        break;
      case 3:
        space = '   ';
        break;
      case 4:
        space = '    ';
        break;
      case 5:
        space = '     ';
        break;
      case 6:
        space = '      ';
        break;
      case 7:
        space = '       ';
        break;
      case 8:
        space = '        ';
        break;
      case 9:
        space = '         ';
        break;
      case 10:
        space = '          ';
        break;
      case 11:
        space = '           ';
        break;
      case 12:
        space = '            ';
        break;
    }
  }
  var shift = ['\n']; // array of shifts
  for (ix = 0; ix < 100; ix++) {
    shift.push(shift[ix] + space);
  }
  return shift;
}

function vkbeautify() {
  this.step = '    '; // 4 spaces
  this.shift = createShiftArr(this.step);
}
vkbeautify.prototype.xml = function(text, step) {
  var ar = text.replace(/>\s{0,}</g, "><").replace(/</g, "~::~<").replace(/\s*xmlns\:/g, "~::~xmlns:").replace(/\s*xmlns\=/g, "~::~xmlns=").split('~::~'),
    len = ar.length,
    inComment = false,
    deep = 0,
    str = '',
    ix = 0,
    shift = step ? createShiftArr(step) : this.shift;
  for (ix = 0; ix < len; ix++) {
    // start comment or <![CDATA[...]]> or <!DOCTYPE //
    if (ar[ix].search(/<!/) > -1) {
      str += shift[deep] + ar[ix];
      inComment = true;
      // end comment  or <![CDATA[...]]> //
      if (ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1 || ar[ix].search(/!DOCTYPE/) > -1) {
        inComment = false;
      }
    } else
      // end comment  or <![CDATA[...]]> //
      if (ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1) {
        str += ar[ix];
        inComment = false;
      } else
        // <elm></elm> //
        if (/^<\w/.exec(ar[ix - 1]) && /^<\/\w/.exec(ar[ix]) && /^<[\w:\-\.\,]+/.exec(ar[ix - 1]) == /^<\/[\w:\-\.\,]+/.exec(ar[ix])[0].replace('/', '')) {
          str += ar[ix];
          if (!inComment) deep--;
        } else
          // <elm> //
          if (ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) == -1 && ar[ix].search(/\/>/) == -1) {
            str = !inComment ? str += shift[deep++] + ar[ix] : str += ar[ix];
          } else
            // <elm>...</elm> //
            if (ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) > -1) {
              str = !inComment ? str += shift[deep] + ar[ix] : str += ar[ix];
            } else
              // </elm> //
              if (ar[ix].search(/<\//) > -1) {
                str = !inComment ? str += shift[--deep] + ar[ix] : str += ar[ix];
              } else
                // <elm/> //
                if (ar[ix].search(/\/>/) > -1) {
                  str = !inComment ? str += shift[deep] + ar[ix] : str += ar[ix];
                } else
                  // <? xml ... ?> //
                  if (ar[ix].search(/<\?/) > -1) {
                    str += shift[deep] + ar[ix];
                  } else
                    // xmlns //
                    if (ar[ix].search(/xmlns\:/) > -1 || ar[ix].search(/xmlns\=/) > -1) {
                      str += shift[deep] + ar[ix];
                    }
    else {
      str += ar[ix];
    }
  }
  return (str[0] == '\n') ? str.slice(1) : str;
}
window.vkbeautify = new vkbeautify();
app.filter('groupBy', function() {
  return function(list, group_by) {
    var filtered = [];
    var prev_item = null;
    var group_changed = false;
    var group_count = 0;
    // this is a new field which is added to each item where we append "_CHANGED"
    // to indicate a field change in the list
    var new_field = group_by + '_CHANGED';
    var new_field2 = group_by + '_COUNT';
    // loop through each item in the list
    angular.forEach(list, function(item) {
      group_changed = false;
      // if not the first item
      if (prev_item !== null) {
        // check if the group by field changed
        if (prev_item[group_by] !== item[group_by]) {
          group_changed = true;
          group_count++;
        }
        // otherwise we have the first item in the list which is new
      } else {
        group_changed = true;
        group_count++;
      }
      // if the group changed, then add a new field to the item
      // to indicate this
      if (group_changed) {
        item[new_field] = true;
        item[new_field2]++;
      } else {
        item[new_field] = false;
        item[new_field2] = 0;
      }
      filtered.push(item);
      prev_item = item;
    });
    return filtered;
  };
})
app.filter('startFrom', function() {
  return function(input, start) {
    if (!input || !input.length) {
      return;
    }
    start = +start; //parse to int
    return input.slice(start);
  }
});
