<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : PlanListForm.html
 * @desc    : 기획전관리 Page
 *============================================================================
 * SISUN
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.02.03   sowon        최초 작성
 *******************************************************************************
 -->
<div id="main">
	<div class="main-title"></div>
<form id="planListSearchForm" name="planListSearchForm" action="#"
			th:action="@{'/marketing/planning/list'}"
			onsubmit="$('#btnSearch').trigger('click'); return false;">
	<div class="panelStyle">
			<table class="frmStyle">
				<colgroup>
					<col style="width: 5%;" />
					<col style="width: 20%;" />
					<col style="width: 5%;" />
					<col style="width: 20%;" />
					<col style="width: 5%;" />
					<col style="width: 10%;" />
					<col style="width: 5%;" />
					<col style="width: 10%;" />
					<col />
				</colgroup>
				<tbody>
					<tr>
						<th>사이트</th>
						<td><select name="siteCd">
								<option value="">전체</option>
								<th:block th:if="${siteCdList}"
									th:each="oneData, status : ${siteCdList}">
									<option th:value="${oneData.cd}"
										th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
								</th:block>
						</select></td>
						<!-- <th>기획전명</th>
							<td>
								<input type="text" name="planNm" id="planNm"/>
							</td>
							<th>기획전번호</th>
							<td colspan="3">
								<input type="text" name="planSq" id="planSq"/>
							</td> -->
						<th>오픈여부</th>
						<td><select name="openYn">
								<option value="">전체</option>
								<option th:if="${useYnList}"
									th:each="oneData, status : ${useYnList}"
									th:value="${oneData.cd}"
									th:text="|[${oneData.cd}] ${oneData.cdNm}|"></option>
						</select></td>
						<th rowspan="2">등록자</th>
						<td rowspan="2"><input type="text" name="regNm" id="regNm" /></td>
						<th rowspan="3">키워드</th>
						<td rowspan="3"><select name="search" id="search">
								<option value="searchPlanNm">기획전명</option>
								<option value="searchPlanSq">기획전번호</option>
						</select> <textarea class="textareaR3 w70p" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>PC/모바일구분</th>
						<td><select name="frontGb">
								<option value="">ALL</option>
								<option value="P">웹</option>
								<option value="M">모바일</option>
								<option value="A">앱</option>
						</select></td>

						<th>기획전구분</th>
						<td><select name="planGb">
								<option value="">전체</option>
								<option value="P">기획전</option>
								<option value="E">이벤트</option>
								<option value="S">총알배송</option>
								<option value="C">출석체크</option>
						</select></td>
					</tr>

					<tr>
						<th>진행기간</th>
						<td colspan="6" id="sellTerms"></td>
					</tr>
				</tbody>
			</table>

			<ul class="panelBar">
				<li class="center"><input type="button" value="초기화" class="btn btn-gray btn-lg" id="btnInit" /> 
				<input type="button" value="조회" class="btn btn-base btn-lg" id="btnSearch" />
				</li>
			</ul>
	</div>

		<div class="panelStyle">
			<!-- 검색결과 영역 -->
			<!-- 상단버튼 영역  -->
			<ul class="panelBar">
				<li>
					<button type="button" class="btn btn-danger btn-lg"
						onclick="fnSelectedDelete();">삭제</button>
				</li>
				<li class="right">
					<button type="button" class="btn btn-primary btn-lg"
						onclick="fnPlanRegisterPopup();">등록</button> 검색결과 : <strong><span
						id="gridRowTotalCount">0</span> 건</strong>&nbsp; 쪽번호 <span id="pgNo">0</span>/
					<strong id="endPgNo">0</strong>&nbsp;&nbsp; <select id="pageSize"
					name="pageSize">
						<option value="50" selected="selected">50개씩 보기</option>
						<option value="100">100개씩 보기</option>
						<option value="500">500개씩 보기</option>
						<option value="1000">1000개씩 보기</option>
				</select> <input type="hidden" name="pageNo" id="pageNo" value="1" />
				</li>
			</ul>

			<div id="gridList" style="width: 100%; height: 500px;" class="ag-theme-balham"></div>
			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="planListPagination"></div>
				</li>
			</ul>
		</div>
	</form>
