<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : MainContentsPopupForm.html
 * @desc    : 메인전시 컨텐츠 수정 팝업 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.2.23    bin2107     최초 작성
 *******************************************************************************
 -->
	<div class="modalPopup" data-width="1400" >
		<div class="panelStyle">
			<div class="panelTitle">
				<h2 id="popTitle" th:text="${contentsLoc}"></h2>
				<button type="button" class="close" onclick="fnMainContentsPopupFormClose()"><i class="fa fa-times"></i></button>
			</div>
			<div class="panelContent">
				<ul class="panelBar">
					<li class="aL">
						<span class="cBlue">* 상단으로 드래그&amp;드랍하여 순서 변경 가능합니다.</span>
					</li>
					<li class="aR">
						<button type="button" class="btn btn btn-base btn-sm" id="btnPopAddRow">컨텐츠 추가</button>
						<button type="button" class="btn btn btn-dark btn-sm" id="btnPopSave">임시저장</button>
						<input type="hidden" name="uploadDefaultUrlPop" id="uploadDefaultUrlPop" th:value="${@environment.getProperty('upload.image.view') + '/display/contents/'}"/>
					</li>
				</ul>
			</div>
			<form name="contentsTitleForm" id="contentsTitleForm" style="width:1170px; overflow:auto; display: none;">
				<table class="frmStyle">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:90%;"/>
					</colgroup>
					<tr>
						<th>컨텐츠 타이틀</th>
						<td><input type="text" name="contentsTitle" style="width:50%;" maxlength="40" required="required" data-valid-name="컨텐츠타이틀" th:value="${contentsTitle}"></td>
					</tr>
				</table>
			</form>
			<form style="height:600px; width:1370px; overflow:auto;" id="popSortable">
			</form>
		</div>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var cateNo = [[${cateNo}]];
	var contentsLoc = [[${contentsLoc}]];
	var contentsTitle = [[${contentsTitle}]];
	var contentsLocArr = gagajf.convertToArray([[${contentsLocList}]]);
	var tdWidth = $("#sortable").find("td").width();
	var tdDeleteWidth = parseInt(tdWidth/11, 10);
	tdWidth = tdWidth - tdDeleteWidth;

	// 컨텐츠 미리보기 리스트
	var fnGetContentsPreviewList = function() {
		$("#popSortable").html('');
		var data = {cateNo : cateNo
			,contentsLoc : contentsLoc
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/display/contents/preview/list', jsonData, fnCreatePopLayout);
	}

	var fnCreatePopLayout = function(result) {
		var html = '';
		for(var i=0; i<result.length; i++){
			var dispStdt = result[i].dispStdt.split(" ");
			var dispEddt = result[i].dispEddt.split(" ");
			html += '<table class="frmStyle" style="margin-bottom:30px">';
			html += '<colgroup>';
			html += '<col style="width:10%;"/>';
			html += '<col style="width:55%;"/>';
			html += '<col/>';
			html += '</colgroup>';
			html += '<thead><tr><th>전시일시</th><td><input name="dispStdt" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출시작일" data-valid-type="calendar" value="'+dispStdt[0]+'"/>';
			html += '<select name="stTimeHour" required="required" data-valid-name="노출기간 시작시간">';
			html += fnCreateTimeOption(24, dispStdt[1].split(":")[0]);
			html += '</select>';
			html += '<select name="stTimeMin" required="required" data-valid-name="노출기간 시작시간">';
			html += fnCreateTimeOption(60, dispStdt[1].split(":")[1]);
			html += '</select>';
			html += '<span> ~ </span>';
			html += '<input name="dispEddt" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출종료일" data-valid-type="calendar" value="'+dispEddt[0]+'"/>';
			html += '<select name="edTimeHour" required="required" data-valid-name="노출기간 종료시간">';
			html += fnCreateTimeOption(24, dispEddt[1].split(":")[0]);
			html += '</select>';
			html += '<select name="edTimeMin" required="required" data-valid-name="노출기간 종료시간">';
			html += fnCreateTimeOption(60, dispEddt[1].split(":")[1]);
			html += '</select>';
			html += '<input name="dispOrd" type="text" class="w80"placeholder="전시순서" style="margin-left:5px; text-align:center"/>';
			html += '</td>';
			html += '<td class="aL"><button type="button" class="btn btn-base btn-lg" onclick="fnAddTitlePopRow(this);">타이틀추가</button>';
			html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddImgPopRow(this);">이미지추가</button>';
			html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddLinkPopRow(this);">링크추가</button>';
			if(contentsLoc=='SMM001'){
				html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddSubTextPopRow(this);">서브텍스트추가</button>';
			}
			html += '<button type="button" class="btn btn-danger btn-lg" onclick="fnDeleteContentsRow(this);">삭제</button></td>';
			html += '</tr></thead><tbody>';
			for(var j=1; j<5; j++){
				var strTitle = eval("result["+i+"].strTitle" + j);
				var imgPath = eval("result["+i+"].imgPath" + j);
				var strVar = eval("result["+i+"].strVar" + j);
				var subText = eval("result["+i+"].subText" + j);
				if(strTitle!=null && strTitle!='null' && strTitle!='' ){
					html += fnAddTitlePopRow(strTitle);
				}
				if(imgPath!=null && imgPath!='null' && imgPath!='' ){
					html += fnAddImgPopRow(imgPath);
				}
				if(strVar!=null && strVar!='null' && strVar!='' ){
					html += fnAddLinkPopRow(strVar);
				}
				if(subText!=null && subText!='null' && subText!='' ){
					html += fnAddSubTextPopRow(subText);
				}
			}
			html += '</tbody></table>';
		}
		$("#popSortable").append(html);
		$("#popSortable").sortable();
		$('.schDate').datepicker("destroy");
		$('.schDate').datepicker({
			changeMonth: true,
			changeYear: true,
			defaultDate: $('.schDate').val()
		});
	}
	/**
	 * 컨텐츠 추가 버튼
	 */
	$("#btnPopAddRow").on("click", function (){
		var html = '<table class="frmStyle" style="margin-bottom:30px">';
		html += '<colgroup>';
		html += '<col style="width:10%;"/>';
		html += '<col style="width:55%;"/>';
		html += '<col/>';
		html += '</colgroup>';
		html += '<thead><tr><th>전시일시</th><td><input name="dispStdt" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출시작일" data-valid-type="calendar"/>';
		html += '<select name="stTimeHour" required="required" data-valid-name="노출기간 시작시간">';
		html += fnCreateTimeOption(24);
		html += '</select>';
		html += '<select name="stTimeMin" required="required" data-valid-name="노출기간 시작시간">';
		html += fnCreateTimeOption(60);
		html += '</select>';
		html += '<span> ~ </span>';
		html += '<input name="dispEddt" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출종료일" data-valid-type="calendar"/>';
		html += '<select name="edTimeHour" required="required" data-valid-name="노출기간 종료시간">';
		html += fnCreateTimeOption(24,23);
		html += '</select>';
		html += '<select name="edTimeMin" required="required" data-valid-name="노출기간 종료시간">';
		html += fnCreateTimeOption(60,59);
		html += '</select>';
		html += '<input name="dispOrd" type="text" class="w80"placeholder="전시순서" style="margin-left:5px; text-align:center"/>';
		html += '</td>';
		html += '<td class="aL"><button type="button" class="btn btn-base btn-lg" onclick="fnAddTitlePopRow(this);">타이틀추가</button>';
		html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddImgPopRow(this);">이미지추가</button>';
		html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddLinkPopRow(this);">링크추가</button>';
		if(contentsLoc=='SMM001'){
			html += '<button type="button" class="btn btn-base btn-lg" onclick="fnAddSubTextPopRow(this);">서브텍스트추가</button>';
		}
		html += '<button type="button" class="btn btn-danger btn-lg" onclick="fnDeleteContentsRow(this);">삭제</button></td>';
		html += '</tr></thead><tbody></tbody></table>';
		$("#popSortable").prepend(html);
		$("#popSortable").sortable();
		$('.schDate').datepicker("destroy");
		$('.schDate').datepicker({
			changeMonth: true,
			changeYear: true,
			defaultDate: $('.schDate').val()
		});
	});

	/**
	 * 임시저장
	 */
	var dataArr = [];
	$("#btnPopSave").on("click", function (){
		if(!gagajf.checkRequired("#popSortable")){
			return;
		}

		if(contentsLoc=='SMM002'||contentsLoc=='SMM003'||contentsLoc=='SMM004'||contentsLoc=='SMM006'||contentsLoc=='SMM007'
				||contentsLoc=='SMM009' ||contentsLoc=='SMM010'||contentsLoc=='SMM011'){
			if(!gagajf.checkRequired("#contentsTitleForm")){
				return;
			}
		}

		var titleBool = true;
		$("#popSortable").find('input[name=title]').each(function(idx, title) {
			if ($(title).val()==''){
				titleBool = false;
				$(title).focus();
				gagajf.alertMessage($(title), 'input');
				return;
			}
		});
		if(!titleBool){
			return false;
		}
		dataArr = [];
		$("#popSortable table").each(function(){
			var newImgFileArr = [];
			var imgPath1 = '';
			var imgPath2 = '';
			var imgPath3 = '';
			var imgPath4 = '';
			var strVar1 = '';
			var strVar2 = '';
			var strVar3 = '';
			var strVar4 = '';
			var strTitle1 = '';
			var strTitle2 = '';
			var strTitle3 = '';
			var strTitle4 = '';
			var subText1 = '';
			var subText2 = '';
			var subText3 = '';
			var subText4 = '';
			var i = 1;
			$(this).find('input[name=imgPath]').each(function(){
				eval("imgPath" + i + "='"+$(this).val()+"'");
				i++;
			});
			$(this).find('input[name=newImgFile]').each(function(){
				newImgFileArr.push($(this).val());
			});
			i = 1;
			$(this).find('input[name=title]').each(function(){
				var title = $(this).val().replace(/[\']/gi, "\\'");
				eval("strTitle" + i + "='"+title+"'");
				i++;
			});
			i = 1;
			$(this).find('input[name=link]').each(function(){
				_mall = [[${@environment.getProperty('domain.front')}]];
				var val = $(this).val();
				val = val.replace('https:'+_mall, '');
				val = val.replace('http:'+_mall, '');
				val = val.replace(_mall, '');
				eval("strVar" + i + "='"+val+"'");
				i++;
			});
			i = 1;
			$(this).find('input[name=subText]').each(function(){
				var subText = $(this).val().replace(/[\']/gi, "\\'");
				eval("subText" + i + "='"+subText+"'");
				i++;
			});

			var dispStdt = $(this).find("[name=dispStdt]").val().replace(/[^0-9]/g, '') + "" +$(this).find("[name=stTimeHour]").val().replace('시', '') + "" +$(this).find("[name=stTimeMin]").val().replace('분', '') + "00";
			var dispEddt = $(this).find("[name=dispEddt]").val().replace(/[^0-9]/g, '') + "" +$(this).find("[name=edTimeHour]").val().replace('시', '') + "" +$(this).find("[name=edTimeMin]").val().replace('분', '') + "59";

			var dispOrd = $(this).find("[name=dispOrd]").val();

			var data = {cateNo : cateNo
				, contentsLoc : contentsLoc
				, dispStdt : dispStdt
				, dispEddt : dispEddt
				, newImgFileArr : newImgFileArr
				, imgPath1 : imgPath1
				, imgPath2 : imgPath2
				, imgPath3 : imgPath3
				, imgPath4 : imgPath4
				, strVar1 : strVar1
				, strVar2 : strVar2
				, strVar3 : strVar3
				, strVar4 : strVar4
				, strTitle1 : strTitle1
				, strTitle2 : strTitle2
				, strTitle3 : strTitle3
				, strTitle4 : strTitle4
				, subText1 : subText1
				, subText2 : subText2
				, subText3 : subText3
				, subText4 : subText4
				, useYn : 'Y'
				, dispOrd : dispOrd
			};

			dataArr.push(data);
		});

		if(dataArr.length==0){
			var data = {cateNo : cateNo
				, contentsLoc : contentsLoc
			};
			dataArr.push(data);
		}else{
			var dataArrSort = [];
			dataArr.forEach(function(item, index){
				if(dataArr[index].dispOrd>0){
					for(var i=1; i<dataArr.length; i++){
						if(i>index){
							if(dataArr[index].dispOrd==dataArr[i].dispOrd){
								dataArr[i].dispOrd = Number(dataArr[i].dispOrd) + 1;
							}
						}
					}
				}
			});
			dataArr.forEach(function(item, index){
				if(dataArr[index].dispOrd != ''){
					dataArrSort[dataArr[index].dispOrd-1] = item;
				}
			});
			dataArr.forEach(function(item, index){
				if(dataArr[index].dispOrd == ''){
					var empty = false;
					for(var i=0; i<dataArrSort.length; i++){
						if(typeof dataArrSort[i] == 'undefined'){
							dataArrSort[i] = item;
							empty = true;
							break;
						}
					};
					if(!empty){
						dataArrSort.push(item);
					}
				}
			});
			dataArr = dataArrSort;
		}

		if(contentsLoc=='SMM002'||contentsLoc=='SMM003'||contentsLoc=='SMM004'||contentsLoc=='SMM006'||contentsLoc=='SMM007'
				||contentsLoc=='SMM009' ||contentsLoc=='SMM010'||contentsLoc=='SMM011'){
			var data = {
				cateNo : cateNo
				, contentsLoc : contentsLoc
				, contentsTitle : $("#contentsTitleForm input[name=contentsTitle]").val()
			}
			dataArr.push(data);
		}

		var jsonData = JSON.stringify(dataArr);
		mcxDialog.confirm('컨텐츠를 저장 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				gagajf.ajaxJsonSubmit('/display/contents/preview/save', jsonData, fnGetContentsPreviewList);
			}
		});
	});

	/**
	 * 파일첨부
	 */
	var fnPopFileUpload = function (obj, ind){
		var file = obj.files[0];
		file.name = 'test';
		if (typeof(file) == 'undefined'){
			return;
		}
		// 파일 업로드
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/display/contents'
				, file
				, function(result) {
					$(obj).closest('div').find('input:hidden[name=newImgFile]').val(result.newFileName);
					$("#bannerPreViewUrlPop_"+ind).attr('src', $("#uploadDefaultUrlPop").val()+result.newFileName);
					$("#imgViewPop_"+ind).removeClass("off").addClass("on");
				}
				, 'image'
		);
	}

	/**
	 * 링크추가
	 */
	var fnAddLinkPopRow = function (param){
		var val = typeof param=='object'?'#':param;
		var html = '<tr name="linkPopRow">';
		html += '<th>링크 (없으면 #)</th>';
		html += '<td><input name="link" type="text" maxlength="200" required="required" data-valid-name="링크" value="'+val+'"/></td>';
		html += '<td class="aL"><button type="button" class="btn icn" onclick="fnDeleteTrRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button></td>';
		html += '</tr>';
		if(typeof param == 'object'){
			if($(param).closest("table").find("tbody").find("tr[name=linkPopRow]").length>3){
				mcxDialog.alert("링크는 4개까지 등록 가능합니다");
				return;
			}
			$(param).closest("table").find("tbody").append(html);
		}else{
			return html;
		}
	}

	/**
	 * 서브텍스트추가
	 */
	var fnAddSubTextPopRow = function (param){
		var val = typeof param=='object'?'':param;
		var html = '<tr name="subTextPopRow">'
		html += '<th>서브텍스트</th>';
		html += '<td><input type="text" name="subText" maxlength="200" value="'+val+'"/></td>';
		html += '<td class="aL"><button type="button" class="btn icn" onclick="fnDeleteTrRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button></td>';
		html += '</tr>';
		if(typeof param == 'object'){
			if($(param).closest("table").find("tbody").find("tr[name=subTextPopRow]").length>3){
				mcxDialog.alert("서브텍스트는 4개까지 등록 가능합니다");
				return;
			}
			$(param).closest("table").find("tbody").append(html);
		}else{
			return html;
		}
	}

	/**
	 * 이미지 추가
	 */
	var imgIndex = 0;
	var fnAddImgPopRow = function (param){
		var src = '';
		var imgPath = '';
		if(typeof param!='object'){
			src = $("#uploadDefaultUrlPop").val().replace('/contents/', '')+param;
			imgPath = param;
		}
		var html = '<tr name="imgPopRow">';
		html += '<th>이미지';
		html += '</th>';
		html += '<td><div class="uFile w300">';
		html += '<input id="filePop_'+imgIndex+'" name="file" type="file" class="uFileInput w300" onchange="fnPopFileUpload(this, '+imgIndex+')"/>';
		html += '<label for="filePop_'+imgIndex+'" class="uFileLabel">파일선택</label>';
		html += '<input type="hidden" name="imgPath" value="'+imgPath+'"/>';
		html += '<input type="hidden" name="newImgFile" value="" />';
		html += '</div>';
		html += '<div id="imgViewPop_'+imgIndex+'" class=';
		if(src!=''){
			html += '"on">';
		}else{
			html += '"off">';
		}
		html += '<img id="bannerPreViewUrlPop_'+imgIndex+'" src="'+src+'" style="height:100px; max-width:500px;"  onclick="cfnOpenImagePreViewPopup(\'bannerPreimgViewPop\',$(this).attr(\'src\'));"/>';
		html += '</div></td>';
		html += '<td class="aL"><button type="button" class="btn icn" onclick="fnDeleteTrRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button></td>';
		html += '</tr>';
		if(typeof param == 'object'){
			if($(param).closest("table").find("tbody").find("tr[name=imgPopRow]").length>3){
				mcxDialog.alert("이미지는 4개까지 등록 가능합니다");
				return;
			}
			imgIndex++;
			$(param).closest("table").find("tbody").append(html);
		}else{
			imgIndex++;
			return html;
		}
	}

	/**
	 * 타이틀추가
	 */
	var fnAddTitlePopRow = function (param){
		var val = typeof param=='object'?'':param;
		var html = '<tr name="titlePopRow">';
		html += '<th>타이틀</th>';
		html += '<td><input name="title" type="text" maxlength="200" data-valid-name="타이틀" value="'+val+'"/></td>';
		html += '<td class="aL"><button type="button" class="btn icn" onclick="fnDeleteTrRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button></td>';
		html += '</tr>';
		if(typeof param == 'object'){
			if($(param).closest("table").find("tbody").find("tr[name=titlePopRow]").length>3){
				mcxDialog.alert("타이틀은 4개까지 등록 가능합니다");
				return;
			}
			$(param).closest("table").find("tbody").append(html);
		}else{
			return html;
		}
	}

	// 컨텐츠 행삭제
	var fnDeleteContentsRow = function (obj){
		$(obj).closest("table").remove();
	}

	// 행삭제
	var fnDeleteTrRow = function (obj){
		$(obj).closest("tr").remove();
	}

	// 컨텐츠 추가 날짜 설정
	var fnCreateTimeOption = function(val, sel) {
		var html = '';
		for(var i=0; i<val; i++){
			var time = 0;
			if(i<10){
				time = '0'+i;
			}else {
				time = i;
			}
			var select = false;
			if(sel==time){
				select = true;
			}
			if(val==24){
				time += '시';
			}else if(val==60){
				time += '분';
			}
			html += '<option value="'+time+'"';
			if(select){
				html += 'selected="selected"';
			}
			html += '>'+time+'</option>';
		}
		return html;
	}

	// 창닫기
	var fnMainContentsPopupFormClose = function (){
		uifnPopupClose('popupMainContents');
	}

	$(document).ready(function() {
		$("#popTitle").text("["+contentsLoc+"] "+gagaAgGrid.lookupValue(contentsLocArr, contentsLoc));

		if(contentsLoc=='SMM002'||contentsLoc=='SMM003'||contentsLoc=='SMM004'||contentsLoc=='SMM006'||contentsLoc=='SMM007'
				||contentsLoc=='SMM009' ||contentsLoc=='SMM010'||contentsLoc=='SMM011'){
			$("#contentsTitleForm").show();
		}else{
			$("#contentsTitleForm").hide();
		}

		$("#popSortable").disableSelection();
		fnGetContentsPreviewList();
	});
/*]]>*/
</script>

</html>
