Files
du_an_khach_hang/Chico/product_detail.js
2023-03-30 17:40:10 +07:00

920 lines
27 KiB
JavaScript

// LAZY FOOTER ARTICLE
lazy_load_group.push(
{
id: 'js-artilce-product-detail',
target: '#js-artilce-product-detail',
loadFn: function () {
getArticleProductDetail();
},
},
)
//FANCYBOX
// SWIPER GALLERY - PRODUCT
function swiperThumbnails() {
const galleryThumbs = new Swiper(".gallery-thumbs", {
spaceBetween: 8,
slidesPerView: 5,
slideToClickedSlide: true,
freeMode: true,
watchSlidesProgress: true,
centerInsufficientSlides: true,
navigation: {
nextEl: ".swiper-button-next-gallery",
prevEl: ".swiper-button-prev-gallery",
},
});
const galleryTop = new Swiper(".gallery-top", {
spaceBetween: 16,
slidesPerView: 1,
thumbs: {
swiper: galleryThumbs,
},
// AUTO SILDED AT FISRT AND END
on: {
slideChange: function () {
let activeIndex = this.activeIndex + 1;
let activeSlide = document.querySelector(
`.gallery-thumbs .swiper-slide:nth-child(${activeIndex})`
);
let nextSlide = document.querySelector(
`.gallery-thumbs .swiper-slide:nth-child(${activeIndex + 1})`
);
let prevSlide = document.querySelector(
`.gallery-thumbs .swiper-slide:nth-child(${activeIndex - 1})`
);
if (
nextSlide &&
!nextSlide.classList.contains("swiper-slide-visible")
) {
this.thumbs.swiper.slideNext();
} else if (
prevSlide &&
!prevSlide.classList.contains("swiper-slide-visible")
) {
this.thumbs.swiper.slidePrev();
}
},
},
});
}
swiperThumbnails();
function fancyBox() {
Fancybox.bind('[data-fancybox="gallery"]', {
Toolbar: {
display: [
{
id: "counter",
position: "center",
},
"zoom",
"slideshow",
"fullscreen",
"thumbs",
"close",
],
},
//click: "unset",
on: {
initLayout: (fancybox) => {
// Create left column
const $leftCol = document.createElement("div");
$leftCol.classList.add("fancybox__leftCol");
while (fancybox.$container.firstChild) {
$leftCol.appendChild(fancybox.$container.firstChild);
}
// Add elements to DOM
fancybox.$container.appendChild(fancybox.$backdrop);
fancybox.$container.appendChild($leftCol);
fancybox.$leftCol = $leftCol;
},
"Carousel.ready Carousel.change": (fancybox, carousel, slideIndex) => {
// Get index of the current gallery item
slideIndex =
slideIndex === undefined
? carousel.options.initialPage
: slideIndex;
// console.log(slideIndex);
// Get link related to current item
const $trigger = fancybox.items[slideIndex].$trigger;
// Get data from `data-info` attribute
const data = $trigger.dataset.info || "";
},
},
});
}
fancyBox();
function callForMe(){
var error = "";
var number_regex1 = /^[0]\d{9}$/i;
var number_regex2 = /^[0]\d{10}$/i;
var glPro = "{{ page.product_info.productName}}";
var check_name = 'Khách hàng yêu cầu gọi lại';
var check_email = '';
var check_tel = document.getElementById('phone-now').value;
var check_message = "Khách hàng yêu cầu gọi lại sản phẩm: " + glPro;
if(check_tel.length < 8) error += "- Bạn chưa nhập số điện thoại\n";
else{
if(number_regex1.test(check_tel) == false && number_regex2.test(check_tel) == false) error += "- Số điện thoại chưa chính xác\n";
}
if (error == "") {
var params = {
action : "customer",
action_type: "contact",
type: "contact",
info: {
name: check_name,
email: check_email,
tel: check_tel,
title : 'Khách hàng yêu cầu gọi lại sản phẩm: ' + glPro,
message: check_message,
},
};
Hura.Ajax.post("customer", params).then(function (data) {
alert(
"Bạn đã gửi liên hệ thành công\nChúng tôi đã nhận được thông tin và sẽ liên hệ với quý khách trong thời gian sớm nhất"
);
location.reload();
});
} else alert(error);
return false;
}
$("#js-showmore").click(function(){
$("#js-summary").toggleClass("active");
var text = $(this).find("span").html();
if (text == 'Xem thêm') {
$(this).find("span").text("Thu gọn");
} else if (text == 'Thu gọn') {
$(this).find("span").text("Xem thêm");
}
})
function _showProductDescription() {
let height_container = $("#js-product-desc").height();
$("#js-desc-showmore").css("display","block");
$("#js-desc-showmore").click(function(){
$("#js-product-desc").addClass("active");
$("#js-desc-showless").css("display","block");
$(this).hide();
});
$("#js-desc-showless").click(function(){
$("#js-product-desc").removeClass("active");
$("#js-desc-showmore").css("display","block");
$(this).hide();
$('html, body').animate({
scrollTop: $("#js-product-desc").offset().top - 140
},800);
});
}
_showProductDescription();
// ADD PRODUCT TO CART - PRODUCT DETAILS
function addProductToCart(product_id, variant_id_fake, props) {
const props_quantity = parseInt($(".js-buy-quantity-temp").attr("value"));
const stockQuantity = parseInt($(".bk-check-out-of-stock").attr("value"));
//console.log(props_quantity);
var variant_id = 0;
var data = $('.js-variant-option-container input[type="hidden"]').val();
if (data) {
var newData = JSON.parse(data)
variant_id = newData.variant_id;
}
if (stockQuantity) {
var product_props = {
quantity: props_quantity,
buyer_note: "",
};
Hura.Cart.Product.add(product_id, variant_id, product_props).then(function (
response
) {
// Error response
if (response.status === "error") {
if (response.error_type == "item-in-cart") {
alert("Sản phẩm đã trong giỏ hàng");
} else if (response.error_type == "invalid-item-id")
alert("ID sản phẩm không đúng");
else alert(response.message);
}
// Success response
else {
modalSuccess();
change_cart_amount();
}
});
} else {
alert("Sản phẩm không có sẵn. Vui lòng liên hệ. Xin cảm ơn!")
}
}
// BUY NOW
function buyNow(product_id, variant_id_fake, props) {
addProductToCart(product_id, variant_id_fake, props);
const stockQuantityCheck = parseInt($(".bk-check-out-of-stock").attr("value"));
if (stockQuantityCheck) {
setTimeout(function () {
window.location.href = "./cart";
}, 1500);
}
}
// BUY NOW
function buyPayInstall(product_id, variant_id_fake, props) {
addProductToCart(product_id, variant_id_fake, props);
const stockQuantityCheck = parseInt($(".bk-check-out-of-stock").attr("value"));
if (stockQuantityCheck) {
setTimeout(function () {
window.location.href = "./cart?show=tragop";
}, 1500);
}
}
// LANG NGHE THAY DOI SO LUONG SP
function listenQuantityBuy() {
const $track_change = $(".js-quantity-change");
//thay doi so luong sp mua, neu nhap so luong
$track_change.on("change", function (e) {
$(".js-buy-quantity-temp").attr("value", e.target.value);
});
//thay doi so luong sp theo - hoac +
$track_change.on("click", function (e) {
if (e.target.nodeName === "INPUT") return;
let quantity_change = parseInt(this.getAttribute("data-value"));
let $row = $(this).closest(".cart-quantity-select");
let current_quantity = parseInt($row.find(".js-buy-quantity").val());
//loai bo so luong vo ly
if (current_quantity < 0) {
$row.find(".js-buy-quantity").val(0);
return;
}
let totalQuantity = current_quantity + quantity_change;
$row.find(".js-buy-quantity").val(totalQuantity);
$(".js-buy-quantity-temp").attr("value", totalQuantity);
});
}
listenQuantityBuy();
function renReplyReview(new_replies){
var html = '';
new_replies.forEach(function(value,item){
var check_user = `<span class="avatar">
<b class="avatar-user">`+value.user_name+`</b>
</span>
<b class="name">`+value.user_name+`</b>`;
if (value.is_user_admin == 1) {
check_user = `<i class="cmt-logo"></i>
<b class="name">`+value.user_name+`</b>
<i class="qtv">QTV</i>`
}
if(value.is_user_admin == 1 || value.approved == 1){
html += `
<div class="item_reply">
<div class="comment_right">
<div class="comment-name">
`+check_user+`
</div>
<div class="reply-content">`+value.content+`</div>
</div>
</div>
`;
}
})
return html;
}
// COMMENT KHÁCH HÀNG
const is_admin_login = "no";
const customer_info = 0;
$(document).ready(function () {
getRatingComment();
$(".comment-form textarea").focus(function(){
$(this).parent().find(".form-input").show();
});
layComment({{ page.product_info.productId }}, "product", "", "", "new");
$("#js-show-comment").click(function(){
$("#js-box-review").fadeIn();
$("#js-show-comment").addClass("hide");
$("#js-hide-comment").removeClass("hide");
});
$("#js-hide-comment").click(function(){
$("#js-box-review").fadeOut();
$("#js-hide-comment").addClass("hide");
$("#js-show-comment").removeClass("hide");
});
$("#comment_keyword").keydown(function(e){
if(e.keyCode==13){
var search_field = $(".search-comment select").val();
var keyword = $("#comment_keyword").val();
//console.log(search_field +"---"+keyword);
layComment({{ page.product_info.productId }},keyword,search_field,'new');
}
});
$(".comment-action-list .sort a").click(function(){
$(".comment-action-list .sort a").removeClass("current");
$(this).addClass("current");
});
});
function checkReply(is_admin_login, customer_info, replyTo) {
var formReply = "";
if (is_admin_login == "yes") {
formReply =`
<div class="input-text" style="margin-bottom: 20px;align-items: center;display: flex;">
<p style="margin: 0 10px 0 0;color: #f15a22;">Bạn đang đăng nhập là Admin</p>
<input type=hidden id="name`+replyTo+`" value='Admin'/>
<input type=hidden id="email`+replyTo+`" value='admin@gmail.com'/>
<a href="javascript:;" class="send_form" onclick="postComment(`+replyTo+`,'reply')"> Gửi bình luận </a>
</div>
`;
} else if (is_admin_login == "no" && customer_info.length > 0) {
formReply =
`
<div class="input-text">
<input type=hidden id="name`+replyTo+`" value=''/>
<input type=hidden id="email`+replyTo+`" value=''/>
<a href="javascript:;" class="send_form" onclick="postComment(`+replyTo+`,'reply')"> Gửi bình luận </a>
</div>
`;
} else
formReply =
`
<div class="comment-form-input" id="comment-form-input-0" style="display: block;">
<div class="form-group input-text">
<input type="text" id="name`+replyTo+`" placeholder="Họ và tên" name='user_post[user_name]' class="inputText" value=""/>
<input type="text" id="email`+replyTo+`" placeholder="Email" name='user_post[user_email]' class="inputText" value=""/>
<a href="javascript:;" class="btn-send-comment send_form" onclick="postComment(`+replyTo+`,'reply')"> Gửi bình luận </a>
</div>
</div>`;
return formReply;
}
function checkReplyReview(is_admin_login, customer_info , replyTo) {
var formReply = '';
if( is_admin_login == 'yes') {
formReply = `
<p class="note">Bạn đang đăng nhập là Admin</p>
<input type=hidden id="review-name`+replyTo+`" value='Admin'/>
<input type=hidden id="review-email`+replyTo+`" value='admin@gmail.com'/>
<input type="button" onclick="postReview(`+replyTo+`,'reply')" value="Gửi" class="btn-send-comment" />
`;
} else if ( is_admin_login == 'no' && customer_info.length > 0 ) {
formReply = `
<input type=hidden id="review-name`+replyTo+`" value=''/>
<input type=hidden id="review-email`+replyTo+`" value=''/>
<input type="button" onclick="postReview(`+replyTo+`,'reply')" value="Gửi" class="btn-send-comment" />
`;
} else
formReply = `
<div class="comment-form-input" id="comment-form-input-0" style="display: block;">
<div class="form-group clearfix">
<input type="text" id="review-name`+replyTo+`" name='user_post[user_name]' class="inputText" placeholder="Họ tên*" value=""/>
<input type="text" id="review-email`+replyTo+`" name='user_post[user_email]' class="inputText" placeholder="Email*" value=""/>
<input type="button" onclick="postReview(`+replyTo+`,'reply')" value="Gửi" class="btn-send-comment" />
</div>
</div>`;
return formReply ;
}
function layComment(productId, item_type, searchText, searchField, sort) {
var params = {
action_type: "get",
item_type: "product",
item_id: productId,
search: searchText,
search_field: searchField,
order_by: "new",
};
Hura.Ajax.get("comment", params).then(function (data) {
//console.log("comment - ", data);
var html = Hura.Template.parse(commentTpl, data);
Hura.Template.render("#comment-list", html);
$(".js-avatar-user").each(function () {
var name = $(this).html().substring(0, 1);
$(this).html(name);
});
});
}
function getReply(commentId) {
var replyParams = {
action_type: "get-reply",
item_id: commentId,
};
var target = "#reply_list_" + commentId;
Hura.Ajax.get("comment", replyParams).then(function (data) {
// console.log("getReply - ", data);
var html = Hura.Template.parse(replyTpl, data);
Hura.Template.render(target, html);
$(".js-avatar-user").each(function () {
var name = $(this).html().substring(0, 1);
$(this).html(name);
});
});
}
function send_vote(){
var error = "";
var idUpload = $('#js-file-upload-id').val();
if($("#rating-content").val() == '') error+="Bạn chưa nhập nội dung đánh giá\n";
if($("#rating-name").val() == '') error+="Bạn chưa nhập tên\n";
if($("#rating-email").val() == '') error+="Bạn chưa nhập email\n";
if(error!=''){
alert(error);
return false;
}
var reviewParams = {
action_type: "review",
info : {
item_type : 'product',
item_id : {{ page.product_info.productId }},
item_title : `{{ page.product_info.productName }}`,
user_name : $("#rating-name").val(),
user_email : $("#rating-email").val(),
user_avatar : '',
user_note : '',
rate : $("#select-rate-pro input:checked").val(),
title : `Đánh giá sản phẩm {{ page.product_info.productName }}`,
content : $("#rating-content").val(),
files : idUpload
}
}
Hura.Ajax.post('customer', reviewParams).then(function (data) {
//console.log("data",data);
alert('Bạn đã gửi thành công!'); location.reload();
})
}
function getRatingComment() {
var params = {
action_type: "list",
item_id :{{ page.product_info.productId }},
search : '',
search_field :'',
order_by :'new',
numPerPage :20,
item_type : 'product'
};
Hura.Ajax.get("review", params).then(function (data) {
//console.log(data);
var html = Hura.Template.parse(rating_tpl, data);
Hura.Template.render("#js-review-holder", html);
})
}
function postComment(id, reply) {
if (check_field(id) == false) return false;
if (reply == "") {
var item_type = $(".form-post [name='user_post[item_type]']").val();
var item_id = $(".form-post [name='user_post[item_id]']").val();
var item_title = $(".form-post [name='user_post[item_title]']").val();
var title = $(".form-post [name='user_post[title]']").val();
var avatar = $(".form-post [name='user_post[user_avatar]']").val();
var user_name = $("#name" + id).val();
var user_email = $("#email" + id).val();
var content = $("#content" + id).val();
var rate = $("#rating-review0 input:checked").val();
var idUpload = $('#js-file-upload-id').val();
var params = {
action_type: "comment",
type :"ajax",
info: {
item_type : 'product',
item_id : '{{ page.product_info.productId }}',
item_title : `{{ page.product_info.productName }}`,
reply_to : reply_to,
user_email : user_email,
user_name : user_name,
user_avatar : '',
user_note : '',
rate : 5,
title : `{{ page.product_info.productName }}`,
content : content,
files : ''
},
};
// console.log(params);
Hura.Ajax.post("customer", params).then(function (data) {
alert("Bạn đã gửi thành công");
location.reload();
});
} else {
var reply_to = id;
var item_type = $(".form-reply" + id + "[name='user_post[item_type]']").val();
var item_id = $(".form-reply" + id + "[name='user_post[item_id]']").val();
var item_title = $(".form-reply" + id + "[name='user_post[item_title]']").val();
var title = $(".form-reply" + id + "[name='user_post[title]']").val();
var avatar = $(".form-reply" + id + "[name='user_post[user_avatar]']").val();
var user_name = $("#name" + id).val();
var user_email = $("#email" + id).val();
var content = $("#content" + id).val();
var params = {
action_type: "comment-reply",
info: {
item_type: item_type,
item_id: item_id,
item_title: item_title,
reply_to: reply_to,
user_email: user_email,
user_name: user_name,
user_avatar: "",
user_note: "",
rate: 5,
title: title,
content: content,
files: "",
},
};
Hura.Ajax.post("customer", params).then(function (data) {
alert("Bạn đã gửi thành công");
location.reload();
});
}
}
function closeCommentBox() {
$('#newCommentBox').fadeOut();
}
function showCommentBox(id) {
var error = "";
var content = document.getElementById("content"+id).value;
if(content=='') error+= "Bạn chưa nhập nội dung\n";
if(error==''){
$('#newCommentBox').fadeIn();
}
else {
alert(error);
return false;
}
}
function check_field(id) {
var error = "";
var name = document.getElementById("name"+id).value;
var email = document.getElementById("email"+id).value;
if(name=='') error+= "Bạn chưa nhập tên\n";
if(email=='') error+= "Bạn chưa nhập email\n";
if(error==''){
return true;
}
else {
alert(error);
return false;
}
};
function check_field_review(id) {
var error = "";
var name = document.getElementById("review-name"+id).value;
var email = document.getElementById("review-email"+id).value;
var content = document.getElementById("review-content"+id).value;
if(name=='') error+= "Bạn chưa nhập tên\n";
if(email=='') error+= "Bạn chưa nhập email\n";
if(content=='') error+= "Bạn chưa nhập nội dung\n";
if(error==''){
return true;
}
else {
alert(error);
return false;
}
};
function postReview(id,reply) {
if(check_field_review(id)==false) return false;
var reply_to = id;
var user_name = $("#review-name"+id).val();
var user_email = $("#review-email"+id).val();
var content = $("#review-content"+id).val();
var params = {
action_type: "review-reply",
type :"ajax",
info : {
item_type : 'product',
item_id : '{{ page.product_info.productId }}',
item_title : `{{ page.product_info.productName }}`,
reply_to : reply_to,
user_email : user_email,
user_name : user_name,
user_avatar : '',
user_note : '',
rate : 5,
title : `{{ page.product_info.productName }}`,
content : content,
files : ''
}
}
Hura.Ajax.post('customer', params).then(function (data) {
alert("Bạn đã gửi thành công");
location.reload();
})
};
function formatDate(a) {
var a = new Date(parseInt(a) * 1000);
var year = a.getFullYear();
var month = a.getMonth() + 1;
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
// var time = date + '/' + month + '/' + year + ' ' + hour + ':' + min + ':' + sec ;
var time = date + "/" + month + "/" + year;
return time;
}
function closeFormCommentInput() {
$(".form-input").hide();
}
function showFormReply(a) {
$("#" + a).show();
}
function showReplyForm(id){
var element = $("#reply-comment-"+id);
$("#reply-comment-"+id).toggle();
}
function closeCommentFormInput(a){
$(a).hide();
}
// TIN MỚI NHẤT
function getArticleProductDetail() {
var params = {
action_type: "featured",
type: "article",
show: 18,
};
var target = "#js-artilce-product-detail";
Hura.Ajax.get("article", params).then(function (data) {
var html = Hura.Template.parse(artilceProductDetail, data.splice(0, 4));
Hura.Template.render(target, html);
});
}
// POST PRODUCT HISTORY
var ITEM_TYPE = 'product';
var ITEM_ID = '{{ page.product_info.productId }}';
var ITEM_NAME = `{{ page.product_info.productName }}`;
var VARIANT_SELECTED = {};
// SWICH BOTTOM PRODUCT BOX
// SWICH BOTTOM PRODUCT BOX
function switchBottomProductBox() {
$(".related-products").on("click", function () {
$(this).toggleClass("current");
$(this).siblings().removeClass("current");
});
}
switchBottomProductBox();
// GET PRODUCT RELATIVE
function getRelativeProduct() {
var categoryID = parseInt($('.section-details').attr('data-item_category-id'));
var params = {
action_type: "product-list",
category: categoryID,
};
var target = "#js-bottom-product-box";
Hura.Ajax.get("product", params).then(function (data) {
//console.log(data.list)
var currentProductID = parseInt($('.section-details').attr('data-item_id'));
var newDataList = data.list.filter(item => item.id !== currentProductID);
if (data.list.length > 0) {
var html = Hura.Template.parse(productTpl, newDataList);
Hura.Template.render(target, html);
tooltip();
} else {
$("#js-bottom-product-box").html(`<p class="alert-mess">Sản phẩm đang cập nhập</p>`)
}
resetBottomBoxDetails();
});
}
getRelativeProduct();
// GET PRODUCT HISTORY
function getProductHistory() {
Hura.Ajax.post('user', { action_type: 'product-view-history' }).then(function (data) {
var target = '#js-bottom-product-box';
var html = Hura.Template.parse(productTpl, data.list);
Hura.Template.render(target, html);
resetBottomBoxDetails();
tooltip();
})
}
function resetBottomBoxDetails() {
$(".swiper-wrapper").css("display", "none");
setTimeout(function () {
$(".swiper-wrapper").css("display", "flex");
}, 100)
}
resetBottomBoxDetails();
// SWIPER BOTTOM PRODUCT BOX
function productBottomBoxSwiper() {
new Swiper(".bottom-product-box-swiper", {
slidesPerView: 5,
spaceBetween: 20,
rewind: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
breakpoints: {
// when window width is >= 1600px
1600: {
slidesPerView: 6,
},
},
});
}
productBottomBoxSwiper();
// CẤU HÌNH : KÍCH THƯỚC, DUNG LƯỢNG, MÀU SẮC
function _setVariantColor() {
$('#js-variant-holder .js-variant-option-value').each(function () {
var variant_key = $(this).attr('data-key');
if (variant_key === 'mau-sac') {
$(this).addClass('js-variant-color');
}
});
$('.js-variant-color').each(function () {
var data_color = $(this).attr('data-value').substring(0, 7);
$(this).css('background', data_color)
});
}
_setVariantColor();
function _changePriceVariant() {
$('.js-variant-option-value').click(function () {
setTimeout(function () {
var data = JSON.parse($('#js-variant-holder input[type="hidden"]').val());
var price = parseInt(data.current_price);
var marketPrice = parseInt($('.bk-product-marketPrice').attr("value"));
var variantStock = data.current_stock;
var variantValue = data.label;
//console.log(data, price, marketPrice, variantValue)
$('.js-variant-label').attr("data-label", variantValue);
getVariantLabel();
var variantName = $('.js-variant-label').html();
$('.bk-check-out-of-stock').attr("value", variantStock);
if (variantStock > 0) {
$('.js-variant-price').html(formatCurrency(price) + ' <u>đ</u>');
$('.bk-product-price').html(price);
} else {
$('.js-variant-price').html("Hết hàng");
}
$('.bk-product-property').val(variantName)
$('.js-variant-name').html(' - (' + variantName + ')');
if (marketPrice > price && price > 0) {
var price_off = 100 - price / marketPrice * 100;
$('.js-price-off').html('(-' + formatCurrency(price_off) + '%)');
$('.js-variant-marketPrice').show();
} else {
$('.js-variant-marketPrice').hide();
$('.js-price-off').hide();
}
// change image
let variant_image = data.image;
//console.log(variant_image);
if (variant_image != '') {
$('.gallery-thumbs .swiper-slide').each(function (index) {
var slideThumbsSrc = $(this).children().attr("src");
if (variant_image === slideThumbsSrc) {
//console.log(index);
galleryTop.slideTo(index, 500, true);
}
});
}
}, 100);
});
//$('.js-variant-option-value:first-child').click();
}
_changePriceVariant()