<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsFreeGoodsForm.html
 * @desc    : 사은품관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.12.28   eskim       최초 작성
  *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- 검색조건 영역 -->
		<div class="panelStyle">
			<div class="panelContent">
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/freeGoods/list'}">
			<input type="hidden" id="searchGb" name="searchGb" value="BASIC" />
			<input type="hidden" id="dateGbn" name="dateGbn" value="R"/> <!-- 등록일 -->
				<table class="frmStyle">
					<colgroup>
						<col style="width:9%;"/>
						<col/>
						<col style="width:9%;"/>
						<col style="width:20%;"/>
					</colgroup>
					<tr>
						<th>업체/브랜드</th>
						<td>
							<select name="supplyCompCd" id="supplyCompCd">
								<option value="" th:if="${sessionInfo.roleCd} != 'G001_B000'">[전체]</option>
								<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<span id="multiBrand"></span>
						</td>
						<th rowspan="2">키워드</th>
						<td rowspan="2">
							<select name="search" id="search">
								<option value="searchProductNo">사은품번호</option>
								<option value="searchGoodsNm">사은품명</option>
								<option value="searchGoodsNum">품번</option>
							</select>
							<textarea class="textareaR2 w130" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>등록일</th>
						<td id="sellTerms"></td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-default btn-lg" id="btnInit">초기화</button>
						<button type="button" class="btn btn-success btn-lg" id="btnSearch">조회</button>
					</li>
				</ul>
			</form>
			</div>
		</div>
		<!-- //검색조건 영역 -->
		
		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<div id="gridList" style="width: 100%; height: 450px;" class="ag-theme-balham lh60"></div>
		</div>
		<!-- //리스트 영역 -->
		<!-- 등록/수정 -->
		<div class="panelStyle">
			<form id="detailForm" name="detailForm" action="#" th:action="@{'/goods/freeGoods/update'}">
				<table class="frmStyle">
					<colgroup>
						<col style="width:8%;"/>
						<col style="width:11%;"/>
						<col style="width:8%;"/>
						<col style="width:11%;"/>
						<col style="width:8%;"/>
						<col style="width:11%;"/>
						<col style="width:8%;"/>
						<col style="width:17%;"/>
						<col style="width:8%;"/>
						<col/>
					</colgroup>
					<tr>
						<td colspan='10'>사은품 상세</td>
					</tr>
					<tr>
						<th>사은품번호</th>
						<td>
							<input class="w130" type="text"  name="productNo"  data-valid-name="사은품번호"  readonly="readonly"/>
						</td>
						<th>품번</th>
						<td>
							<input class="w130" type="text"  name="goodsNum"  data-valid-name="품번"  readonly="readonly"/>
						</td>
						<th>브랜드</th>
						<td>
							<!-- <input class="w130" type="text"  name="brandCd"  data-valid-name="브랜드코드"  readonly="readonly" />/ -->
							<input class="w130" type="text"  name="brandEnm"  data-valid-name="브랜드명"  readonly="readonly" />
						</td>
						<th>사은품명<em class="required" title="필수"></em></th>
						<td>
							<input class="w200" type="text"  name="goodsNm" maxlength="50" required="required" data-valid-name="사은품명"/>
						</td>
						<th>사용여부<em class="required" title="필수"></em></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="useYn" value="Y" checked="checked">Y</label>
							<label class="rdoBtn"><input type="radio" name="useYn" value="N">N</label>
						</td>
					</tr>
					<tr>
						<th>이미지</th>
						<td colspan="9">
							<div class="uFile w300">
								<input type="file" id="file" name="file" class="uFileInput"/>
								<label for="file" class="uFileLabel">파일 선택</label>
								<input type="hidden" name="sysImgNm" id="sysImgNm"/>
								<input type="hidden" name="newSysImgNm" id="newSysImgNm"/>
							</div>
							<input type="hidden" name="uploadDefaultUrl" id="uploadDefaultUrl" th:value="${@environment.getProperty('upload.default.view')}"/>
							<div id="imgView" class="off">
								<img id="bannerPreViewUrl" src="" style="height:100px"/>
							</div>
						</td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
					</li>
				</ul>
			</form>
		</div>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var sessRoleCd = [[${sessionInfo.roleCd}]];
	// specify the columns
	var columnDefs = [
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "이미지", field: "sysImgNm", width: 100, height: 60, cellClass: 'text-center'
			,cellRenderer: function(params) {
				return '<img width="60" src="'+ _imgUrl+  params.value + '" alt="" onerror="this.src=\'/image/no.png\';"/>';
			}
		},
		{headerName: "브랜드", field: "brandEnm", width: 130, cellClass: 'text-center'},
		{headerName: "사은품 상품번호", field: "productNo", width: 120, cellClass: 'text-center',
			cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "사은품 품번", field: "goodsNum", width: 150, cellClass: 'text-center'},
 		{headerName: "사은품명", field: "goodsNm", width: 300, cellClass: 'text-left'},
		{headerName: "사용여부", field: "useYn", width: 100, cellClass: 'text-center'},
		{headerName: "등록일자", field: "regDt", width: 150, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "등록자", field: "regNm", width: 130, cellClass: 'text-center'},
		{headerName: "수정일자", field: "updDt", width: 150, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "수정자", field: "updNm", width: 130, cellClass: 'text-center'},
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);
	
	//gridOptions.suppressRowClickSelection = true;
	gridOptions.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
	
	// 상품코드 셀 클릭
	gridOptions.onCellClicked = function(event) {
		if (event.colDef.field == "productNo"){
			
			$("#detailForm")[0].reset();
			$("#detailForm input[name=productNo]").val('');
			$("#detailForm input[name=goodsNum]").val('');
			$("#detailForm input[name=brandNm]").val('');
			
			var formId = '#detailForm';
			$(formId + " input[name=productNo]").val(event.data.productNo);
			$(formId + " input[name=goodsNum]").val(event.data.goodsNum);
			$(formId + " input[name=brandEnm]").val(event.data.brandEnm);
			$(formId + " input[name=goodsNm]").val(event.data.goodsNm);
			$(formId + " input:radio[name=useYn]:input[value="+event.data.useYn+"]").click();
			var sysImgNm = event.data.sysImgNm;
			if(!gagajf.isNull(sysImgNm)){
				$("#sysImgNm").val(sysImgNm);
				$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+sysImgNm);
				$("#imgView").removeClass("off").addClass("on");
			}else {
				$("#sysImgNm").val('');
				$("#bannerPreViewUrl").attr('src', '');
				$("#imgView").removeClass("on").addClass("off");
			}
			$('#detailForm input[name=file]').closest('div').find('label').text('파일선택');
		}
	}
	
	//업체변경시
	$('#searchForm select[name=supplyCompCd]').on('change', function() {
		var actionUrl = '/renderer/supplyCompany/brand/list/' + $(this).val();

		if(sessRoleCd == "G001_B000"){
			actionUrl = '/renderer/brand/AuthBrandlist';
		}
		
		cfnCreateMultiCombo(actionUrl,"multiBrand",  "[전체]",null, 'Y');
	});

	
	// 조회
	$('#btnSearch').on('click', function() {
		var formId = '#searchForm';
		var form = document.searchForm;
		var searchFlag = false;
		var cnt = 0;

		if( !gagajf.isNull($("#searchForm select[name=supplyCompCd]").val()) 
				|| !gagajf.isNull($("#searchForm textarea[name=condition]").val())
				|| (!gagajf.isNull($("#searchForm input[name=stDate]").val()) && !gagajf.isNull($("#searchForm input[name=edDate]").val()))
			){
			searchFlag = true;
		}else{
			/* for (i = 0; i < form.elements.length; i++ ) {
				var el = form.elements[i];

				if ($(el).prop("type") == "text" || ($(el).prop("type") == "select-one" && el.name != "search" && el.name != "pageSize")) {
					if (!(el.value == null || el.value == "")) {
						cnt++;
					}
				}
			}

			if(cnt > 0) searchFlag = true; */
		}

		/* if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		if($("#searchForm input[name=multiBrand]:checked").length == 0) {
			mcxDialog.alert("브랜드까지 조회해주세요.");
			return false;
		} */
	
		// 기간 값 체크
		if (!fnCalendarDateValidation('#sellTerms', 'stDate', 'edDate')){
			return false;
		}
		
		if (!gagajf.isNull($('#searchForm textarea[name=condition]').val())){
			var arrData = $('#searchForm textarea[name=condition]').val().replace(/\r\n/g,"\n").split("\n"); 
			if (arrData.length > 500){
				mcxDialog.alertC("키워드 조회값을 500 이하로 조회 하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm textarea[name=condition]').focus();
					}
				});
				return false;
			}
		}
		
		// Fetch data
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions, '#searchForm');
	});
	
	// 검색조건 초기화
	$('#btnInit').on('click', function() {
		$("#searchForm")[0].reset();
		$("#multiBrand").empty();
	});
	
	// 파일첨부 선택 시
	$('#detailForm input[name=file]').on('change', function() {
		// multiple 속성이 있으면 files에는 다수의 객체가 할당됨
		var file = this.files[0];

		// 파일 업로드
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/contents/freegoods'
				, file
				, function(result) {
					// 업로드한 파일명 설정
					$('#detailForm input[name=newSysImgNm]').val(result.newFileName);
					$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+"/contents/freegoods/"+result.newFileName);
					$("#imgView").removeClass("off").addClass("on");
				}
		);
	});
	
	// 사은품 저장
	$("#btnSave").on('click', function() {
		
		if(gagajf.isNull($('#detailForm input[name=productNo]').val())){
			mcxDialog.alert("사은품 선택 후 저장하세요.");
			return false;
		}
		
		// 입력 값 체크
		if (!gagajf.validation('#detailForm'))
			return false;
		
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				gagajf.ajaxFormSubmit($('#detailForm').prop('action'), '#detailForm', function() {
					fnDetailFormInit();
					$('#btnSearch').click();
				});
			}
		});
	});
	
	var fnDetailFormInit = function(){
		$("#detailForm")[0].reset();
		$("#bannerPreViewUrl").attr('src', '');
		$("#imgView").removeClass("on").addClass("off");
	}
	
	$(document).ready(function() {
		
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '등록일', true);
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
	});
/*]]>*/
</script>

</html>
