(function ($) {
  Drupal.behaviors.addCartBehavior = {
    attach: function (context, settings) {
      $.prototype.addProductInCart = function (id) {
        var src = '/sites/default/files/styles/large/public/';

        var query_add_cart = [{
          "purchased_entity_type": "commerce_product_variation",
          "purchased_entity_id": id,
          "quantity": "1"
        }];

        $.ajax({
          url: '/cart/add?_format=json',
          method: 'post',
          data: JSON.stringify(query_add_cart),
          headers: {'Content-Type': 'application/json'},
          success: function(data){
            var order_id = data[0]['order_id'];
            var get_request = '/cart/' + order_id + '?_format=json';
            $.get(get_request, function(data) {
              console.log(data);
              var content = '<div class="cart">';
              data['items'].forEach(function (item) {
                img_attr = 'width="60" height="60" src="' + src + item['uri'] +'"';
                img = '<div class="item-img-container"><img ' + img_attr + '></div>';
                content = content + '<div class="card">'
                content = content + '<div class="item-img-container">' + img + '</div>';
                content = content + '<div class="item-name">Наименование товара: ' + item['name'] + '</div>';
                content = content + '<div class="item-count">Количество: ' + Math.round(item['quantity']) + '</div>';
                content = content + '<div class="item-attribute-size">Размер: ' + item['attribute_size'] + '</div>';
                content = content + '<div class="item-price">Сумма: ' + parseFloat(item['item_total_price']['number']).toFixed(2) + ' ' + item['item_total_price']['currency_code'] + '</div>';
                content = content + '</div>';
              });
              total_price_cart = data['total_price']['number'];
              total_price_cart = parseFloat(total_price_cart).toFixed(2);
              content = content + '<div class="total_price">';
              content = content + 'Общая сумма: ' + total_price_cart + data['total_price']['currency_code'];
              content = content + '</div>';
              content = content + '</div>';

              var myDialog = $(content).appendTo('body');
              Drupal.dialog(myDialog, {
                title: 'Cart',
                buttons: [{
                  text: 'Close',
                  click: function() {
                    $(this).dialog('close');
                  }
                }]
              }).showModal();
            });
          }
        });
      }
    }
  };
})(jQuery);
