<!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/GoodsLayoutMob">
<!--
 *******************************************************************************
 * @source  : cartListFormMob
 * @desc    : 장바구니
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.04.05   xodud1202   최초 작성
 *******************************************************************************
 -->
<body>
<th:block layout:fragment="content">

	<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>
	<script type="text/javascript" th:src="${@environment.getProperty('naverPay.button.mobile.js.url')}" src="" charset="UTF-8"></script>
	<form id="nPayForm" name="nPayForm"></form>

	<main role="" id="" class="container od">
		<section class="content shopping_bag" id="cartAjaxList">
			<!-- 장바구니 내용 -->
		</section>

		<div class="inner" style="margin-top:10px;">
			<th:block th:if="${sessionInfo != null and (sessionInfo.custId == 'xodud1202' or sessionInfo.custId == 'jsh77b' or sessionInfo.custId == 'card007')}">
				<th:block th:with="buttonKey=${@environment.getProperty('naverPay.button.key')}">
					<script th:inline="javascript">
						if(!wcs_add) var wcs_add = {};
						wcs_add["wa"] = "[[${@environment.getProperty('naverPay.common.certification.key')}]]";
						wcs.inflow("style24.com");
						wcs_do();
					</script>

					<script type="text/javascript" >
						/*버튼설정*/
						naver.NaverPayButton.apply({
							BUTTON_KEY              : "[[${buttonKey}]]",       // 네이버페이에서 제공받은 버튼 인증 키 입력
							TYPE                    : "MA",                      // 버튼 모음 종류 설정
							COLOR                   : 1,                        // 버튼 모음의 색 설정
							COUNT                   : 1,                        // 버튼 개수 설정. 구매하기 버튼만 있으면(장바구니 페이지) 1, 찜하기 버튼도 있으면(상품 상세 페이지) 2를 입력.
							ENABLE                  : "Y",                      // 품절 등의 이유로 버튼 모음을 비활성화할 때에는 "N" 입력
							BUY_BUTTON_HANDLER      : buy_nc,                   // 구매하기 버튼 이벤트 Handler 함수 등록, 품절인 경우 not_buy_nc 함수 사용
							"":""
						});
						
						/*네이버구매하기*/
						function buy_nc() {
							// 자사 일반 상품 정보
							let cartSqArr = [];
							
							$("#cartListForm .cartInfo").each(function(idx, item) {
								if ($(item).find('input[name=cartSqArr]').is(':checked')) {
									cartSqArr.push($(item).find('input[name=cartSqArr]').val());
								}
							});
							
							// 네이버페이 주문형 결제
							buy_nc_req(cartSqArr);
							
							return false;
						}
						
						function buy_nc_req(cartSqArr) {
							let data = {  cartSqArr : cartSqArr
								, backUrl : location.href
								, goodsUrl : _PAGE_GOODS_DETAIL
							};
							let jsonData = JSON.stringify(data);
							
							$.ajax( {
								type		: "POST",
								url 		: "/pg/nPayReq",
								dataType 	: 'json',
								data		: jsonData,
								beforeSend : function(xhr, settings) {
									xhr.setRequestHeader("AJAX"			, "true");
									xhr.setRequestHeader('Accept'		, 'application/json');
									xhr.setRequestHeader('Content-Type'	, 'application/json');
								},
								error: function(xhr, status, error) {
									mcxDialog.alert(status + '; ' + error);
								},
								success : function(result) {
									if (result.state == "sucess") {
										enp('create', 'conversion', 'is24', { device: 'M', paySys: 'naverPay' });	// 모비온 네이버주문형 클릭시
										document.nPayForm.action = result.npayOrderUrl + "/" + result.orderKey + "/" + result.resultNo;
										document.nPayForm.submit();
									} else {
										mcxDialog.alert(result.message);
									}
								}
							});
						}
						
						<!-- 구매불가 -->
						function not_buy_nc() {
							mcxDialog.alert("죄송합니다. 네이버페이로 구매가 불가한 상품입니다.");
							return false;
						}
					</script>
				</th:block>
			</th:block>
		</div>

		<th:block th:if="${cartSize>0}">
			<div class="od_recommend" style="background-color:white;">
				<h3>추천상품</h3>
				<div class="swiper-container item_list swiper-container-initialized swiper-container-horizontal swiper-container-ios">
					<div class="swiper-wrapper" style="transform: translate3d(0px, 0px, 0px);">
						<th:block th:each="cart, status : ${recomGoodsList}">
							<div class="swiper-slide swiper-slide-active" style="width: 163.5px; margin-right: 8px;">
								<div class="item_prod"> <!-- item_prod ranker d_detail -->
									<div class="item_state"> <!-- item_state AD soldout -->
										<button type="button" class="itemLike" onclick="cfnPutWishList(this);" th:attr="goodsCd=${cart.product.itemId}, goodsNm=${cart.product.itemName}, ithrCd='IN18_01', contentsLoc='', planDtlSq=''">관심상품 추가</button>
										<a th:href="${cart.product.itemUrl}" class="itemLink">
											<div class="itemPic">
												<img class="vLHTC pd_img" th:src="${cart.product.itemImage}" src="" alt="">
											</div>
											<p class="itemBrand" th:text="${cart.product.brandName}"></p>
											<div class="itemName" th:text="${cart.product.itemName}"></div>
											<p class="itemPrice">
												<span class="itemPrice_original" th:if="${cart.product.salePrice < cart.product.originalPrice}" th:text="${#numbers.formatInteger(cart.product.originalPrice, 1, 'COMMA')}">89,000</span>
												<span th:text="${#numbers.formatInteger(cart.product.salePrice, 1, 'COMMA')}"></span>
												<span class="itemPercent" th:if="${cart.product.salePrice < cart.product.originalPrice}" th:text="${#numbers.formatInteger(100 - ((cart.product.salePrice / cart.product.originalPrice) * 100), 1, 'COMMA') + '%'}">10%</span>
											</p>
										</a>
									</div>
								</div>
							</div>
						</th:block>
					</div>
					<span class="swiper-notification" aria-live="assertive" aria-atomic="true"></span>
				</div>
			</div>
		</th:block>

		<th:block th:if="${cartSize == null or cartSize == 0}">
			<div class="od_liveview" style="background-color:white;">
				<h3>지금 많이 보고 있어요</h3>
				<div class="swiper-container item_list">
					<div class="swiper-wrapper">
						<th:block th:each="cart, status : ${recomGoodsList}">
							<div class="swiper-slide">
								<div class="item_prod">
									<div class="item_state">
										<a th:href="${cart.itemUrl}" class="itemLink">
											<div class="itemPic">
												<img alt="BLACK-a" class=" vLHTC pd_img" th:src="${cart.imageUrl}" src="">
											</div>
											<div class="itemName" th:text="${cart.itemName}"></div>
											<div class="viewComment" th:text="${cart.count < 10 ? '10명 미만' : cart.count + '명 보는중'}"></div>
										</a>
									</div>
								</div>
							</div>
						</th:block>
					</div>
				</div>
			</div>
		</th:block>
 		
		<!-- 옵션변경_팝업01 -->
		<div id="optModifyPop01" class="popup_box optModifyPop optModifyPop01">
			<div class="lap">
				<div class="popup_close">카테고리닫기</div>
				<div class="popup_head">
					<h2>옵션변경</h2>
				</div>
				<div class="popup_con"></div>
			</div>
		</div>
		<!-- //옵션변경_팝업01 -->

		<!-- 옵션변경_팝업02 -->
		<div id="optModifyPop02" class="popup_box optModifyPop optModifyPop02">
			<div class="lap">
				<div class="popup_close">카테고리닫기</div>
				<div class="popup_head">
					<h2>옵션변경</h2>
				</div>
				<div class="popup_con"></div>
			</div>
		</div>
		<!-- //옵션변경_팝업02 -->

		<!-- 다다익선 할인 대상_팝업 -->
		<div id="moresalePop" class="popup_box moresalePop" style="display: none;"></div>
		<!-- //다다익선 할인 대상_팝업 -->

		<!-- 배송비 SAVE_팝업 -->
		<div id="dlvrSavePop" class="popup_box dlvrSavePop" style="display: none;"></div>
		<!-- //배송비 SAVE_팝업 -->

		<!-- 옵션변경 팝업 -->
		<div id="optModifyPop01" class="popup_box optModifyPop optModifyPop01"></div>
		<!-- //옵션변경 팝업 -->
	</main>

	<script src="/ux/mo/js/swiper.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/ux/mo/css/swiper.min.css" />

