<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="web/common/layout/DefaultLayoutWeb">
<!--
 *******************************************************************************
 * @source  : SocialMainFormWeb.html
 * @desc    : 소셜메인(핫딜메인) Page
 *============================================================================
 * Pastelmall
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.3.11     sowon     최초 작성
 *******************************************************************************
 -->
<body>
<th:block layout:fragment="content">
	<!--  container -->
	<div id="container" class="container dp">
		<div class="breadcrumb"> 
			<ul>
				<li class="bread_home"><a href="javascript:void(0);" onclick="cfnGoToPage(_PAGE_MAIN);">홈</a></li>
				<li class="bread_2depth">핫딜</li>
			</ul> 
		</div>
		<div class="wrap">
				<div class="nodata" style="display: none;">
					<div class="txt_box">
						<p>진행하는 핫딜이 없습니다.</p>
					</div>
					<div class="btn_box">
						<button class="btn btn_default" onclick="cfnGoToPage(_PAGE_MAIN);">
							<span>홈으로 가기</span>
						</button>
					</div>
				</div>
			<th:block th:if="${socialInfo != null}">
			<div id="socialDiv" style="display: none;">
				<div class="content wide dp_hotdeal"> <!-- 페이지특정 클래스 = dp_hotdeal -->
					<div class="cont_body">
						<div class="hotdeal">
							<img th:src="${@environment.getProperty('domain.uximage')} + '/images/pc/thumb/hotdeal_bg2.jpg'" alt="핫한 아이템을 핫한 가격에 LAST DAY DEAL">
							<div id="countdown">
								<span id="h-hours"></span>
								<span id="h-minutes"></span>
								<span id="h-seconds"></span>
							</div>
						</div>
						<div class="list_content">
							<div class="itemsGrp rowtype"> <!-- itemsGrp rank hot deal --> <!-- rowtype 추가시 가로형태로 출력 -->
								<section id="infiniteContainer">
									<div id="listBoxOuter">
										<ul id="listBox">
										</ul>
									</div>
								</section>
							</div>
							<div class="last_page" id="divLastPage" style="display: none;">
								<span>마지막 페이지입니다.</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</th:block>
	</div>
</div>
<form id="socialForm" name="socialForm" action="#" th:action="@{'/social/list'}">
	<input type="hidden" name="pageNo" id="pageNo" value ="1"/>
	<input type="hidden" name="pageSize" value ="50"/>
</form>
<script src="/ux/plugins/gaga/gaga.infinite.scrollSession.js"></script>
<script src="/ux/plugins/jquery/jquery.history.min.js"></script>
<script th:inline="javascript">
let socialInfo = [[${socialInfo}]];


var socialAddCart = function (obj) {

	let btnType = "C";
	let params = [];

	let cart = new Object();
    cart.goodsCd = $(obj).attr("goodsCd");
	cart.optCd = $(obj).attr("optCd");
	cart.goodsQty = $(obj).attr("minOrdQty");
	cart.goodsType = $(obj).attr("goodsType");
	cart.cartGb = btnType;
	cart.afLinkCd = $(obj).attr("afLinkCd");
	cart.ithrCd = "";
	cart.contentsLoc =  "";
	cart.planDtlSq = "";
	params.push(cart); 
	
	// 장바구니담기
	if (params.length > 0){
		cfnAddCart(params);	
	} 
}

var socialSetAddCart = function (obj) {

	let cartGoodsList = [];
	var optCdArr = $(obj).attr("optCd").split(",");
	var compsGoodsCdArr = $(obj).attr("compsGoodsCd").split(",");

	let compsList = [];
	let goodsList = {
	cartCompsList : new Array()
	}

	for(let j = 0 ; j <  optCdArr.length ; j++) { 
		let temp = new Object;
		temp.goodsCd = $(obj).attr("goodsCd");
		temp.optCd = optCdArr[j];
		temp.goodsQty = $(obj).attr("minOrdQty");
		temp.goodsType = "G056_S";
		temp.itemCd =  compsGoodsCdArr[j];
		temp.cartGb = "C";
		temp.afLinkCd = $(obj).attr("afLinkCd");
		temp.ithrCd = "";
		temp.contentsLoc = "";
		temp.planDtlSq = "";
		compsList.push(temp);
	}  

	goodsList.cartCompsList = compsList;
	cartGoodsList.push(goodsList);
	cfnAddCart(cartGoodsList);
}

