<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<head>
<script type="text/javascript">
$(document).ready(function(){
	$("input:text[numberOnly]").on("keyup", function() {
		$(this).val($(this).val().replace(/[^0-9]/g,""));
	});
	
	$("#sampleSearching").keydown(function(keyNum){ 
		if(keyNum.keyCode == 13){
			popupImgList(1);
		}
		return false;
	});
	
	// 제작형태를 선택한거에 따라 첨부 이미지 업로드 여부 & 수량 변경
	$("input[name='customType']").change(function(e){
		var customId = "customPay"+$(this).val();
		if($(this).val() == "01"){
			$("#uploadFileList").css("display","none");
		}else if($(this).val() == "02"){
			$("#uploadFileList").css("display","");
			$("#uploadFile02").css("display","none");
			$("#uploadFile03").css("display","none");
		}else if($(this).val() == "03"){
			$("#uploadFileList").css("display","");
			$("#uploadFile02").css("display","");
			$("#uploadFile03").css("display","");
		}else if($(this).val() == "04"){
			$("#uploadFileList").css("display","none");
		}
 		selectPayCalculation(customId);
	});
	
	$(".input-image-file").change(function(e){
		var id = $(this).attr("id");
		var files = $("#"+id)[0].files;
		temImg(files);
		$("."+id).val(this.value);
	});
	
	//이메일 체크박스 체크 시 이메일 쓰는 input 보임
	$("#radio12").click(function(){
		var chxChecked = $(this).is(":checked")
		if(chxChecked == true){
			$(".radio12_input").css("display","inline-block");
		}else {
			$(".radio12_input").css("display","none");
		}
	})
	
	
	// 요청사항 글자수 제한
	$("textarea[name='customRequest']").on('input', function() {
		var maxLength = 2000;
		var currentLength = $(this).val().length;
		
		if (currentLength > maxLength) {
			$(this).val($(this).val().substring(0, maxLength));
		}
	});
	
	// 요청사항 글자수 제한
	$("textarea[name='customRequest']").on('input paste', function() {
	    var maxLength = 2000;
	    var currentLength = $(this).val().length;

	    if (currentLength > maxLength) {
	        $(this).val($(this).val().substring(0, maxLength));
	    }
	});
});

//샘플 이미지 리스트
function popupImgList(pageNo){
	
	$.ajax({
		url : "<c:url value='/web/mjon/custom/selectCustomPopupImgListAjax.do'/>"
		,type : 'POST'
		,data:{ "searchKeyword": $("#sampleSearching").val()
			, "categoryCode": $("#sampleTemplate option:selected").val()
			, "pageNo": pageNo}
		,dataType:'json'
		,success : function(returnData, status){
			if(status == "success") {
				$("#scrollPaging").html("");
				var html = "";
				for(var i=0; i<returnData.resultCustomList.length; i++) {
					var imgId = returnData.resultCustomList[i].attachFileId;
					var fileSn = returnData.resultCustomList[i].fileSn;
					var letterId = returnData.resultCustomList[i].letterId;
					var strImgPath = "<c:url value='/cmm/fms/getImage2.do'/>?atchFileId="+imgId+"&fileSn="+fileSn;
					html += "<li>";
					html += 	"<a ref='#' onclick='selectSampleImg(\""+imgId+"\",\""+fileSn+"\",\""+letterId+"\");'>";
					html += 	"<img id='img"+i+"' src='"+strImgPath+"' onerror='/publish/images/main/template02.jpg'>";
					html += 	"<input type='hidden' id='"+imgId+"' value='"+strImgPath+"'/>"
					html += 	"</a>";
					html += "</li>";
				}
				$("#scrollPaging").append(html);
				scrollbar();
			}else{ 
				alert("ERROR!");return;
			} 
		}
		,error : function(request , status, error){
			alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
		}
	});
}

// 결제금액 확인
function selectPayCalculation(customId){
	var customPay =  $("#"+customId).val();
	var userMoney = $("#userMoney").val();
	var userBalance = (userMoney - customPay);
	if(userBalance < 0){
		alert("잔액이 부족합니다. 결제 페이지로 이동됩니다.");
		return location.href="/web/member/pay/PayView.do";
	}
	$("#customAmount").val(customPay);
}

//샘플 이미지 조회
function searchSampleImg() {
	$("#scrollPaging").html("");
	var form = document.customPopupImgForm;
	form.searchKeyword.value = $("#sampleSearching").val();
	form.categoryCode.value = $("#sampleTemplate option:selected").val();
	popupImgList(1);
}

/*파일 드래그앤 드롭*/
/* 파일등록 */
var _fileIdx = 0;
var _fileForm2 = new Array();

