<!DOCTYPE html>
<html lang="ko"
	  xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : LookbookBannerPickerPopupForm.html
 * @desc    : 룩북 배너 피커 팝업
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.03.09   bin2107     최초 작성
 *******************************************************************************
 -->
<div class="modalPopup" data-width="1600" data-height="850">
	<div class="panelStyle" style="overflow-y:scroll;">
		<form id="lbBannerPickerForm" name="lbBannerPickerForm" action="#" th:action="@{'/display/lookbook/banner/picker/save'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<input type="hidden" id="lookbookbSq" name="lookbookbSq" th:value="${lookbookbSq}"/>
			<div class="panelTitle">
				<h2 th:text="${'룩북 피커' + (mode == 'N' ? '등록' : '상세')}"></h2>
				<button type="button" class="close" onclick="uifnPopupClose('popupLookbookBannerPicker');"><i class="fa fa-times"></i></button>
			</div>
			<ul class="panelBar">
				<li  class="right">
					<button type="button" class="btn btnRight btn-success btn-lg" id="btnSavePicker">피커저장</button>
				</li>
			</ul>
			<div id="pickerDiv">
				<input type="hidden" name="uploadBannerUrl" id="uploadBannerUrl" th:value="${@environment.getProperty('upload.image.view') + '/lookbook/banner/'}"/>
				<!-- posistion picker -->
				<ul class="panelBar" id="pictureOffset"> <!--style="border-color: #dbdbdb;border-style: solid;border-width: 1px;"-->
					<li>
						<div class="picWrap">
							<div id="pickerBannerPreViewUrl" class="thumb" style="background-image:url('');"></div>
						</div>
					</li>
					<li>
						<ul class="notice padB15">
							<li>이미지를 클릭시 해당 위치의 <em>절대 좌표 값</em>을 가져옵니다.</li>
						</ul>
						<table class="frmStyle dataWrap">
							<colgroup>
								<col width="10%"/>
								<col/>
							</colgroup>
						</table>
					</li>
				</ul>
				<!-- //posistion picker -->
			</div>
		</form>
	</div>