<script th:inline="javascript">
	$(document).ready(function(){
		// 바텀바 제거
		$("nav#tabbar").hide();
		$("nav#tabbar").removeClass("tabbar");
		$("nav#tabbar").empty();

		// 1. 타이틀설정
		$("#htopTitle").text("쇼핑백");

		// 장바구니 상품 정보 select
		getCartList();

		// 로그인 되어 있을 경우 체크
		if("[[${cartSize}]]" == "" || "[[${cartSize}]]" == "0") {
			if(cfCheckLogin()) {
				// 장바구니 보유 상품 없을 경우 추천솔루션 > "지금 많이 보고있어요" 영역
				let targetT = $('.container>.od_realtime').find('.item_state').find('button');
				targetT.each(function(){
					let goodsCd = $(this).attr('goodscd');
					var $this = $(this);
					let url = "/mypage/wish/list/check/"+goodsCd;
					var result = '';
					$.ajax({
						type: 'get'
						, async: false
						, url: url
						, success: function (data) {
							//likeit active
							if ("Y" == data){
								$this.addClass('likeit').addClass('active');
							}
						}
					});
				});
			}
		} else {
			if(cfCheckLogin()) {
				// 장바구니 보유 상품 없을 경우 추천솔루션 > "지금 많이 보고있어요" 영역
				let targetT = $('.container>.od_recommend').find('.item_state').find('button');
				targetT.each(function(){
					let goodsCd = $(this).attr('goodscd');
					var $this = $(this);
					let url = "/mypage/wish/list/check/"+goodsCd;
					var result = '';
					$.ajax({
						type: 'get'
						, async: false
						, url: url
						, success: function (data) {
							//likeit active
							if ("Y" == data){
								$this.addClass('likeit').addClass('active');
							}
						}
					});
				});
			}
		}

		//추천상품_슬라이드
		var od_recommend_slide = new Swiper('.od_recommend .swiper-container', {
			slidesPerView: 2,
			spaceBetween: 8,
			centerMode: true
		});

		//추천상품_슬라이드
		var od_liveview_slide = new Swiper('.od_liveview .swiper-container', {
			slidesPerView: 3,
			spaceBetween: 8,
			centerMode: true,
		});

		//배송요청사항
		// var my_deilivery_selecter = new sCombo('.my .ship_request .select_custom');

		//상품옵션변경 팝업 > 컬러선택 표기
		$(document).on('click','.optModifyPop .opt_color ul li a',function(e){
			$(this).parents('.opt_color').find('li a').removeClass('on');
			$(this).addClass('on');
			var optColor = $(this).find("img").attr('alt');
			$(this).parent().parent().parent().find(".info").text(optColor);
			return false;
		});

		//상품옵션변경 팝업 > 컬러선택 표기
		$(document).on('change','input[name=shotDelvUseYn]',function(e){
			let data = {shotDelvUseYn : $("input[name=shotDelvUseYn]:checked").val()};
			getCartList(data);
		});

		//옵션변경_팝업01
		$(document).on("click", ".btn_option_pop01", function(){
			//$("#optModifyPop01 .popup_con").load("popup_optModify01.html");
			/*$('#optModifyPop01').show().addClass("active");
			$("body").css({"overflow":"hidden"});*/
		});

		//옵션변경_팝업02
		$(document).on("click", ".btn_option_pop02", function(){
			//$("#optModifyPop02 .popup_con").load("popup_optModify02.html");
			$('#optModifyPop02').show().addClass("active");
			$("body").css({"overflow":"hidden"});
		});

		//팝업_닫기
		$(document).on("click", ".popup_close", function(){
			$('.popup_box').hide();
			$('.popup_box').removeClass('active');
			$("body").css({"overflow":"visible"});
		});

		//수량조절 이벤트
		$(document).on('click','.optModifyPop01 .number_count .minus',function(e){
			var $input = $(this).parent().find('input');
			var count = parseInt($input.val()) - 1;
			var minOrdQty = $(this).parent().parent().find(".minOrdQty").val();

			count = count < minOrdQty ? minOrdQty : count;
			$input.val(count);
			$input.change();
			//주문 최소 수량 이하 감소버튼 비활성화
			if ($input.val() == minOrdQty) {
				$('.optModifyPop01 .number_count .minus').addClass('min_val');
			}

			$('.optModifyPop01 .number_count .plus').removeClass('min_val');

			return false;
		}).on('click','.optModifyPop01 .number_count .plus',function(e){
			var $input = $(this).parent().find('input');
			var count = parseInt($input.val()) + 1;
			var maxOrdQty = $(this).parent().parent().find(".maxOrdQty").val();

			count = count > maxOrdQty ? maxOrdQty : count;
			$input.val(count);
			$input.change();

			//주문 최대 수량 이상 증가버튼 비활성화
			if ($input.val() == maxOrdQty) {
				$('.optModifyPop01 .number_count .plus').addClass('min_val');
			}

			$('.optModifyPop01 .number_count .minus').removeClass('min_val');

			return false;
		}).on('keyup','.optModifyPop01 .number_count input[type=text]',function(e){
			var minOrdQty = $(this).parent().parent().find(".minOrdQty").val();
			var maxOrdQty = $(this).parent().parent().find(".maxOrdQty").val();

			$(this).val($(this).val().replace(/[^0-9]/g,""));

			if(Number($(this).val()) < Number(minOrdQty)) {
				$(this).val(minOrdQty);
				$('.optModifyPop01 .number_count .minus').addClass('min_val');
				$('.optModifyPop01 .number_count .plus').removeClass('min_val');
			}
			if(Number($(this).val()) > Number(maxOrdQty)) {
				$(this).val(maxOrdQty);
				$('.optModifyPop01 .number_count .plus').addClass('min_val');
				$('.optModifyPop01 .number_count .minus').removeClass('min_val');
			}
		});

		//팝업 - 쿠폰사용안내
		$(document).on('click','#btn_couponInfo_pop',function(e){
			//$("#couponInfoPop .modal-content").load("popup_couponInfo.html");
			$("#couponInfoPop").modal("show");
			return false;
		});
		$("#couponInfoPop_close").on("click", function() {
			$("#couponInfoPop").modal("hide");
		});

		// 자사 일반 상품 사이즈 선택시
		$(document).on("change", ".selfGoodsSize input[type=radio]", function() {
			let addPrice = $(this).parent().find("input[name=addPrice]").val();
			let sizeTextHtml = "<span>" + $(this).parent().find(".sizeNameTxt").text() + "</span>";
			if(addPrice > 0) {
				sizeTextHtml += "<span>(+<em>" + Number(addPrice).toLocaleString() + "</em>)원</span>";
			}
			$(this).parent().parent().parent().find(".opt_header>.info").html(sizeTextHtml);
		});

		// 자사 일반 상품 컬러 선택시
		$(document).on("click", ".selfGoodsColorSelect", function(e) {
			let sizeHtml = "";
			let imgHtml = "";
			let color =  getSelfColorList();
			let optCd1 = $(this).attr("data");

			for(let i = 0 ; i < color.length ; i++) {
				let size = color[i].cartSizeList;
				for(let j = 0 ; j < size.length ; j++) {
					if(optCd1 == size[j].optCd1) {
						sizeHtml += "<div>";
						sizeHtml += "<input type='hidden' name='addPrice' value='" + size[j].addPrice + "' />";
						sizeHtml += "<input type='radio' name='rdi-optsize' id='rdi-optsize" + size[j].goodsCd + "-" + size[j].optCd + "' value='" + size[j].optCd + "' ";
						if(size[j].soldoutYn == "Y" || size[j].minOrdQty > size[j].currStockQty) {
							sizeHtml += "disabled = 'disabled'";
						}
						sizeHtml += " />\n";
						sizeHtml += "<label for='rdi-optsize" + size[j].goodsCd + "-" + size[j].optCd + "'><span class='sizeNameTxt'>" + size[j].optCd2 + "</span></label>\n"
						sizeHtml += "</div>\n";
					}
				}

				if(optCd1 == color[i].optCd1) {
					for (let j = 0; j < color[i].cartImgList.length; j++) {
						let img = color[i].cartImgList[j];
						if(optCd1 == img.colorCd && img.defaultImgYn == "Y") {
							imgHtml += '<img src="' + _uploadGoodsUrl + "/" + img.sysImgNm + '?RS=100" onerror="' + _uximgUrl + '/images/pc/thumb/bg_item_none.png" alt="' + img.sysImgNm + '" />\n';
						}
					}
				}
			}

			$(".cartOptionModal .area_order .goods_section .goods_detail .thumb_box").html(imgHtml);
			$(".cartOptionModal .selfGoodsSize").html(sizeHtml);
			$(".cartOptionModal .opt_size .opt_header .info").html("");
		});
	});

	//배송비 SAVE_팝업
	function fnGetDelvFeeSaveGoods(delvFeeCd, delvFeeSaveGoodsAmt) {
		let param = new Object();
		param.delvFeeCd = delvFeeCd;
		param.delvFeeSaveGoodsAmt = delvFeeSaveGoodsAmt;

		gagajf.ajaxSubmit("/cart/delv/fee/save/goods/list", "html", "dlvrSavePop", param);
	};

	//다다익선 할인 대상_팝업
	function fnGetTmtbSalesGoods(obj) {
		// 파라미터
		let tmtbSqList = new Array();
		let param = new Object();

		// 다다익선 정보
		let qtyTmtbSq = $(obj).parent().parent().parent().parent().find("input[name=qtyTmtbSq]").val();
		let amtTmtbSq = $(obj).parent().parent().parent().parent().find("input[name=amtTmtbSq]").val();
		let qtyTmtbYn = $(obj).parent().parent().parent().parent().find("input[name=applyQtySectionYn]").val();
		let amtTmtbYn = $(obj).parent().parent().parent().parent().find("input[name=applyAmtSectionYn]").val();
		let goodsCd = $(obj).parent().parent().parent().parent().find("input[name=goodsCd]").val();

		if(qtyTmtbYn == "N") {tmtbSqList.push(Number(qtyTmtbSq));}
		if(amtTmtbYn == "N") {tmtbSqList.push(Number(amtTmtbSq));}
		if(tmtbSqList.length < 1) {mcxDialog.alert("적용가능한 다다익선이 없습니다."); return false;}

		let tmtb = JSON.stringify({goodsCd : goodsCd, arrTmtbSq : tmtbSqList});

		$.ajax( {
			type		: "POST",
			url 		: '/cart/tmtb/sales/goods/list',
			data		: tmtb,
			dataType 	: 'html',
			beforeSend : function(xhr, settings) {
				xhr.setRequestHeader("AJAX"			, "true");
				xhr.setRequestHeader('Accept'		, 'application/json');
				xhr.setRequestHeader('Content-Type'	, 'application/json');
			},
			success 	: function(result) {
				$("#moresalePop").html(result);
			}
		});
	};

	function getCartList(parameter) {
		// 장바구니 정보 조회
		$.ajax( {
			type: "POST",
			url : '/cart/goods/list',
			data : parameter,
			dataType : 'html',
			success : function(result) {
				if (result != null) {
					$("#cartListForm").remove();
					$("#cartAjaxList").html(result);
				}
			}
		});
	}
</script>
<!--네이버페이 전환스크립트를 이용하여 전환값 설정-->
<script th:inline="javascript">
	var _nasa={};
	if (window.wcs) _nasa["cnv"] = wcs.cnv("3","[[${loginCustNo}]]");
</script>
<!--위 스크립트를 통해 설정된 전환값과 본 페이지의 로그를 서버에 전송-->
<script th:inline="javascript">
	if (!wcs_add) var wcs_add = {};
	wcs_add["wa"] = "[[${@environment.getProperty('naverPay.common.certification.key')}]]";
	if (!_nasa) var _nasa = {};
	if (window.wcs) {
		wcs.inflow("style24.com");
		wcs_do(_nasa); //서버로 로그 전송
	}
</script>
</th:block>

</body>
</html>