</div>

<!-- 컬러 피커 -->
<!-- <script src='https://bgrins.github.io/spectrum/spectrum.js'></script> -->
<!-- <link rel='stylesheet' href='https://bgrins.github.io/spectrum/spectrum.css' /> -->
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	
	var siteCdList = gagajf.convertToArray([[${siteCdList}]]);
	var wmGbList = {"A":"모바일APP", "P":"웹PC", "M":"모바일PC", "P|M":"웹PC|모바일PC", "P|A":"웹PC|모바일APP", "M|A":"모바일PC|모바일APP", "P|M|A":"전체"};
	var templateTypeList = {"H":"HTML", "T":"TEXT"};
	var planGbList = {"P":"기획전", "E":"이벤트", "S":"총알배송", "C" :"출석체크"};

	var columnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "미리보기"		, field:'plan'		, width:100, cellClass: 'text-center',
			cellRenderer: function(params) { return '<a href="javascript:void(0);" onclick="fnPreview(\'' + params.data.planSq + '\');">' + '미리보기' + '</a>'; }
		},
		{headerName: "기획전구분"		, field:'planGb'	, width:100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(planGbList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(planGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(planGbList, params.newValue); }
		},
		{headerName: "사이트"			, field:'siteCd'	, width:100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(siteCdList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(siteCdList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(siteCdList, params.newValue); }
		},
		{headerName: "프론트구분"	, field:'frontGb'	, width:120, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(wmGbList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(wmGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(wmGbList, params.newValue); }
		},
		{headerName: "오픈여부"		, field:'openYn'	, width:80 , cellClass: 'text-center'},
		{headerName: "기획전번호"		, field:'planSq'	, width:100, cellClass: 'text-center',
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "기획전명"		, field:'planNm'	, width:300, cellClass: 'text-left',
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "서브제목"		, field:'dtlTitle1'	, width:300 , cellClass: 'text-center'},
		{headerName: "댓글참여"		, field:'replyYn'	, width:300 , cellClass: 'text-center',
			cellRenderer: function(params) {
				if(params.value === 'Y'){
					return '<a href="javascript:void(0);">댓글 보기</a>';
				}else{
					return params.value;
				}
			}
		},
		{headerName: "전시순서"		, field:'dispOrd'	, width:100, cellClass: 'text-right' },
		{headerName: "진행시작일시"		, field:'dispStdt'	, width:150, cellClass: 'text-center'},
		{headerName: "진행종료일시"		, field:'dispEddt'	, width:150, cellClass: 'text-center'},
		{headerName: "등록자"			, field:'regNm'		, width:100, cellClass: 'text-center'},
		{headerName: "등록일"			, field:'regDt'		, width:150, cellClass: 'text-center'}
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	// 중복 선택 가능
	gridOptions.rowSelection = 'multiple';
	gridOptions.suppressRowClickSelection = true;

	// 셀 클릭 이벤트
	gridOptions.onCellClicked = function(event) {
		var field = event.colDef.field;
		if (field != 'planSq' && field != 'planNm' && field != 'replyYn')
			return;

		fnBindDetail(field, event.data); // 바인딩

	}
	
	// 바인딩
	var fnBindDetail = function(field, rowData) {
		if (field == 'planSq') { // 기획전 웹수정 팝업
			fnEventDetailPopup(rowData.planSq);
		}

		if (field == 'planNm') { // 기획전 관리 팝업
			fnEventCornerPopup(rowData.planSq);
		}
		
		if (field == 'replyYn') { // 기획전(이벤트) 댓글 팝업
			fnEventReplyPopup(rowData.planSq);
		}
	}
	

	// 웹 등록 팝업
	var fnPlanRegisterPopup = function() {
		var actionUrl = "/marketing/planning/detail/form?mode=N";
		cfnOpenModalPopup(actionUrl,'popupPlanDetail');
	} 

	// 웹 수정 팝업
	var fnEventDetailPopup = function(planSq) {
		var actionUrl = "/marketing/planning/detail/form?mode=U&planSq=" + planSq;
		cfnOpenModalPopup(actionUrl,'popupPlanDetail');
	}
	
	// 이벤트 코너 관리 팝업
	var fnEventCornerPopup = function(planSq) {
		var actionUrl = "/marketing/planning/corner/list/form?planSq=" + planSq;
		cfnOpenModalPopup(actionUrl, 'popupCorner');
	}
	
	// 기획전 댓글 관리 팝업
	var fnEventReplyPopup = function(planSq) {
		var actionUrl = "/marketing/planning/reply/form?planSq=" + planSq;
		cfnOpenModalPopup(actionUrl, 'popupReply');
	}


	// 미리보기
	var fnPreview = function(planSq) {
		window.open(_frontUrl + '/planning/detail/form?planSq=' + planSq + '&adminPreview=Y', '_blank');
 		//document.location.href = _PAGE_CUSTOMER_INFO;
	}

		
	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		fnInit();
	});
	
	var fnInit = function(){
		$('#planListSearchForm')[0].reset();
	}
	
	// 조회클릭시
	$('#btnSearch').on('click', function() {
		$("#planListSearchForm input[name=pageNo]").val('1');
		fnPlanListSearch();
	});
	
	// 이벤트 코너 관리 팝업
	var fnEventCornerPopup = function(planSq) {
		var actionUrl = "/marketing/planning/corner/list/form?planSq=" + planSq;
		cfnOpenModalPopup(actionUrl, 'popupCorner');
	}

	// 조회
	var fnPlanListSearch = function() {
		
		if(!fnConditionCheck()) return;
		
		gagaPaging.init('planListSearchForm', fnSearchCallBack, 'planListPagination', $('#pageSize').val());
		gagaPaging.load($("#planListSearchForm input[name=pageNo]").val());
	}
	
	// 삭제클릭시
	var fnSelectedDelete = function() {
		var selectedData = gagaAgGrid.selectedRowData(gridOptions);

		if (selectedData.length < 1) {
			mcxDialog.alert('선택 된 기획전이 업습니다.');
			return;
		}

		mcxDialog.confirm('선택된 기획전을 삭제하시겠습니까?',{
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(selectedData);

				gagajf.ajaxJsonSubmit('/marketing/planning/delete', jsonData, function() {
					fnPlanListSearch();
				});
			}
		});
	}

	//검색 조건 확인
	var fnConditionCheck = function(){
		var formId = '#planListSearchForm';
		var form = document.planListSearchForm;

		var searchFlag = false;
		var cnt = 0;
		
		for (i = 0; i < form.elements.length; i++ ) {
			var el = form.elements[i];
			if ($(el).prop("type") == "text" || $(el).prop("type") == "textarea" || ($(el).prop("type") == "select-one" && 
					el.name != "search" && el.name != "pageSize" && el.name != "beforSkipFlag")) {
				if (!(el.value == null || el.value == "")) {
					cnt++;
				}
			}
		}		
		if(cnt > 0) searchFlag = true;
		
		var fromDate = $('#planListSearchForm input[name=stDate]').val();
		var toDate = $('#planListSearchForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#planListSearchForm input[name=stDate]').focus();
					}
				});
				return false;
			}

			if (fromDate > toDate) {
				mcxDialog.alert("노출기간 시작일자는 종료일자 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#planListSearchForm input[name=stDate]').focus();
					}
				});
				return false;
			} 
		}

		return true;
	}
	
	var fnSearchCallBack = function(result){
		$('#planListSearchForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
		$('#planListSearchForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
		$('#planListSearchForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
		$('#planListSearchForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
		gridOptions.api.setRowData(result.planList);
		
		gagaPaging.createPagination(result.pageing.pageable);
	}
	
	//페이징 
	$('#planListSearchForm select[name=pageSize]').on('change', function() {
		$("#planListSearchForm input[name=pageNo]").val('1');
		fnPlanListSearch($("#planListSearchForm input[name=searchGb]").val());
	});

	
	$(document).ready(function() {

		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '기간', 'X');
		var chkBeforSkipFlag = '&nbsp;&nbsp;<label class="chkBox"><input type="checkbox" name="beforSkipFlag" value="Y" >이전데이터 제외</label>';
		$("#planListSearchForm").find('#sellTerms').append(chkBeforSkipFlag);
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);

	});

/*]]>*/
</script>

</html>