</div>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	var lookbookbSq = [[${lookbookbSq}]];
	var imgNm = [[${imgNm}]];
	var mode = [[${mode}]];
	var lookbookBannerPickerList = [[${lookbookBannerPickerList}]];

	var $pic = $("#pictureOffset .picWrap");
	var absX = absY = 0; //위치 표시 단위(픽셀)
	var relX = relY = 0; //위치 표시 단위(퍼센트)
	var trIdx = 0;
	var idx = 0; //원 안의 숫자 count
	const picW = $pic.width(); //이미지 넓이
	const picY = $pic.height(); //이미지 높이

	$pic.on('click', function(e) {
		absX = e.pageX - $(this).offset().left; //left(px)
		absY = e.pageY - $(this).offset().top; //top(px)
		relX = ((absX / picW) * 100).toFixed(2); //left(%) : 소수점 둘째자리까지 표현
		relY = ((absY / picY) * 100).toFixed(2); //top(%) : 소수점 둘째자리까지 표현
		trIdx = trIdx+1; //ID
		idx = idx+1; //circle value

		//원 안에 숫자 표현
		let posTag = `<span data-id="${trIdx}" class="pos" style="left:${relX}%; top:${relY}%;"><i>${idx}</i></span>`;
		$pic.append(posTag);

		//테이블에 좌표정보 표현
		let trTag = `<tr data-id="${trIdx}" class="pickerTr">
						<th>${idx}</th>
						<td>
							<span>left <input type="text" name="xlim" value="${relX}" readonly="readonly"/><em class="per">%</em></span>
							<span>top <input type="text" name="ylim" value="${relY}" readonly="readonly"/><em class="per">%</em></span>
							<span>상품코드
								<input type="text" name="goodsCd" readonly="readonly"/>
								<button type="button" value="검색하기" class="btn btn-base btn-lg" onclick="fnSearchGoods(${idx});">상품조회</button>
							</span>
							<span class="btnDel"><button type="button" value="검색하기" class="btn btn-dark btn-lg" onclick="trDel(${trIdx}, ${idx})">삭제</button></span>
						</td>
					</tr>`;
		$(".dataWrap").append(trTag);
	});

	/* 좌표 삭제 */
	function trDel(trIdx, idx) {
		mcxDialog.confirm( idx + " 번을 삭제하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "삭제",
			sureBtnClick: function(){
				$( "[data-id="+trIdx+"]").remove();
			}
		});
	};

	/**
	 * 상품조회
	 */
	var addRowIdx;
	var fnSearchGoods = function (obj){
		addRowIdx = obj;
		cfnOpenGoodsPopup('fnAddLookbookBannerPickerGoods');
	}

	var fnAddLookbookBannerPickerGoods = function (result){
		//console.log('result.goodsCd::::::::::'+result[0].goodsCd);
		$("[data-id="+addRowIdx+"]").find("input[name=readGoodsCd]").val(result[0].goodsCd);
		$("[data-id="+addRowIdx+"]").find("input[name=goodsCd]").val(result[0].goodsCd);
		uifnPopupClose('popupGoods');
	}

	/**
	 * 저장
	 */
	$("#btnSavePicker").on('click', function(){
		//데이터 validation 체크
		// if(!dataValidation()){
		// 	return false;
		// }
		var optCheck = false;

		$(".pickerTr").each(function (i){
			if(gagajf.isNull($(this).find("input[name=xlim]").val())){
				optCheck = true;
				mcxDialog.alert((i+1)+'행의 left 값이 없습니다.');
				return false;
			}

			if(gagajf.isNull($(this).find("input[name=ylim]").val())){
				optCheck = true;
				mcxDialog.alert((i+1)+'행의 top 값이 없습니다.');
				return false;
			}

			if(gagajf.isNull($(this).find("input[name=goodsCd]").val())){
				optCheck = true;
				mcxDialog.alert((i+1)+'행의 상품코드 값이 없습니다.');
				return false;
			}
		});

		var pickerList = [];
		var pIdx = 0;
		$(".pickerTr").each(function(){
			var pickerInfo = {
				xlim : $(this).find("input[name=xlim]").val()
				,ylim : $(this).find("input[name=ylim]").val()
				,goodsCd : $(this).find("input[name=goodsCd]").val()
			};
			pickerList.push(pickerInfo);
			pIdx++;
		});
		
		if (optCheck){
			return false;
		}

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {
					lookbookbSq : $('#lbBannerPickerForm input[name=lookbookbSq]').val()
					,pickerList : pickerList
					,delYn : 'N'
					,mode : mode
				};

				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit($('#lbBannerPickerForm').prop('action'), jsonData, fnPickerSaveCollback);
			}
		});
	});

	var fnPickerSaveCollback = function (){
		uifnPopupClose('popupLookbookBannerPicker');
	}

	function dataValidation(){
		$(".pickerTr").each(function (i){
			if(gagajf.isNull($(this).find("input[name=xlim]").val())){
				mcxDialog.alert((i+1)+'행의 left 값이 없습니다.');
				return false;
			}

			if(gagajf.isNull($(this).find("input[name=ylim]").val())){
				mcxDialog.alert((i+1)+'행의 top 값이 없습니다.');
				return false;
			}

			if(gagajf.isNull($(this).find("input[name=goodsCd]").val())){
				mcxDialog.alert((i+1)+'행의 상품코드 값이 없습니다.');
				return false;
			}
		});
		return true;
	}

	/**
	 * picker list
	 */
	var fnCreateLookbookPickerList = function (){
		if(lookbookBannerPickerList.length > 0){
			for(let i=0; i<lookbookBannerPickerList.length; i++){
				var picIdx = lookbookBannerPickerList[i].dispOrd;
				var picX = lookbookBannerPickerList[i].xlim;
				var picY = lookbookBannerPickerList[i].ylim;
				var picGoodsCd = lookbookBannerPickerList[i].goodsCd;

				var posTag = '<span data-id="'+picIdx+'" class="pos" style="left:'+picX+'%; top:'+picY+'%;"><i>'+picIdx+'</i></span>';
				var html = '<tr data-id="'+picIdx+'" class="pickerTr">';
				html += '<th>'+picIdx+'</th>';
				html += '		<td>';
				html += '			<span>left <input type="text" name="xlim" value="'+picX+'" readonly="readonly"/><em class="per">%</em></span>';
				html += '	<span>top <input type="text" name="ylim" value="'+picY+'" readonly="readonly"/><em class="per">%</em></span>';
				html += '	<span>상품코드';
				html += '		<input type="text" name="goodsCd" readonly="readonly" value="'+picGoodsCd+'"/>';
				html += '		<button type="button" value="검색하기" class="btn btn-base btn-lg" onclick="fnSearchGoods('+picIdx+');">상품조회</button>';
				html += '	</span>';
				html += '	<span class="btnDel"><button type="button" value="검색하기" class="btn btn-dark btn-lg" onclick="trDel('+picIdx+', '+picIdx+')">삭제</button></span>';
				html += '		</td>';
				html += '	</tr>';

				trIdx = picIdx;
				idx = picIdx;
				$pic.append(posTag);
				$(".dataWrap").append(html);
			}
		}
	}

	$(document).ready(function() { //debugger;
		var bannerImgPath = $("#lbBannerPickerForm input[name=uploadBannerUrl]").val().replace('/lookbook/banner/', '')+imgNm;
		$("#lbBannerPickerForm #pickerBannerPreViewUrl").css({"background-image":"url("+bannerImgPath+")"});
		//var container = document.getElementById("pickerBannerPreViewUrl");
		//container.style.backgroundImage = "url("+bannerImgPath+")";


		// 상세/수정일때
		if(mode != 'N'){
			fnCreateLookbookPickerList();
		}

		//sortable Item List
		/*$("#bannerDiv").sortable({
			stop: function(event, ui) {
				fnResetIdx();
			}
		});*/
	});
/*]]>*/
</script>
</html>