function temImg(files){
	var fd = new FormData();
	fd.append('file', files[0]);
	var tmpObj = new Object();
	tmpObj.name = "file_" + _fileIdx;
	tmpObj.fileObj = files[0];
	_fileForm2.push(tmpObj);
	_fileIdx++;
}

//이미지 선택 조건 확인
function selectAddImg(id){
	
	var typeVal = $("input:radio[name='customType']:checked").val(); // 제작형태
	if(typeVal == null){
		alert("제작형태를 선택해 주세요");
		return;
	}
	$('#'+id).click();
};

//샘플파일 이미지 선택
function selectSampleImg(id, fileSn, letterId){
	
	if(loginVO == "" || loginVO == null){
		alert("로그인 후 이용이 가능합니다.");
		return false;
	}else{
		$(".groupSendLayer").attr("data-tooltip", "popup01");
		$("#idCheckSuccess").trigger("click");
	}
	
	// 클릭 시 조회수 증가 로직
	var url = "/web/mjon/msgdata/updateSmsTemplateCntAjax.do";
	
	$.ajax({
		type: "POST",
		url: url,
		data: {'letterId':letterId},
		dataType:'json',
		async: false,
		cache: false,
		success: function (returnData, status) {
			console.log("status : ", status);
		},
		error: function (e) {console.log("ERROR : ", e); }
	});
	// 클릭 시 조회수 증가 로직 끝
	
	$("#selectImgInfo").html("");
	var html = "<img src='<c:url value='/cmm/fms/getImage2.do'/>?atchFileId="+id+"&fileSn="+fileSn+"' onerror='/publish/images/main/template02.jpg' alt='' style='width: 100%;'>"
	$("#selectImgInfo").append(html);
	$("#customChoiceImg").val(id);
	$("#customChoiceImgFileSn").val(fileSn);
	$("#customType04").hide();
	popCustomScrT=$(window).scrollTop();
	popScrTarget();
}

//내보관함 이미지 선택
function selectMyCustomImg(groupId, id, fileSn){
	
	if(loginVO == "" || loginVO == null){
		alert("로그인 후 이용이 가능합니다.");
		return false;
	}else{
		$(".groupSendLayer").attr("data-tooltip", "popup01");
		$("#idCheckSuccess").trigger("click");
	}
	
	$("#selectImgInfo").html("");
	var html = "<img src='<c:url value='/cmm/fms/getImage2.do'/>?atchFileId="+id+"&fileSn="+fileSn+"' onerror='/publish/images/main/template02.jpg' alt='' style='width: 100%;'>"
	$("#selectImgInfo").append(html);
	$("#customChoiceImg").val(id);
	$("#customChoiceImgFileSn").val(fileSn);
	$("#customGroupId").val(groupId);
	$("#customType04").show();
	popCustomScrT=$(window).scrollTop();
	popScrTarget();
}

// 맞춤제작 등록
function insertCustomInfo(){
	var frm = document.customPopupImgForm;
	
	if($("#customChoiceImg").val() == ''){
		alert("맞춤제작을 진행할 이미지를 선택해 주세요.");
		return;
	}
	
	var typeVal = $("input:radio[name='customType']:checked").val(); // 제작형태
	if(typeVal == null){
		alert("제작형태를 선택해 주세요");
		return;
	}
	
	if(frm.customPhoneNo.value == ''){
		alert("연락처를 입력해주세요.");
		return;
	}
	
	if(frm.customRequest.value == ''){
		alert("요청사항을 입력해주세요.");
		return;
	}
	
	//익스플로러 오류때문에 파일 첨부 여부에 따라 따로 호출한다.
	if(typeVal == '01' || typeVal == '04') {
		atchExcludeInsertAjax();
	} else {
		atchIncludeInsertAjax();
	}
}

function atchIncludeInsertAjax() {
	$("#customUploadYn").val("Y");
	var data = new FormData(document.customPopupImgForm);

	_fileForm2.forEach(function(obj, idx) {
		if (obj) data.append("file"+idx, obj.fileObj);
	});
	
	
	$.ajax({
		type: "POST"
		, enctype: 'multipart/form-data'
		, url: "/web/mjon/custom/insertCustomImgInfoAjax.do"
		, data: data
		, dataType:'json'
		, async: false
		, processData: false
		, contentType: false
		, cache: false
		, success: function (returnData, status) {
			if(returnData.result == 'success'){
				alert("그림문자 맞춤제작이 접수되었습니다.");
				$("body").find(".mask").removeClass("on");
				customPopup();
				location.href = "/web/mjon/custom/selectMsgCustomView.do";
			} else if(returnData.result == 'notMoney'){
				alert("보유 잔액이 부족 합니다.");
			}
		}
		,error: function (e) { alert("저장에 실패하였습니다."); console.log("ERROR : ", e); }
	});
	
}

