<!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.3.3   	 sowon		   최초 작성
 *******************************************************************************
 -->
<div id="main">
	<div class="main-title">
	</div>

	<div class="panelStyle">
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/marketing/social/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<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>
								<option th:if="${siteList}" th:each="oneData, status : ${siteList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
							</select>
						</td>
						<th>웹/모바일구분</th>
						<td>
							<select name="frontGb">
								<option value="A">ALL</option>
								<option value="P">웹</option>
								<option value="M">모바일</option>
							</select>
						</td>

						<th>소셜유형</th>
						<td>
							<select name="socialType">
								<option value="">선택</option>
								<option th:if="${socialTypeList}" th:each="oneData, status : ${socialTypeList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
							</select>
						</td>
					</tr>
					<tr>
						<th>소셜번호</th>
						<td>
							<input type="text" name="socialSq" id="socialSq"/>
						</td>

						<th>등록자</th>
						<td>
							<input type="text" name="regId" id="regId"/>
						</td>

						<th>사용여부</th>
						<td>
							<select name="useYn">
								<option value="">전체</option>
								<option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
							</select>
						</td>
					</tr>
					<tr>
						<th>진행기간</th>
						<td colspan="7" id="terms"></td>
					</tr>
				</tbody>
			</table>
			<ul class="panelBar">
				<li class="center">
					<input type="button" value="초기화" class="btn btn-gray btn-lg" id="btnReset" onclick="fnReset();"/>
				<input type="button" value="조회" class="btn btn-base btn-lg" id="btnSearch" onclick="fnSearch();"/>
				</li>
			</ul>
		


			<div class="panelContent">
				<ul class="panelBar">
					<li class="right">
						 검색결과 : <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="gridSocialList" style="width: 100%; height: 500px;" class="ag-theme-balham"></div>
				
				<ul class="panelBar">
					<li class="center">
						<div class="tablePaging" id="socialListPagination"></div>
					</li>
				</ul>
			</div>
	</form>
