<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="mob/common/layout/DefaultLayoutMob">
<!--
 *******************************************************************************
 * @source  : SocialMainFormMob.html
 * @desc    : 핫딜(소셜) Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.04.12   sowon     최초 작성
 *******************************************************************************
 -->
<body>
<th:block layout:fragment="content">
<main role="" id="" class="container dp">
			<section class="content dp_hotdeal">
				<div class="inner" id="topInner" style="display:none;">
					<div class="list_content"> <!-- 데이터 없을시 클래스 nodata 추가 -->
						 <div class="list_defult" style="display: none;" id="noData">
	                         <div>
	                             <p>진행하는 핫딜이 없습니다.</p>
	                         </div>
	                        <button type="button" class="btn btn_default" onclick="cfnGoToPage(_PAGE_MAIN);"><span>홈으로 가기</span></button>
	                    </div>
					</div>
				</div>
			<div id="socialDiv">
			<th:block th:if="${socialInfo != null}">
				<div class="inner wide">
                    <div class="hotdeal">
                        <div id="countdown">
                            <span>남은시간 </span>
                            <span id="h-hours"></span>
                            <span id="h-minutes"></span>
                            <span id="h-seconds"></span>
                        </div>
                    </div>
                </div>
                <div class="inner">
                    <div class="list_content">
						<div class="itemsGrp rowtype"><!-- itemsGrp rank hot deal --> <!-- rowtype 추가시 가로형태로 출력 -->
							<div class="list_content">
								<div class="itemsGrp" id="listBox">
								</div>
							</div>
							<div class="list_last" id="divLastPage" style="display: none;">마지막페이지 입니다.</div>
						</div>
                    </div>
				</div>
			</th:block>
			</div>
			</section>
		</main>
<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) {
		if (item.stockQtySum == 0) {
		html += '<div class="item_prod sold_out">';
		}else{
			html += '<div class="item_prod">';
		}
		html += '    <div class="item_state"> ';
		if (item.likeIt == 'likeit') {
			html += '        <button type="button" class="itemLike likeit " onclick="cfnMoPutWishList(this);" goodsCd=\''+item.goodsCd+'\', ithrCd=\'\', contentsLoc=\'\', planDtlSq=\'\'>관심상품 추가</button>';
		}else{
			html += '        <button type="button" class="itemLike" onclick="cfnMoPutWishList(this);" goodsCd=\''+item.goodsCd+'\', ithrCd=\'\', contentsLoc=\'\', planDtlSq=\'\'>관심상품 추가</button>';
		}
		html += '		<a href="javascript:void(0);" class="itemLink" onclick="cfnGoToGoodsDetail(\''+item.goodsCd+'\',\'\',\'IN11_01\')" >';
		html += '			<div class="shape ranker"><span>특가</span></div>';
		html += '			<div class="itemPic">';
		html += '				<img class="vLHTC pd_img" src="'+ _uploadGoodsUrl +'/'+item.sysImgNm +'">';
		html += '			</div>';
		html += '			<p class="itemBrand">'+item.brandGroupNm+'</p>';
		if(item.goodsTnm != null){
			html += '           <div class="itemComment">'+item.goodsTnm+'</div>';
		}
		html += '			<div class="itemName">'+item.goodsNm+'</div>';
		html += '			<p class="itemPrice">';
		if (item.currPrice != item.listPrice) {
			html += '                <span class="itemPrice_original">'+item.listPrice.addComma()+'</span>';
		}
		html += item.currPrice.addComma();
		if (item.dcRate != 0) {
			html += '                <span class=" itemPercent">'+item.dcRate.addComma()+'%</span>';
		}
		html += '			</p>';
		
		html += '		</a>';
		html += '			<div class="shopBag">';
		if (item.goodsType == 'G056_N') {
			html += '				<button class="btn btn_default" onclick="socialAddCart(this)" goodsCd=\''+item.goodsCd+'\', minOrdQty=\''+item.minOrdQty+'\', goodsType=\''+item.goodsType+'\', optCd=\''+item.optCd+'\'"><span>쇼핑백담기</span></button>';
		}else if(item.goodsType == 'G056_D'){
			html += '<button class="btn btn_default"  onclick="socialGoodsDeal()"><span>쇼핑백담기</span></button>';
		}else{
			html += '<button class="btn btn_default" onclick="socialSetAddCart(this)" compsGoodsCd=\''+item.compsGoodsCd+'\',goodsCd=\''+item.goodsCd+'\', minOrdQty=\''+item.minOrdQty+'\', goodsType=\''+item.goodsType+'\', optCd=\''+item.optCd+'\'"><span>쇼핑백담기</span></button>';
		}
		
		html += '			</div>';
		html += '	</div>';
		html += '</div>';

	});
	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();	
		$("#topInner").hide();
		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();	
			$("#topInner").show();
		}
		$("#divLastPage").show();
		gagaInfiniteScroll.draw('not');
		
	}
}

//사파리 - event.persisted || 크롬 - window.performance.navigation.type 이 1이면 새로고침, 2면 페이지 이동을 통한 캐쉬페이징
$(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();
	}
});

$(function(){
	fnSocialListSearch();
    /* 핫딜 countDown */
    function hotdealTimer() {
    		var endTime = socialInfo.socialEddt.toDate("YYYYMMDD");
   
            endTime = (Date.parse(endTime) / 1000); // nan
            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);		
    }
    setInterval(function() { hotdealTimer(); }, 1000);
    
    /* countDown */
});
</script>

</th:block>

</body>
</html>