function atchExcludeInsertAjax() {
	$("#customUploadYn").val("N");
	$.ajax({
		type: "POST"
		, url: "/web/mjon/custom/insertCustomImgInfoNoFileAjax.do"
		, data: $("#customPopupImgForm").serialize()
		, dataType:'json'
		, async: false
		//, processData: false
		//, contentType: false
		, cache: false
		, success: function (returnData, status) {
			if(returnData.result == 'success'){
				alert("그림문자 맞춤제작이 접수되었습니다.");
				$("body").find(".mask").removeClass("on");
				customPopup();
				location.href = "/web/mjon/custom/selectMsgCustomView.do";
			} else if(returnData.result == 'notMoney'){
				alert("보유 잔액이 부족 합니다.");
			}
		}
		,error: function (e) { alert("저장에 실패하였습니다."); console.log("ERROR : ", e); }
	});
	
}

// 제작형태 선택
function customProvisionView(obj){
	var v=$(obj).val();
	if(v == 02 || v == 03){
		$('.custom_provision').addClass('active');
	}else{
		$('.custom_provision').removeClass('active').find('input[type=radio]').prop('checked','');
	}
}
</script>
</head>
<body>
	
	<form id="customPopupImgForm" name="customPopupImgForm" method="post">
		<input type="hidden" id="userMoney" name="userMoney" value="${userMoney}"/>
		<input type="hidden" id="customAmount" name="customAmount" value=""/>
		
		<input type="hidden" id="customPopupType" name="customPopupType" value=""/>
		<input type="hidden" id="categoryCode" name="categoryCode" value=""/>
		<input type="hidden" id="searchKeyword" name="searchKeyword" value=""/>
		
		<input type="hidden" id="tempImg1" name="tempImg1" value="">
		<input type="hidden" id="tempImg1FileSn" name="tempImg1FileSn" value="">
		
		<input type="hidden" id="tempImg2" name="tempImg2" value="">
		<input type="hidden" id="tempImg2FileSn" name="tempImg2FileSn" value="">
		
		<input type="hidden" id="tempImg3" name="tempImg3" value="">
		<input type="hidden" id="tempImg3FileSn" name="tempImg3FileSn" value="">
		
		<input type="hidden" id="customUploadYn" name="customUploadYn" value="N">
		
		<input type="hidden" id="customChoiceImg" name="customChoiceImg" value="">
		<input type="hidden" id="customChoiceImgFileSn" name="customChoiceImgFileSn" value="">
		
		<input type="hidden" id="customGroupId" name="customGroupId" value="">
		
		<input type="hidden" class="groupSendLayer" id="idCheckSuccess"  data-tooltip="popup01" style="width:0;height:0;opacity:0;filter:opacity(0);"/>
		
		<div class="popup-com custom_layer popup01" tabindex="0" data-tooltip-con="popup01" data-focus="popup01" data-focus-prev="popup01-close">
			<div class="popup_heading">
				<p>맞춤제작</p>
				<button type="button" class="tooltip-close" data-focus="popup01-close">
					<img src="/publish/images/content/layerPopup_close.png" alt="팝업 닫기">
				</button>
			</div>
			<div class="layer_in">
				<div class="header_cont">
					<h3>선택이미지</h3>
					<div class="slectImg_cont" id="selectImgInfo">
						<img src="/publish/images/main/template02.jpg" alt="" />
					</div>
					<div class="search_box">
						<label for="" class="label">추천 템플릿 검색 입력</label>
						<input type="text" name="sampleSearching" id="sampleSearching" placeholder="템플릿 검색" onfocus="this.placeholder=''" onblur="this.placeholder='템플릿 검색'">
						<label for="" class="label">추천 템플릿 검색</label>
						<button>
							<img src="/publish/images/popup/search.png" alt="검색">
						</button>
						<label for="" class="label">추천 템플릿 선택</label>
						<select name="sampleTemplate" id="sampleTemplate" onchange="searchSampleImg();">
							<option value="">All</option>
							<option value="best" selected>BEST</option>
							<c:forEach items="${cateConfList}" var="cateList">
								<option value="<c:out value='${cateList.cateCode}'/>"><c:out value="${cateList.cateNm}"/></option>
							</c:forEach>
						</select>
					</div>
					<div class="contWrap_scroll" id="scrollPagingWrap">
						<ul class="contWrap" id="scrollPaging">
						</ul>
					</div>
				</div>
				<div class="body_cont">
					<table>
						<caption>제작비용 형태, 제공방법, 연락처, 요청사항, 이미지 등록 표</caption>
						<colgroup>
							<col style="width: 105px;">
							<col style="width: auto">
						</colgroup>
						<tbody>
							<tr class="custom_put1">
								<th>제작형태</th>
								<td>
								<div>
									<c:forEach var="code" items="${codeResult}" varStatus="status">
									<div class="custom_put1_list" id="customType${code.code}">
										<input id="radio${status.count}" type="radio" name="customType" value="${code.code}" onclick="customProvisionView(this);">
										<label for="radio${status.count}">${code.codeNm}</label>
										<span class="price"><span><fmt:formatNumber value="${code.codeDc}" type="number" pattern="####,###"/></span>원</span>
										<input type="hidden" id="customPay${code.code}" name="customPay${code.code}" value="${code.codeDc}">
									</div>
									</c:forEach>
								</div>
								<div class="custom_put1_txt">
									<p><span class="vMiddle">*</span> <span class="c_e40000">캘리그래피체는 수정이 불가</span>합니다.</p>
									<p><span class="vMiddle">*</span> <spanspan class="c_e40000">제작형태와 요청사항이 상이</span>한 경우 <spanspan class="c_e40000">추가로 비용이 발생</span>할 수 있습니다.</p>
								</div>
								</td>
							</tr>
							<tr class="custom_put2">
								<th>제공방법</th>
								<td>
									<input type="checkbox" id="storage" checked="checked" disabled="disabled"> <label for="storage">내보관함</label>
									<input type="checkbox" name="customProvision" id="radio11" value="01"> <label for="radio11">카카오톡</label>
									<input type="checkbox" name="customProvision" id="radio12" value="02"> <label for="radio12">이메일</label>
									<input type="text" class="radio12_input" name="customResultEmail" placeholder="이메일주소를 입력해주세요" onfocus="''" onblur="this.placeholder='이메일주소를 입력해주세요'">