let fnGetSocialList = function(result) {
	var html = '';

	$.each(result.dataList, function(idx, item) {
		
		html += ' <div class="item_prod">\n';
		if (item.stockQtySum > 0 || item.stockQtySum == null) {
			html += '    <div class="item_state">\n';
		}else{
			html += '    <div class="item_state soldout">\n';
		}
		if (item.likeIt == 'likeit') {
			html += '        <button type="button" class="itemLike active" onclick="cfnPutWishList(this);" goodsCd=\''+item.goodsCd+'\', goodsNm=\'' + item.goodsNm + '\', ithrCd=\'\', contentsLoc=\'\', planDtlSq=\'\'>관심상품 추가</button>\n';
		}else{
			html += '        <button type="button" class="itemLike" onclick="cfnPutWishList(this);" goodsCd=\''+item.goodsCd+'\', goodsNm=\'' + item.goodsNm + '\', ithrCd=\'\', contentsLoc=\'\', planDtlSq=\'\'>관심상품 추가</button>\n';
		}
		
		html += '        <a href="javascript:void(0);" class="itemLink" onclick="cfnGoToGoodsDetail(\''+item.goodsCd+'\',\'\',\'IN11_01\')" >\n';
		html += '            <div class="itemPic">\n';
		html += '                <img alt="BLUE-a" class=" vLHTC pd_img" src="'+ _uploadGoodsUrl +'/'+item.sysImgNm +'?RS=550">\n';
		html += '            </div>\n';
		html += '            <div class="itemSpecialPrice"><span>특가</span></div>\n';
		html += '            <p class="itemBrand">'+item.brandGroupNm+'</p>\n';
		if(item.goodsTnm != null){
			html += '           <div class="itemComment">'+item.goodsTnm+'</div>\n';
		}
		html += '            <div class="itemName">'+item.goodsNm+'</div>\n';
		html += '            <p class="itemPrice">\n';
		html += item.currPrice.addComma() +'원';
		if (item.currPrice != item.listPrice) {
			html += '                <span class="itemPrice_original">'+item.listPrice.addComma()+'원</span>\n';
		}
		if (item.dcRate != 0) {
			html += '                                 <span class=" itemPercent">'+item.dcRate.addComma()+'%</span>\n';
		}
		html += '            </p>\n';
		
		html += '        </a>\n';
		if (item.goodsType == 'G056_N') {
			html += '        	 <div class="shopBagBtn">\n';
			html += '                <button type="button" class="btn btn_defalt" onclick="socialAddCart(this)" goodsCd=\''+item.goodsCd+'\', minOrdQty=\''+item.minOrdQty+'\', goodsType=\''+item.goodsType+'\', optCd=\''+item.optCd+'\'">\n';
			html += '                    <span>쇼핑백 담기</span>\n';
			html += '                </button>\n';
			html += '            </div>\n';
		}else if(item.goodsType == 'G056_D'){
			html += '        	 <div class="shopBagBtn">\n';
			html += '                <button type="button" class="btn btn_defalt" onclick="socialGoodsDeal()">\n';
			html += '                    <span>쇼핑백 담기</span>\n';
			html += '                </button>\n';
			html += '            </div>\n';
		}else{
			html += '        	 <div class="shopBagBtn">\n';
			html += '                <button type="button" class="btn btn_defalt" onclick="socialSetAddCart(this)" compsGoodsCd=\''+item.compsGoodsCd+'\', goodsCd=\''+item.goodsCd+'\', minOrdQty=\''+item.minOrdQty+'\', goodsType=\''+item.goodsType+'\', optCd=\''+item.optCd+'\'">\n';
			html += '                    <span>쇼핑백 담기</span>\n';
			html += '                </button>\n';
			html += '            </div>\n';
		}
		html += '    </div>\n';
		html += '</div>\n';
	});
	return html;
	
}
// 딜상품일 경우 alert
var socialGoodsDeal = function() {
	mcxDialog.alert("해당 상품은 옵션 선택 후 쇼핑백 담기가 가능합니다.");
	return;
}