</div>

	<!-- TABS AREA -->
	<div class="tabs">
		<ul class="tabsNav">
			<li class="on"><a href="#tab-1">기본정보</a></li>
			<li class="off"><a href="#tab-2">소셜상품</a></li>
		</ul>

		<ul class="tabsCont">
			<!-- 기본 정보 -->
			<li class="tab on" id="tab-1">
					<div class="panelStyle">
						<!-- 버튼 배치 영역 -->
						<ul class="panelBar">
							<li class="right">
								<button type="button" class="btn btn-info btn-lg" onclick="afreshBtn()">신규</button>
							<button type="button" class="btn btn-success btn-lg" onclick="fnSocialSaveValid();">저장</button>
							</li>
						</ul>
						<!-- //버튼 배치 영역 -->
					<!-- <h3>
						<i class="fa fa-info-circle"></i>소셜관리(핫딜)는<font color="red"> 등록순</font>으로 최신 <font color="red">한 건만</font> 노출됩니다.
					</h3> -->
				</div>

					<div class="panelStyle" style="border-top: #fff">
			
						<form id="detailForm" name="detailForm" action="#" th:action="@{'/marketing/event/save'}">
							<table class="frmStyle">
								<colgroup>
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
									<col style="width:''">
								</colgroup>
								<tr>
									<th>소셜번호</th>
									<td>
										<input type="text" name="socialSq" id="socialSq" readonly="readonly"/>
									</td>
									
									<th>사이트</th>
									<td>
										<select name="siteCd" required="required" data-valid-name="사이트">
											<option th:if="${siteList}" th:each="oneData, status : ${siteList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
										</select>
									</td>
									
									<th>사용여부</th>
									<td>
										<select name="useYn" required="required" data-valid-name="사용여부">
											<option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
										</select>
									</td>

									<th>웹/모바일구분</th>
									<td>
										<select name="frontGb" required="required" data-valid-name="웹/모바일구분">
											<option value="A">ALL</option>
											<option value="P">웹</option>
											<option value="M">모바일</option>
										</select>
									</td>
								</tr>
								<tr>
									<th>소셜명</th>
									<td colspan="3">
										<input type="text" name="socialNm" id="socialNm" required="required" data-valid-name="소셜명"/>
									</td>
									<th>소셜타이틀명</th>
									<td colspan="3">
										<input type="text" name="socialTnm" id="socialTnm"/>
									</td>
								</tr>
								<tr>
									<th>소셜유형</th>
									<td colspan="3">
										<select name="socialType" required="required" data-valid-name="소셜유형">
											<option th:if="${socialTypeList}" th:each="oneData, status : ${socialTypeList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
										</select>
										
									 <!-- 		<button type="button" class="btn btn-base btn-lg" id="btnSearchPlan">기획전 조회</button>
											/ 기획전
										 <span id="planSpan">
											<select name="planSq" id="planSq">
													<option th:if="${planList}" th:each="oneData, status : ${planList}" th:value="${oneData.planSq}" th:text="|[${oneData.planSq}]  ${oneData.planNm}|"></option>
											</select>
										</span> -->
									</td>
									
									<th>진행기간</th>
									<td>
										<input name="stDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="진행시작일자" />
										<select id="stTimeHour" required="required" data-valid-name="진행기간 시작시간">
											<th:block th:each="num, index  : ${#numbers.sequence(0,23)}">
											<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" >시간</option>
											</th:block>
										</select>
										 ~ 
										<input name="edDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="진행종료일자" />
										<select id="edTimeHour" required="required" data-valid-name="진행기간 종료시간">
											<th:block th:each="num: ${#numbers.sequence(0,23)}">
											<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${#numbers.formatInteger(num,2)}==23 ? 'true'">시</option>
											</th:block>
										</select>
										
										<input type="hidden" name="socialStdt"/>
										<input type="hidden" name="socialEddt"/>
									</td>
									
									<th>적용구분</th>
									<td>
										<select name="applyGb" required="required" data-valid-name="적용구분">
											<option value="P">대기</option>
											<option value="A">적용</option>
											<option value="F">종료</option>
										</select>
									</td>
									
								</tr>
							</table>
						</form>
					</div>			
					<div class="panelStyle" style="border-top: #fff">		
					
					</div>
				</li>
			
			<!-- 소셜 상품 -->
			<li class="tab" id="tab-2">
				<div class="panelStyle">	
						<span class="btnLeft">
							<select name="priceGb" id="priceGb">
								<option value="">선택</option>
								<option value="currAprice">판매가</option>
								<option value="dcArate">할인율</option>
								<!-- <option value="pntAprate">PC 포인트</option> -->
								<!-- <option value="pntAmrate">MOBILE 포인트</option> -->
							</select>					
							<input type="text" class="w100 aR" id="price" name="price" data-valid-type="numeric"/>
							<button type="button" class="btn btn-default btn-lg" onclick="fnPriceApply();">일괄적용</button>
						</span> 
						<ul class="panelBar">
							<li>
								<h3><i class="fa fa-info-circle"></i>설정하는 가격과 할인율은 즉시적용 쿠폰을 적용하지 않으며 <font color="red">상품에 있는 판매가로 적용</font>됩니다.</h3>
							</li>
							<li class="right">
								<button type="button" class="btn btn-default btn-lg" onclick="fnOpenGoodsPopup();">상품추가</button>
								<button type="button" class="btn btn-default btn-lg" onclick="fnDeleteGoods();">상품삭제</button>
								<button type="button" class="btn btn-default btn-lg" onclick="fnSocialGoodsExcelUpload();">엑셀상품추가</button>
								<button type="button" class="btn btn-default btn-lg" onclick="cfnDownloadSampleFile('SF011');">엑셀상품추가 양식 다운로드</button>
								<button type="button" class="btn btn-success btn-lg" onclick="fnSocialGoodsSave();">저장</button>
							</li>
						</ul>
						<div id="gridSocialGoodsList" style="width: 100%; height: 700px" class="ag-theme-balham lh60"></div>
					
					
					<!-- <li class="boxContentBtnB" style="margin-top: 10px;">
						<span class="btnRight">
							<button type="button" class="btn btn-success btn-lg" onclick="">즉시적용</button>
						</span>
					</li> -->
				</div>
			</li>

		</ul>
	</div>

</div>

<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
/*<![CDATA[*/

	var siteList = gagajf.convertToArray([[${siteList}]]);
	var socialTypeList = gagajf.convertToArray([[${socialTypeList}]]);
	var wmGbList = {"A":"ALL", "P":"웹", "M":"모바일"};
	var applyList = {"P":"대기", "A":"적용", "F":"종료"};

	var columnSocialDefs = [
		{headerName: "사이트"		, field:'siteCd'		, width:100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(siteList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(siteList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(siteList, params.newValue); }
		},
		{headerName: "소셜번호"		, field:'socialSq'		, width:100, cellClass: 'text-center'},
		{headerName: "소셜명"		, field:'socialNm'		, width:300, cellClass: 'text-center',
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "소셜타이틀명"	, field:'socialTnm'		, width:200, cellClass: 'text-center'},
		{headerName: "진행시작일시"	, field:'socialStdt'	, width:150, cellClass: 'text-center'},
		{headerName: "진행종료일시"	, field:'socialEddt'	, width:150, cellClass: 'text-center'},
		{headerName: "프론트구분"	, field:'frontGb'		, width:120, cellClass: 'text-center',
			 valueFormatter: function (params) { return gagaAgGrid.lookupValue(wmGbList, params.value); }
		},
		{headerName: "소셜유형"		, field:'socialType'	, width:150, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(socialTypeList, params.value); }
		},
		{headerName: "사용여부"		, field:'useYn'			, width:80 , cellClass: 'text-center'},
		{headerName: "적용구분"	, field:'applyGb'	, width:100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(applyList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(applyList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(applyList, params.newValue); }
		},
		{headerName: "등록자"		, field:'regNm'			, width:100, cellClass: 'text-center'},
		{headerName: "등록일"		, field:'regDt'			, width:150, cellClass: 'text-center'},
	];

	var gridOptions = gagaAgGrid.getGridOptions(columnSocialDefs);

	// 셀 클릭 이벤트
	gridOptions.onCellClicked = function(event) {
		if (event.colDef.field != 'socialNm')
			return;

		$('.tabsNav li').eq(0).trigger('click');
		fnBindDetail(event.data); // 바인딩
	}

	// 바인딩
	var fnBindDetail = function(data) {
		fnFirstSearchSocialGoodsList(data.socialSq);
		fnSetDate(data);
	}
	
	
	
	// 데이터 설정
	var fnSetDate = function(data) {
		var formId = '#detailForm';
		
		$('.tabsNav li').eq(1).removeClass('off');
		
		// 기본정보 입력
		$(formId + ' input[name=socialSq]').val(data.socialSq);
		$(formId + ' input[name=socialNm]').val(data.socialNm);
		$(formId + ' input[name=socialTnm]').val(data.socialTnm);
		$(formId + ' select[name=siteCd]').val(data.siteCd);
		$(formId + ' select[name=useYn]').val(data.useYn);
		$(formId + ' select[name=applyGb]').val(data.applyGb);
		$(formId + ' select[name=frontGb]').val(data.frontGb);
		$(formId + ' select[name=socialType]').val(data.socialType);
		$(formId + ' select[name=planSq]').val(data.planSq);
		$(formId + ' select[name=socialType]').trigger('change');
		
		$(formId + ' select[name=planSq]').attr("disabled",true);
		//$(formId + ' select[name=socialType]').attr("disabled",true);
		$(formId + ' button[id=btnSearchPlan]').css("display","none");
		// 진행 기간 설정
		var stDate = data.socialStdt.split(" ")[0];
		var edDate = data.socialEddt.split(" ")[0];
		var stTime = data.socialStdt.split(" ")[1].replaceAll(":", "");
		var edTime = data.socialEddt.split(" ")[1].replaceAll(":", "");
		
		// 진행 시작 기간 설정
		$(formId + ' input[name=stDate]').val(stDate);
		$('#stTimeHour').val(stTime.substring(0,2));
		
		// 진행 종료 기간 설정
		$(formId + ' input[name=edDate]').val(edDate);
		$('#edTimeHour').val(edTime.substring(0,2));
	}
	
	// 신규버튼  클릭 시 
	var afreshBtn = function() {
		var formId = '#detailForm';
		
		$('#detailForm')[0].reset();
		$('.tabsNav li').eq(1).addClass('off');
		
		$(formId + ' select[name=planSq]').removeAttr("disabled");
		$(formId + ' select[name=socialType]').removeAttr("disabled");
		$(formId + ' button[id=btnSearchPlan]').removeAttr("style");
		
	};
	// 소셜 기본정보 저장
	var fnSocialSaveValid = function() {
		var formId = '#detailForm';
		
		if (!gagajf.validation(formId))
			return;
		
		// 날짜 유효성 체크
		var stDate = $(formId + ' input[name=stDate]').val().replaceAll("-", "");
		var edDate = $(formId + ' input[name=edDate]').val().replaceAll("-", "");
		var stTime = $('#stTimeHour').val().replaceAll(":", "");
		var edTime = $('#edTimeHour').val().replaceAll(":", "");
		var toDate = _today.replaceAll("-", "");
		
		var socialSq = $(formId + ' input[name=socialSq]').val();
		var planSq = $(formId + ' input[name=planSq]').val();
		
		var msg = '저장';
		if (gagajf.isNull(socialSq)) {
			msg = '등록';
			// 신규
			if (Number(stDate) < Number(toDate)) {
				mcxDialog.alert('시작일자는 오늘포함 이후로 등록해주세요.');
				return;
			}
			
			if (Number(edDate) < Number(toDate)) {
				mcxDialog.alert('종료일자는 오늘포함 이후로 등록해주세요.');
				return;
			}
		}
		
		if (Number(stDate) > Number(edDate)) {
			mcxDialog.alert('종료일자는 시작일자 보다 클 수 없습니다.');
			return;
		}
		
		if (Number(stDate) == Number(edDate)) {
			if (Number(stTime) > Number(edTime)) {
				mcxDialog.alert('시작시간은 종료시간보다 클 수 없습니다.');
				return;
			}
			
			if (Number(stTime) == Number(edTime)) {
				mcxDialog.alert('같은 날 시작시간과 종료시간은 같을 수 없습니다.');
				return;
			}
		}
		
		$(formId + ' input[name=socialStdt]').val($(formId + ' input[name=stDate]').val() + ' ' + stTime + ':00:00');
		$(formId + ' input[name=socialEddt]').val($(formId + ' input[name=edDate]').val() + ' ' + edTime + ':59:59');
		
		//fnPlanCheck(planSq, msg);
		fnSocialSave(msg);
	}

	
	// 소셜 저장
	var fnSocialSave = function(msg) {
		mcxDialog.confirm(msg +' 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var actionUrl = '/marketing/social/save';
				gagajf.ajaxFormSubmit(actionUrl, '#detailForm', function() {
					fnSearch();
				});
			}
		});
	}

	// 검색
	var fnSearch = function() {
		$('.tabsNav li').eq(1).addClass('off');
		$('.tabsNav li').eq(0).trigger('click');
		
		gagaPaging.init('searchForm', fnSearchCallBack, 'socialListPagination', $('#pageSize').val());
		gagaPaging.load($("#searchForm input[name=pageNo]").val());
	}
	
	var fnSearchCallBack = function(result){
		$('#searchForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
		$('#searchForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
		$('#searchForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
		$('#searchForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
		gridOptions.api.setRowData(result.socialList);
		
		gagaPaging.createPagination(result.pageing.pageable);
	}
	
	var columnDefsSocialGoods = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: '상품이미지'				, field:'sysImgNm'	, width: 100, height: 60, cellClass: 'text-center',
			cellRenderer: function(params) {
				return '<img width="60" src="'+ _goodsUrl+ "/" + params.value + '?RS=60" alt="" onclick="cfnOpenImagePreViewPopup(\'goodsImgView\', \''+ _goodsUrl+ "/" + params.value +'\')" onerror="this.src=\'/image/no.png\';"/>';
			}
		},
		{headerName: '상품코드'				, field:'goodsCd'	, width:250 , cellClass: 'text-center',
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "상품명", field: "goodsNm", width: 200, cellClass: 'text-left'},
		{headerName: '정상가'			, field:'listPrice', width:200 , cellClass: 'text-center', cellEditor: 'numericCellEditor'
			, cellRenderer: function(params) { return gagajf.isNull(params.value) ? '' : params.value.addComma(); }
		},
		{headerName: '기존 판매가'			, field:'currBprice', width:200 , cellClass: 'text-center', cellEditor: 'numericCellEditor'
			, cellRenderer: function(params) { return gagajf.isNull(params.value) ? '' : params.value.addComma(); }
		},
		{headerName: '적용 판매가'			, field:'currAprice', width:200 , cellClass: 'text-center', cellEditor: 'numericCellEditor'
			, editable: function(params) { return gagajf.isNull(params.data.dcArate) ? true : false; } 
			, cellRenderer: function(params) { return gagajf.isNull(params.value) ? '' : params.value.addComma(); }
		}, // 변경 후 현재판매가
		{headerName: '변경전 할인율(%)'				, field:'dcBrate'		, width:100 , cellClass: 'text-center'},
		{headerName: '적용 할인율(%)'			, field:'dcArate'	, width:200 , cellClass: 'text-center', cellEditor: 'numericCellEditor'
			, editable: function(params) { return gagajf.isNull(params.data.currAprice) ? true : false; }
		}, // 변경 후 할인율
		{headerName: '상품타입'	         , field:'goodsType'		, width:100 , cellClass: 'text-center', hide: true},
		{headerName: '삭제여부'				, field:'delYn'		, width:100 , cellClass: 'text-center', hide: true},
		{headerName: '변경전 할인율'				, field:'dcBrate'		, width:100 , cellClass: 'text-center', hide: true},
	];

	var gridOptionsGoods = gagaAgGrid.getGridOptions(columnDefsSocialGoods);
	gridOptionsGoods.rowSelection = 'multiple';
	gridOptionsGoods.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
	
	// 소셜 상품 목록 검색
	var fnSearchSocialGoodsList = function(socialSq) {
		var actionUrl = 'marketing/social/goods/list';
		var params = new Object();
		params.socialSq = typeof socialSq == 'object' ? $('#detailForm input[name=socialSq]').val() : socialSq;
		
		var jsonData = JSON.stringify(params);
			gagajf.ajaxJsonSubmit(actionUrl, jsonData, function(result) {
			//gridOptionsGoods.api.setRowData(result);
		});
	}
	
	// 소셜 상품 목록 검색
	var fnFirstSearchSocialGoodsList = function(socialSq) {
		var actionUrl = 'marketing/social/goods/list';
		var params = new Object();
		params.socialSq = typeof socialSq == 'object' ? $('#detailForm input[name=socialSq]').val() : socialSq;
		
		var jsonData = JSON.stringify(params);
			gagajf.ajaxJsonSubmit(actionUrl, jsonData, function(result) {
			gridOptionsGoods.api.setRowData(result);
		});
	}
	
	// 적용가격 일괄적용
	var fnPriceApply = function() {
		var priceGb = $('select[name=priceGb]').val();
		var price = $('#price').val();
		var msg = '';
		
		// 선택 된 상품
		var selectedGoodsList = gagaAgGrid.selectedRowData(gridOptionsGoods);
		if (selectedGoodsList.length < 1) {
			mcxDialog.alert('선택한 상품이 존재 하지않습니다.');
			return;
		}
		
		if (gagajf.isNull(priceGb)) {
			mcxDialog.alert('일괄적용을 선택 하세요.');
			$('#priceGb').focus();
			return;
		}
		
		if (gagajf.isNull(price)) {
			mcxDialog.alert('할인 금액 및 율을 입력하세요.');
			$('#price').focus();
			return;
		}

		var msg = $("#priceGb option:selected").text() + '을(를) ' + $('#price').val() + '값으로 ';
		mcxDialog.confirm(msg +'일괄적용 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {

				$(selectedGoodsList).each(function(idx, goods) {
					if (goods.listPrice < price) {
						mcxDialog.confirm(goods.goodsNm + ' 상품이 정상가보다 적용판매가가 높습니다.');
						return;
					}
					
					if (priceGb == 'currAprice') { // 판매가
						goods.currAprice = price;
						goods.dcArate = null;
					} else if (priceGb == 'dcArate') { // 할인율
						goods.dcArate = price;
						goods.currAprice = null;
					} else if (priceGb == 'pntAprate') { // pc 할인율
						goods.pntAprate = price;
					} else if (priceGb == 'pntAmrate') { // mobile 할인율
						goods.pntAmrate = price;
					}
				});
				
				gridOptionsGoods.api.updateRowData({update: selectedGoodsList});
			}
		});
	}
	
	// 상품 추가
	var fnOpenGoodsPopup = function() {
		var edDate = $('#detailForm input[name=socialEddt]').val().replaceAll("-", "");;
		var toDate = _today.replaceAll("-", "");
		
		if (Number(toDate) < Number(edDate)) {
			mcxDialog.alert("진행종료일자 전에만 상품추가가 가능합니다.");
			return;
		}
		cfnOpenGoodsPopup('fnCreateGoods');
	}
	
	// 상품 추가 콜백
	var fnCreateGoods = function(result) {
		if (result.length < 1) return;
		
		// 기존상품
		var oldGoodsList = gagaAgGrid.getAllRowData(gridOptionsGoods);
		var socialSq = $('#detailForm input[name=socialSq]').val();
		
		// 중복체크
		var check = true;
		var checkData = [];
		$(oldGoodsList).each(function(idx) {
			
			$(result).each(function(newIdx) {
				
				if (oldGoodsList[idx].goodsCd == result[newIdx].goodsCd) {
					check = false;
					checkData.push(result[newIdx].goodsCd);
				}
			});
		});
		
		if (!check) {
			mcxDialog.alert('아래 중복상품이 존재 합니다.<br/>' + checkData.join(","));
			return;
			
		} else {
			/* if (gagajf.isNull(socialSq)) {
				mcxDialog.alert('소셜을 선택 해주세요.');
				return;
			} */
			
			for (var disp = 0; disp < result.length; disp++) {
				var goods = { socialSq : Number(socialSq) ,
							  scgoodsSq : Number(0) ,
							  goodsCd : result[disp].goodsCd, 
							  goodsNm : result[disp].goodsNm,
							  currBprice: result[disp].currPrice,
							  dcBrate: result[disp].dcRate,
							  listPrice : result[disp].listPrice,
							  sysImgNm : result[disp].sysImgNm,
							  goodsType : result[disp].goodsType,
							  dispOrd : disp+1
							  };
				
				oldGoodsList.unshift(goods);
				
			}
		}
		mcxDialog.alert('상품이 적용되었습니다.');
		uifnPopupClose('popupGoods');
		gridOptionsGoods.api.setRowData(oldGoodsList);
	}
	
	// 상품 삭제
	var fnDeleteGoods = function() {
		// 선택 상품
		var selectedGoodsList = gagaAgGrid.selectedRowData(gridOptionsGoods);
		
		if (selectedGoodsList.length < 1) {
			mcxDialog.alert('선택된 상품이 존재 하지않습니다.');
			return;
		}
		
		mcxDialog.confirm('선택하신 상품을 삭제하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				gridOptionsGoods.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsGoods)});
				$(selectedGoodsList).each(function(idx, goods) {
					goods.delYn = 'Y';
				});
				
				var jsonData = JSON.stringify(selectedGoodsList);
				gagajf.ajaxJsonSubmit('/marketing/social/goods/delete', jsonData, fnSearchSocialGoodsList);
			}
		});
	}
	
	var fnSocialGoodsExcelUpload = function() {
		cfnExcelUploadPopup('socialGoodsExcelUpload', 'socialGoodsExcelUpload');
	}
	
	// 상품 엑셀 업로드
	var socialGoodsExcelUpload = function(result) {
		var data = {procJob : result.procJob
					,excelFileNm : result.excelFileNm
					,socialSq : Number($('#detailForm input[name=socialSq]').val())
					};
		
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/marketing/social/goods/excelupload', jsonData, fnSearchSocialGoodsList);
	} 
	
	// 소셜 상품 저장
	var fnSocialGoodsSave = function() {
		
	var dcRate;
	var currAprice;
		var goodsList = gagaAgGrid.getAllRowData(gridOptionsGoods);
		
		if (goodsList.length < 1) {
			mcxDialog.alert('상품이 존재 하지않습니다.');
			return;
		}
		
		var checkData = [];
		var msg = '';
		$(goodsList).each(function(idx, goods) {
			if (goods.listPrice < goods.currAprice) {
				msg = goods.goodsNm + ' 상품이 정상가보다 적용판매가가 높습니다.';
				return false;
			}
			
			if (goods.goodsType == "G056_D") {
				if(goods.currBprice != goods.currAprice){
					msg = goods.goodsNm + ' 상품은 딜상품으로 기존 판매가와 동일하게 적용하여야 합니다.';
					return false;
				}
			}
			
			if (goods.dcArate > 100) {
				msg = '할인율은 100%를 넘을 수 없습니다.';
				return false;
			}
			
			if (gagajf.isNull(goods.currAprice) && gagajf.isNull(goods.dcArate)) {
				msg = '상품코드 : ' + goods.goodsCd + '<br/>판매가와 할인율 모두 값이 존재하지않습니다.';
				return false;
			}
		/* 	if (gagajf.isNull(goods.dispOrd)) {
				msg = '상품코드 : ' + goods.goodsCd + '<br/>전시순서를  입력해주세요.';
				return false;
			} */
			
			if(!gagajf.isNull(goods.currAprice)){
				dcRate =  100 - Math.floor(Number(goods.currAprice) / Number(goods.listPrice) * 100);	//절사
				goods.dcArate = dcRate;
				//var good = {dcArate : dcRate};
				//goodsList.unshift(good);	
			}
			else{
				currAprice =   Number(goods.listPrice) - ( Number(goods.listPrice) * (Number(goods.dcArate)/100) );
				goods.currAprice = currAprice;
			}
			
		});
		
		if (!gagajf.isNull(msg)) {
			mcxDialog.alert(msg);
			return;
		}
		
		mcxDialog.confirm('저장 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(goodsList);
				gagajf.ajaxJsonSubmit('/marketing/social/goods/save', jsonData, fnSearchSocialGoodsList);
			}
		});
	}
	
	// Row Click
	gridOptionsGoods.onCellClicked = function(event) {
		var goodsCd = event.data.goodsCd;
		if (event.colDef.field == "goodsCd"){
			cfnOpenGoodsDetailPopup('U',goodsCd);
		}
	}
	
	$('#btnSearchPlan').on('click', function() {
		cfnOpenPlanPopup('popupPlan');
	});
	
	var popupPlan = function(result) {
		$('#detailForm select[name=planSq]').val(result[0].planSq);
	}
	
	$(document).ready(function() {
		cfnCreateCalendar('#terms', 'stDate', 'edDate', false);

		gagaAgGrid.createGrid('gridSocialList', gridOptions);
		gagaAgGrid.createGrid('gridSocialGoodsList', gridOptionsGoods);
		//uifnFitGrid();
		
	});
	
	// copylight 처리
	$('.tabsNav li').eq(1).on('click', function() {
		timer = setInterval(function() { fnCheckClass(1); }, 50); 
	});
	
	$('.tabsNav li').eq(0).on('click', function() {
		timer = setInterval(function() { fnCheckClass(0); }, 50); 
	});
	
	var fnCheckClass = function(flag) {
		var tabClass = $('.tabsNav li').eq(flag).attr('class');
		if (tabClass == 'on') {
			/*  uifnFitGrid(); */
			clearInterval(timer);
		}
	}
	
/*]]>*/
</script>

</html>