<!-- 									<span>중복선택 가능(최대2개)</span> -->
								</td>
							</tr>
							<tr class="custom_put3">
								<th>연락처</th>
								<td>
									<input type="text" name="customPhoneNo" numberOnly maxlength="11" placeholder="완료 메세지를 받을 전화번호를 기재 해주세요." onfocus="this.placeholder=''" onblur="this.placeholder='완료 메세지를 받을 전화번호를 기재 해주세요.'">
								</td>
							</tr>
							<tr class="custom_put4">
								<th>요청사항</th>
								<td>
									<textarea name="customRequest" placeholder="수정사항을 상세히 기입해 주세요.&#13;&#10;약도를 추가할 경우 지번을 정확히 입력해 주세요." onfocus="this.placeholder=''" onblur="this.placeholder='수정사항을 상세히 기입해 주세요.&#13;&#10;약도를 추가할 경우 지번을 정확히 입력해 주세요.'"></textarea>
								</td>
							</tr>
							<tr class="custom_put5" id="uploadFileList">
								<th>첨부 이미지</th>
								<td>
									<div id="uploadFile01">
										<input type="text" class="input-file1" title="첨부파일">
										<button type="button" class="img_add" title="이미지 추가 버튼" style="display: block;" onclick="selectAddImg('input-file1');">파일첨부</button>
										<input type="file" accept=".jpg" class="input-image-file" multiple id="input-file1" style="width:0px !important;height:0px !important"/>
									</div>
									<div id="uploadFile02">
										<input type="text" class="input-file2" title="첨부파일">
										<button type="button" class="img_add" title="이미지 추가 버튼" style="display: block;"  onclick="selectAddImg('input-file2');">파일첨부</button>
										<input type="file" accept=".jpg" class="input-image-file" multiple id="input-file2" style="width:0px !important;height:0px !important"/>
									</div>
									<div id="uploadFile03">
										<input type="text" class="input-file3" title="첨부파일">
										<button type="button" class="img_add" title="이미지 추가 버튼" style="display: block;"  onclick="selectAddImg('input-file3');">파일첨부</button>
										<input type="file" accept=".jpg" class="input-image-file" multiple id="input-file3" style="width:0px !important;height:0px !important"/>
									</div>
								</td>
							</tr>				
						</tbody>
					</table>
					<div class="custom_btn">
						<button type="button" onclick="insertCustomInfo()">신청하기</button>
						<button type="button" class="tooltip-close" data-focus="popup01-close" data-focus-next="popup01">취소</button>
					</div>
				</div>
			</div>
		</div>
	</form>
</body>