var fnSocialListSearch = function() {
	fnSocialInfiniteScrollInit();
	gagaInfiniteScroll.getHistory();
}
// 인피니트 스크롤 초기화
var fnSocialInfiniteScrollInit = function(){
	sessionStorage.removeItem(document.location.href);
	//History 초기화
	$("#listBox").html("");
}

var totalCnt = 0;
var idx = 1;
//인피니트 스크롤 이벤트 발생 시 데이터 가져오기
var fnGetInfiniteScrollDataList = function(pageNum) {
	$("#socialForm input[name=pageNo]").val(pageNum+1);
	
	if(idx==1 || totalCnt > Number($("#socialForm").find("input[name=pageSize]").val())){
		idx++;
		gagajf.ajaxFormSubmit("/social/list",document.socialForm, gagaInfiniteScroll.jsonToHtml);
	}
	
}

var fnDrawInfiniteScrollData = function (result){
	totalCnt = result.totalCnt;
	gagaInfiniteScroll.pageStatus.totalCount = result.totalCnt;

	if (result.dataList != null && result.dataList.length > 0) {
		$(".nodata").hide();	
		$("#socialDiv").show();	
		let lastPage = result.paging.pageable.pageNo;
		let endRow = result.endRow - result.paging.pageable.pageSize;
		
		var htm = fnGetSocialList(result, lastPage, endRow);
		gagaInfiniteScroll.draw(htm);
	}else{
		if($("#socialForm input[name=pageNo]").val()==1){
			$(".nodata").show();	
			$("#socialDiv").hide();	
		}
		$("#divLastPage").show();
		gagaInfiniteScroll.draw('not');
		
	}
}


$(function(){
	fnSocialListSearch();
       /* 핫딜 countDown */
    
       function hotdealTimer() {
    	   		var endTime = socialInfo.socialEddt.toDate("YYYYMMDD");
           //var endTime = new Date(socialInfo.socialEddt); // 남은시간 지정

               endTime = (Date.parse(endTime) / 1000);
console.log(endTime);
               var now = new Date();
               now = (Date.parse(now) / 1000);

               var timeLeft = endTime - now;

               var days = Math.floor(timeLeft / 86400); 
               var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
               var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
               var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

               if (hours < '10') { hours = '0' + hours; }
               if (minutes < '10') { minutes = '0' + minutes; }
               if (seconds < '10') { seconds = '0' + seconds; }

               //$('#d-days').html(days);
               $('#h-hours').html(hours);
               $('#h-minutes').html(minutes);
               $('#h-seconds').html(seconds);		
       }
       
     if (socialInfo != null) {
    	setInterval(function() { hotdealTimer(); }, 1000);
  	 }
       
       /* countDown */
});

/* $(window).on("pageshow", function(event) {
	if ( (event.originalEvent && event.originalEvent.persisted) || (window.performance && window.performance.navigation.type == 2)) {
		var historyData = sessionStorage.getItem(document.location.href);
		if(historyData!=null){
			historyData = JSON.parse(historyData);
		}else{
			historyData = {};
		}
		fnSocialListSearch();
	}else{

		fnSocialListSearch();
	}
});
 */


</script>
</th:block>

</body>
</html>