<!DOCTYPE html>
<html lang="ko"
	  xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsCategoryForm.html
 * @desc    : 상품별카테고리전시관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.01.13   bin2107     최초 작성
 *******************************************************************************
 -->
<div id="main">
	<!-- 메인타이틀 영역 -->
	<div class="main-title">
	</div>
	<!-- //메인타이틀 영역 -->

	<!-- 메뉴 설명 -->
	<div class="infoBox menu-desc">
	</div>
	<form id="goodsSearchForm" name="goodsSearchForm" action="#" th:action="@{'/display/goods/category/list'}">
		<input type="hidden" id="searchGb" name="searchGb" />
		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<!-- TITLE -->
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 <font color="red">상품코드, 업체, 기간</font>중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<!-- //TITLE -->
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="5%"/>
						<col width="18%"/>
						<col width="5%"/>
						<col width="18%"/>
						<col width="7%"/>
						<col width="22%"/>
						<col width="7%"/>
						<col/>
					</colgroup>
					<tr>
						<th>업체<em class="required" title="필수"></em></th>
						<td>
							<input type="text" class="w100" name="supplyCompSearchTxt" id="supplyCompSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchSupplyComp"><i class="fa fa-search"></i></button>
							<span id="supplyCompText"></span>
							<input type="hidden" name="supplyCompList"/>
						</td>
						<th>브랜드<em class="required" title="필수"></em></th>
						<td>
							<input type="text" class="w100" name="searchTxt" id="searchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchBrand"><i class="fa fa-search"></i></button>
							<span id="brandText"></span>
							<input type="hidden" name="brandList"/>
						</td>
						<th>품목</th>
						<td>
							<div class="multiCheckBox"  style="width:300px">
								<button type="button" class="sltBtn" data-name="[전체]">[전체]</button>
								<ul style="overflow:auto; height:170px;" id="grpItemkind">
									<li><label class="chkBox" onclick="uifnAllCheck(this,'grpItemkind')"><input type="checkbox" name="전체선택" >전체선택</label></li>
									<li th:if="${itemkindList}" th:each="oneData, status : ${itemkindList}"><label class="chkBox" data-group="grpItemkind"><input type="checkbox" name="multiItemkindCd" th:id="${'itemkindCd' + oneData.cd}" th:value="${oneData.cd}" ><th:block th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></th:block></label></li>
								</ul>
							</div>
						</td>
						<th rowspan="4">키워드<em class="required" title="필수"></em></th>
						<td rowspan="4">
							<select name="search" id="search">
								<option value="searchGoodsCd">상품코드</option>
								<option value="searchGoodsNm">상품명</option>
								<option value="searchGoodsNum">품번</option>
								<option value="searchSupplyGoodsCd">업체상품코드</option>
							</select>
							<textarea class="textareaR3 w70p" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>상품상태</th>
						<td>
							<div class="multiCheckBox"  style="width:200px">
								<button type="button" class="sltBtn" data-name="[전체]">[전체]</button>
								<ul style="overflow:auto; height:170px" id="grpGoodsStat">
									<li><label class="chkBox" onclick="uifnAllCheck(this,'grpGoodsStat')"><input type="checkbox" name="전체선택" >전체선택</label></li>
									<li th:if="${goodsStatList}" th:each="oneData, status : ${goodsStatList}"><label class="chkBox" data-group="grpGoodsStat"><input type="checkbox" name="multiGoodsStat" th:id="${'goodsStat' + oneData.cd}" th:value="${oneData.cd}" ><th:block th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></th:block></label></li>
								</ul>
							</div>
						</td>
						<th>이월구분</th>
						<td>
							<select name="formalGb">
								<option value=''>[전체]</option>
								<option th:if="${formalGbList}" th:each="oneData, status : ${formalGbList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>년도/시즌</th>
						<td>
							<div class="multiCheckBox" style="width:140px;">
								<button type="button" class="sltBtn" data-name="[전체]">[전체]</button>
								<ul style="overflow:auto; height:140px" id="grpStyle">
									<li><label class="chkBox" onclick="uifnAllCheck(this,'grpStyle')"><input type="checkbox" name="전체선택" id="multiStyleYear" >전체선택</label></li>
									<li th:if="${styleYearList}" th:each="oneData, status : ${styleYearList}"><label class="chkBox" data-group="grpStyle"><input type="checkbox" name="multiStyleYear" th:id="${'styleYear' + oneData.cd}" th:value="${oneData.cd}" ><th:block th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></th:block></label></li>
								</ul>
							</div>
							<div class="multiCheckBox" style="width:170px;">
								<button type="button" class="sltBtn" data-name="[전체]">[전체]</button>
								<ul style="overflow:auto; height:170px" id="grpSeason">
									<li><label class="chkBox" onclick="uifnAllCheck(this,'grpSeason')"><input type="checkbox" name="전체선택" id="multiSeasonCd" >전체선택</label></li>
									<li th:if="${seasonList}" th:each="oneData, status : ${seasonList}"><label class="chkBox" data-group="grpSeason"><input type="checkbox" name="multiSeasonCd" th:id="${'seasonCd' + oneData.cd}" th:value="${oneData.cd}" ><th:block th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></th:block></label></li>
								</ul>
							</div>
						</td>
					</tr>
					<tr>
						<th>담당MD</th>
						<td>
							<select name="mdId">
								<option value=''>[전체]</option>
								<option th:if="${mdIdList}" th:each="oneData, status : ${mdIdList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>품절여부</th>
						<td>
							<select name="soldoutYn">
								<option value=''>[전체]</option>
								<option value='Y'>[Y] Yes</option>
								<option value='N'>[N] No</option>
							</select>
						</td>
						<th>재고수량</th>
						<td>
							<input type="text" class="w100" name="stockQtySum" maxlength="11" required="required" data-valid-name="재고수량" data-valid-type="numeric"/>개 이상
						</td>
					</tr>
					<tr>
						<th>자사몰노출여부</th>
						<td>
							<select name="selfMallYn">
								<option value=''>[전체]</option>
								<option value='Y'>[Y] Yes</option>
								<option value='N'>[N] No</option>
							</select>
						</td>
						<th>할인율(%)</th>
						<td>
							<input type="text" class="w50" name="dcRateSt" maxlength="3" required="required" data-valid-name="할인율" data-valid-type="numeric"/> ~
							<input type="text" class="w50" name="dcRateEd" maxlength="3" required="required" data-valid-name="할인율" data-valid-type="numeric"/>
						</td>
						<th>판매가</th>
						<td>
							<input type="text" class="w60" name="currPriceSt" required="required" data-valid-name="판매가" data-valid-type="numeric"/>원 ~
							<input type="text" class="w60" name="currPriceEd" required="required" data-valid-name="판매가" data-valid-type="numeric"/>원
						</td>
					</tr>
					<tr>
						<th>반품/교환</th>
						<td colspan='7'>
							<label class="chkBox"><input type="checkbox" name="changeableYn" id="changeableYn"/>반품불가</label>
							<label class="chkBox"><input type="checkbox" name="returnableYn" id="returnableYn"/>교환불가</label>
							<label class="chkBox"><input type="checkbox" name="returnFeeFreeYn" id="returnFeeFreeYn"/>무료반품</label>
							<label class="chkBox"><input type="checkbox" name="changeFeeFreeYn" id="changeFeeFreeYn"/>무료교환</label>
						</td>
					</tr>
					<tr>
						<th>기간</th>
						<td id="sellTerms" colspan='7'></td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" id="btnInit" >초기화</button> <!--onclick="$('#goodsSearchForm')[0].reset();"-->
						<button type="button" class="btn btn-info btn-lg" id="btnSearch" >조회</button>
					</li>
				</ul>
			</div>
			<!-- //검색조건 영역 -->
		</div>
		<!-- 패널 영역1 -->
		<div class="panelStyle">
			<!-- 검색결과 영역 -->
			<!-- 상단버튼 영역  -->
			<ul class="panelBar">
				<li>
					<button type="button" class="btn btn-default btn-lg" onclick="cfnDownloadSampleFile('SF003');">상품엑셀조회 양식 다운로드</button>
					<button type="button" class="btn btn-base btn-lg" id="btnGoodsExcelSearch">엑셀조회</button>
				</li>
				<li class="aR">
					검색결과 : <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 lh60"></div>
			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="goodsCategoryListPagination"></div>
				</li>
			</ul>
		</div>
	</form>
	<!-- //패널 영역2 등록/수정 -->
	<div class="panelStyle">
		<form id="goodsCateForm" name="goodsCateForm" action="#" th:action="@{'/display/goods/category/save'}">
			<table class="frmStyle">
				<colgroup>
					<col style="width:20%;"/>
					<col style="width:20%;"/>
					<col style="width:20%;"/>
					<col style="width:20%;"/>
					<col style="width:20%;"/>
				</colgroup>
				<tr>
					<th>카테고리구분</th>
					<th>카테고리1</th>
					<th>카테고리2</th>
					<th>카테고리3</th>
					<th>카테고리4</th>
				</tr>
				<th:block th:each="num, index  : ${#numbers.sequence(1,4)}">
					<tr>
						<td>
							<select th:id="selCate+${num}+1" th:onchange="|fnChangeSelect($(this).val(), ${num}, 1);|">
								<option value="">[선택]</option>
								<option th:if="${cateGbList}" th:each="oneData, status : ${cateGbList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<td>
							<select name="cateCd1Arr" th:id="selCate+${num}+2" th:onchange="|fnChangeSelect($(this).val(), ${num}, 2);|">
								<option value="">[선택]</option>
							</select>
						</td>
						<td>
							<select name="cateCd2Arr" th:id="selCate+${num}+3" th:onchange="|fnChangeSelect($(this).val(), ${num}, 3);|">
								<option value="">[선택]</option>
							</select>
						</td>
						<td>
							<select name="cateCd3Arr" th:id="selCate+${num}+4" th:onchange="|fnChangeSelect($(this).val(), ${num}, 4);|">
								<option value="">[선택]</option>
							</select>
						</td>
						<td>
							<select name="cateCd4Arr" th:id="selCate+${num}+5" th:onchange="|fnChangeSelect($(this).val(), ${num}, 5);|">
								<option value="">[선택]</option>
							</select>
							<input type="hidden" th:id='cateCd+${num}' name='cateCdArr' value='' />
							<input type="hidden" th:id='cateGb+${num}' name='cateGbArr' value='' />
							<input type="hidden" th:id='leafYn+${num}' value='' />
							<input type="hidden" th:id='cateType+${num}' name='cateTypeArr' value='' />
						</td>
					</tr>
				</th:block>
			</table>
			<ul class="panelBar">
				<li class="center">
					<button type="button" class="btn btn-default btn-lg" id="btnCateInit">초기화</button>
					<button type="button" class="btn btn-success btn-lg" id="btnCateSave">전시저장</button>
					<input type="hidden" id='goodsCds' name='goodsCds' value='' />
					<input type="hidden" name='selLvl' value='' />
					<input type="hidden" name='cateIndex' value='' />
				</li>
			</ul>
		</form>
	</div>

	<!-- 카테고리 리스트 영역 -->
	<div class="panelStyle">
		<form id="deleteForm" name="deleteForm" action="#" th:action="@{'/display/goods/category/delete'}">
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btn btn-danger btn-lg" id="btnCateDelete">전시삭제</button>
					<input type="hidden" name='goodsCd' value='' />
				</li>
			</ul>
			<div id="gridCategoryList" style="width: 100%; height: 500px;" class="ag-theme-balham"></div>
		</form>
	</div>
	<!-- //카테고리 리스트 영역 -->


	<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
	<script th:inline="javascript">
		/*<![CDATA[*/
		var goodsStatList = gagajf.convertToArray([[${goodsStatList}]]);
		var cateGbList = gagajf.convertToArray([[${cateGbList}]]);
		var columnDefs = [];
		columnDefs = [
			{width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
			{headerName: 'No', width: 60, cellClass: 'text-center',
				valueGetter: function(params) { return cfnGridNumner('goodsSearchForm',params.node.rowIndex, 'A');}
			},
			{headerName: "카테고리", field: "fullCateNm", width: 140, cellClass: 'text-center'
				,cellRenderer: function(params) {
					return '<a href="javascript:void(0);">'+params.value+'</a>';
				}
			},
			{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: "brandCd", width: 80, cellClass: 'text-center'},
			{headerName: "브랜드명", field: "brandEnm", width: 130, cellClass: 'text-center'},
			{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'},
			{headerName: "상품명", field: "goodsNm", width: 350, cellClass: 'text-left'
				,cellRenderer: function(params) {
					return '<a href="javascript:void(0);">' + params.value + '</a>';
				}
			},
			{headerName: "기존품목코드", field: "itemkindCd", width: 150, cellClass: 'text-center' },
			{headerName: "품목", field: "itemkindNm", width: 150, cellClass: 'text-center',
				cellRenderer: function (params) {
					if (gagajf.isNull( params.value)){
						return  params.value;
					}else{
						return  params.value.replaceAll("&gt;", ">");
					}
				}	
			},
			{headerName: "전시재고", field: "stockQtySum", width: 120, cellClass: 'text-right',
				valueFormatter: function(params) {	return params.value.addComma();},
				cellStyle : function(params){
					if ("00" == params.data.goodsStat  || "10" == params.data.goodsStat || "20" == params.data.goodsStat || "30" == params.data.goodsStat) {
						return;
					}
					var color = "";
					if (params.value <= 0){
						color = '#ff96689c';
					}
					return { 'background-color': color};
				}
			},
			{headerName: "상품타입", field: "goodsType" , width: 100, cellClass: 'text-center'},
			// {headerName: "년도", field: "styleYear" , width: 80, cellClass: 'text-center'},
			// {headerName: "시즌", field: "seasonCd" , width: 80, cellClass: 'text-center',
			// 	cellEditorParams: { values: gagaAgGrid.extractValues(seasonList) },
			// 	valueFormatter: function (params) { return gagaAgGrid.lookupValue(seasonList, params.value); },
			// 	valueParser: function (params) { return gagaAgGrid.lookupKey(seasonList, params.newValue); }
			// },
			{headerName: "정상가", field: "listPrice", width: 80, cellClass: 'text-right',
				valueFormatter: function(params) {return Number(params.value).addComma()}
			},
			{headerName: "판매가", field: "currPrice", width: 80, cellClass: 'text-right',
				valueFormatter: function(params) {return Number(params.value).addComma()}
			},
			{headerName: "할인율", field: "dcRate", width: 80, cellClass: 'text-right'},
			{headerName: "포인트적립율(PC)", field: "pntPrate", width: 80, cellClass: 'text-right'},
			{headerName: "선포인트사용가능여부(PC)", field: "prePpntUsableYn", width: 80, cellClass: 'text-right'},
			{headerName: "포인트적립율(모바일)", field: "pntMrate", width: 80, cellClass: 'text-right'},
			{headerName: "선포인트사용가능여부(모바일)", field: "preMpntUsableYn", width: 80, cellClass: 'text-right'},
			{headerName: "정상/이월", field: "formalGb", width: 80, cellClass: 'text-right'},
			{headerName: "상품상태", field: "goodsStat" , width: 100, cellClass: 'text-center',
				cellEditorParams: { values: gagaAgGrid.extractValues(goodsStatList) },
				valueFormatter: function (params) { return gagaAgGrid.lookupValue(goodsStatList, params.value); },
				valueParser: function (params) { return gagaAgGrid.lookupKey(goodsStatList, params.newValue); }
			}
			//{headerName: "판매가능재고", field: "currStockQty", width: 100, cellClass: 'text-right'}, // 추후 추가해야함 ㅠㅠ
			//{headerName: "품절여부", field: "soldoutYn", width: 80, cellClass: 'text-center'}, // 추후 추가해야함 ㅠㅠ
			/*{headerName: "품목명", field: "itemkindNm", width: 250, cellClass: 'text-left'},
            {headerName: "기존품목코드", field: "itemkindCd", width: 150, cellClass: 'text-center' },
            {headerName: "변경품목코드", field: "itemkindCdNew", width: 150, cellClass: 'text-center', editable : true,
                cellEditor: 'textCellEditor',
                cellEditorParams: { maxlength: 5, required: true, onblur: '$(this).val($(this).val().toUpperCase())' }
            }*/
		];

		var columCategoryDefs = [
			{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
			{headerName: "자동전시카테고리코드", field: "cateCd", width: 150, cellClass: 'text-center'},
			{headerName: "자동전시카테고리", field: "fullCateNm", width: 400, cellClass: 'text-left',
				cellRenderer: function (params) {
					if (gagajf.isNull( params.value)){
						return  params.value;
					}else{
						return  params.value.replaceAll("&gt;", ">");
					}
				}
			},
			{headerName: "카테고리1", field: "cateCd1", width: 150, cellClass: 'text-left', hide: true},
			{headerName: "카테고리2", field: "cateCd2", width: 150, cellClass: 'text-left', hide: true},
			{headerName: "카테고리3", field: "cateCd3", width: 150, cellClass: 'text-left', hide: true},
			{headerName: "카테고리4", field: "cateCd4", width: 150, cellClass: 'text-left', hide: true},
			{headerName: "상품코드", field: "goodsCd", width: 150, cellClass: 'text-left', hide: true}
		];

		// Get GridOptions
		var gridOptions = gagaAgGrid.getGridOptions(columnDefs);
		var gridCategoryOptions = gagaAgGrid.getGridOptions(columCategoryDefs);

		// 중복 선택 가능
		gridOptions.rowSelection = 'multiple';
		gridOptions.suppressRowClickSelection = true;
		gridOptions.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
		gridOptions.stopEditingWhenGridLosesFocus = true;

		gridCategoryOptions.rowSelection = 'multiple';
		gridCategoryOptions.suppressRowClickSelection = true;

		gridOptions.onCellClicked = function(event) {
			if(event.colDef.field == "fullCateNm"){
				$('#deleteForm input[name=goodsCd]').val(event.data.goodsCd);
				fnDisplayCategorySearch();
				$(window).scrollTop($(window).height());
			}
		}

		// 상품별 전시카테고리 조회
		var fnDisplayCategorySearch = function(){
			var goodsCd = $('#deleteForm input[name=goodsCd]').val();
			var actionUrl = "/display/goods/category/view/list?goodsCd=" + goodsCd;
			gagaAgGrid.fetch(actionUrl, gridCategoryOptions);
		}

		// 조회클릭시
		$('#btnSearch').on('click', function() {
			$("#goodsSearchForm input[name=pageNo]").val('1');
			fnGoodsListSearch('BASIC');
		});

		// 조회
		var fnGoodsListSearch = function (gbn){
			if (typeof(gbn) != 'undefined' &&  gbn == 'EXCEL'){
				$("#goodsSearchForm input[name=searchGb]").val("EXCEL");
			}else{
				$("#goodsSearchForm input[name=searchGb]").val("BASIC");
			}

			if(!fnConditionCheck()) return;

			$('#goodsSearchForm input[name=changeableYn]').val($("#changeableYn").prop('checked')? 'N':'');
			$('#goodsSearchForm input[name=returnableYn]').val($("#returnableYn").prop('checked')? 'N':'');
			$('#goodsSearchForm input[name=returnFeeFreeYn]').val($("#returnFeeFreeYn").prop('checked')? 'Y':'');
			$('#goodsSearchForm input[name=changeFeeFreeYn]').val($("#changeFeeFreeYn").prop('checked')? 'Y':'');

			gagaPaging.init('goodsSearchForm', fnSearchCallBack, 'goodsCategoryListPagination', $('#goodsSearchForm').find('#pageSize').val());
			gagaPaging.load($("#goodsSearchForm input[name=pageNo]").val());
		}

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

			if (event.keyCode === 13) return false;

			if($("#goodsSearchForm input[name=searchGb]").val() == "EXCEL") return true;

			var searchFlag = false;
			var cnt = 0;

			if( !gagajf.isNull($("#goodsSearchForm input[name=supplyCompList]").val())
					|| !gagajf.isNull($("#goodsSearchForm textarea[name=condition]").val())
					|| (!gagajf.isNull($("#goodsSearchForm input[name=stDate]").val()) && !gagajf.isNull($("#goodsSearchForm input[name=edDate]").val()))
					|| !gagajf.isNull($("#goodsSearchForm input[name=brandList]").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(!gagajf.isNull($("#goodsSearchForm input[name=currPriceSt]").val()) && !gagajf.isNull($("#goodsSearchForm input[name=currPriceEd]").val())){
				if (Number($("#goodsSearchForm input[name=currPriceSt]").val().removeComma()) > Number($("#goodsSearchForm input[name=currPriceEd]").val().removeComma()) ){
					mcxDialog.alertC("판매가를 확인해 주세요.", {
						sureBtnText: "확인",
						sureBtnClick: function() {
							$("#goodsSearchForm input[name=currPriceEd]").focus();
						}
					});
					return false;
				}
			}

			if(!gagajf.isNull($("#goodsSearchForm input[name=dcRateSt]").val()) && !gagajf.isNull($("#goodsSearchForm input[name=dcRateEd]").val())){
				if (Number($("#goodsSearchForm input[name=dcRateSt]").val().removeComma()) > Number($("#goodsSearchForm input[name=dcRateEd]").val().removeComma()) ){
					mcxDialog.alertC("할인율를 확인해 주세요.", {
						sureBtnText: "확인",
						sureBtnClick: function() {
							$("#goodsSearchForm input[name=dcRateEd]").focus();
						}
					});
					return false;
				}
			}

			var fromDate = $('#goodsSearchForm input[name=stDate]').val();
			var toDate = $('#goodsSearchForm input[name=edDate]').val();

			if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {

				if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
					mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
						sureBtnText: "확인",
						sureBtnClick: function() {
							$('#goodsSearchForm input[name=stDate]').focus();
						}
					});
					return false;
				}

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

			if (!gagajf.isNull($('#goodsSearchForm textarea[name=condition]').val())){
				var arrData = $('#goodsSearchForm textarea[name=condition]').val().replace(/\r\n/g,"\n").split("\n");
				if (arrData.length > 500){
					mcxDialog.alertC("키워드 조회값을 500 이하로 조회 하세요.", {
						sureBtnText: "확인",
						sureBtnClick: function() {
							$('#goodsSearchForm textarea[name=condition]').focus();
						}
					});
					return false;
				}
			}
			return true;
		}

		// 조회
		$('#btnSearch2').on('click', function() {
			if(gagajf.isNull($("#goodsSearchForm select[name=supplyCompCd]").val())
					&& gagajf.isNull($("#goodsSearchForm input[name=goodsCd]").val())
					&& (gagajf.isNull($("#goodsSearchForm input[name=stDate]").val()) && gagajf.isNull($("#goodsSearchForm input[name=edDate]").val()))){
				mcxDialog.alert('검색조건을 입력해 주세요.');
				return;
			}

			$('#goodsSearchForm input[name=changeableYn]').val($("#changeableYn").prop('checked')? 'N':'');
			$('#goodsSearchForm input[name=returnableYn]').val($("#returnableYn").prop('checked')? 'N':'');
			$('#goodsSearchForm input[name=returnFeeFreeYn]').val($("#returnFeeFreeYn").prop('checked')? 'Y':'');
			$('#goodsSearchForm input[name=changeFeeFreeYn]').val($("#changeFeeFreeYn").prop('checked')? 'Y':'');
			$("#goodsSearchForm input[name=searchGb]").val("BASIC");
			fnSearch();
		});

		$("#pageSize").on("change", function(){
			var rowCnt = gridOptions.api.getDisplayedRowCount();
			if(rowCnt > 0){
				fnSearch();
			}
		});

		var fnSearch = function(){
			gagaPaging.init('goodsSearchForm', fnSearchCallBack, 'goodsCategoryListPagination', $('#goodsSearchForm').find('#pageSize').val());
			gagaPaging.load(1);
		};

		var fnSearchCallBack = function(result){

			$('#goodsSearchForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
			$('#goodsSearchForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
			$('#goodsSearchForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
			$('#goodsSearchForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
			gridOptions.api.setRowData(result.goodsCategoryList);
			gagaPaging.createPagination(result.pageing.pageable);
		}

		// 카테고리 selectBox 변경
		var fnChangeSelect = function(val, cateIndex, selLvl){
			$("#cateCd"+cateIndex).val('');
			$("#cateGb"+cateIndex).val('');
			$("#leafYn"+cateIndex).val('');

			if (gagajf.isNull(val)) {
				if (selLvl > 1) {
					selLvl = selLvl - 1;
					if(selLvl>1){
						$("#cateCd"+cateIndex).val($("#selCate"+cateIndex+''+(selLvl-1)).val().split(',')[0]);
						$("#leafYn"+cateIndex).val($("#selCate"+cateIndex+''+(selLvl-1)).val().split(',')[1]);
					}
				} else {
					//selLvl = 1;
					var html = '<option value="">[선택]</option>';
					for(var i=2; i<6; i++){
						$("#selCate"+cateIndex+''+i).html(html);
					}
					return;
				}
			}else if(selLvl>1){
				$("#cateCd"+cateIndex).val(val.split(',')[0]);
				$("#leafYn"+cateIndex).val(val.split(',')[1]);
			}
			$("#goodsCateForm input[name=selLvl]").val(selLvl+1);
			$("#goodsCateForm input[name=cateIndex]").val(cateIndex);

			var cateGb = $('#selCate'+cateIndex+'1').val();
			var cate1No = $('#selCate'+cateIndex+'2').val().split(',')[0];
			var cate2No = $('#selCate'+cateIndex+'3').val().split(',')[0];
			var cate3No = $('#selCate'+cateIndex+'4').val().split(',')[0];
			var cate4No = $('#selCate'+cateIndex+'5').val().split(',')[0];

			$("#cateGb"+cateIndex).val(cateGb);
			if(selLvl==5 || (val=='' && selLvl==4)){
				return;
			}

			var data = { siteCd : 'G000_10'
				, selLvl : selLvl
				,cateGb : cateGb
				,cate1No : cate1No
				,cate2No : cate2No
				,cate3No : cate3No
				,cate4No : cate4No
			};

			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/display/category/list', jsonData, fnChangeCate);
		}

		var fnChangeCate = function(data){
			var selLvl = $("#goodsCateForm input[name=selLvl]").val();
			var cateIndex = $("#goodsCateForm input[name=cateIndex]").val();
			var html = '<option value="">[선택]</option>';

			for(var i=0; i<6; i++){
				i = i+1;
				if(i>selLvl){
					$("#selCate"+cateIndex+''+i).html(html);
				}
			}

			for(var i=0; i<data.length; i++){
				var cd = '';
				var nm = '';
				var leafYn = '';

				if(data[i].useYn=='Y'){
					if(selLvl=='1'){
						cd = data[i].cateGb;
						nm = gagaAgGrid.lookupValue(cateGbList, cd);
					}else{
						cd = data[i].cateNo;
						nm = data[i].cateNm;
						leafYn = ','+data[i].leafYn;
						$("#cateType"+cateIndex).val(data[i].cateType);
					}
					html += '<option value="'+cd+leafYn+'">['+cd+'] '+nm+'</option>';
				}
			}
			$("#selCate"+cateIndex+''+selLvl).html(html);
		}

		// 카테고리 저장
		$("#btnCateSave").on('click', function() {
			var data = gridOptions.api.getSelectedRows();
			if(data.length == 0){
				mcxDialog.alert('상품을 선택하세요.');
				return false;
			}

			var msgArr = ['', '첫 번째', '두 번째', '세 번째', '네 번째'];
			var cateCdBool = false;

			for(var i=1; i<5; i++){
				if($("#cateCd"+i).val()!=''){
					cateCdBool = true;
					if($("#leafYn"+i).val()!='Y'){
						mcxDialog.alert(msgArr[i]+' 행의 leaf카테고리를 선택하세요.');
						return;
					}
				}else if($("#cateGb"+i).val()!=''){
					mcxDialog.alert(msgArr[i]+' 행의 leaf카테고리를 선택하세요.');
					return;
				}
			}
			if(!cateCdBool){
				mcxDialog.alert('전시할 카테고리를 선택하세요.');
				return;
			}
			var goodsCdS = '';
			data.forEach(function(row){
				if (goodsCdS!=''){
					goodsCdS += ','
				}
				goodsCdS += row.goodsCd;
			});
			$("#goodsCds").val(goodsCdS);

			mcxDialog.confirm('저장하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){ //debugger;
					gagajf.ajaxFormSubmit($('#goodsCateForm').prop('action'), "#goodsCateForm", fnGoodsCateCallBack);
				}
			});
		});

		// 검색조건 초기화
		$('#btnCateInit').on('click', function() {
			$("#goodsCateForm")[0].reset();
			var html = '<option value="">[선택]</option>';
			for(var i=2; i<6; i++){
				for(var j=1; j<5; j++){
					$("#selCate"+j+''+i).html(html);
				}
			}
			for(var i=1; i<5; i++){
				$("#cateCd"+i).val('');
				$("#cateGb"+i).val('');
				$("#leafYn"+i).val('');
			}
			
		});

		// 전시카테고리 삭제
		$("#btnCateDelete").on("click", function(){
			var selectData = gridCategoryOptions.api.getSelectedRows();
			if(selectData.length == 0){
				mcxDialog.alert('삭제할 카테고리를 선택하세요.');
				return false;
			}

			var data = {
				goodsList : selectData
			};

			var jsonData = JSON.stringify(data);
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					gagajf.ajaxJsonSubmit($('#deleteForm').prop('action'), jsonData, fnGoodsCateCallBack);
				}
			});
		});

		// 저장,삭제 콜백
		var fnGoodsCateCallBack = function(){
			$('#btnCateInit').click();
			fnDisplayCategorySearch();
		};

		// 엑셀 상품 조회
		$("#btnGoodsExcelSearch").on('click', function(){
			cfnExcelUploadPopup('goodsExcelUpload', 'goodsExcelUpload');
		});

		var goodsExcelUpload = function(result){
			var data = {procJob : result.procJob
				,excelFileNm : result.excelFileNm
			};
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnGoodsExcelUploadCallBack);
		}

		var fnGoodsExcelUploadCallBack = function(result){
			$("#goodsSearchForm input[name=searchGb]").val("EXCEL");
			fnSearch();
		}

		// 업체 조회 선택시
		$('#btnSearchSupplyComp').on('click', function() {
			cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M');
		});

		// 업체 조회 팝업에서 호출
		var fnSetSupplyCompInfo = function(result) {
			var arrSupplyComp = [];
			var supplyCompText = "";
			var sIndex = 0;
			$('#goodsSearchForm').find('#supplyCompText').html('');
			$('#goodsSearchForm input[name=supplyCompSearchTxt]').val('');
			result.forEach(function(supplyComp){
				sIndex++;
				arrSupplyComp.push(supplyComp.supplyCompCd);
			});

			// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리
			if (sIndex == 1) {
				$('#goodsSearchForm input[name=supplyCompSearchTxt]').val(arrSupplyComp[0]);
			}else{
				supplyCompText = sIndex + " 개";
				$('#goodsSearchForm').find('#supplyCompText').html(supplyCompText);
			}
			var jsonData = JSON.stringify(arrSupplyComp);
			$("#goodsSearchForm input[name=supplyCompList]").val(jsonData);
		}

		// 브랜드 조회 선택시
		$('#btnSearchBrand').on('click', function() {
			cfnOpenBrandListPopup('fnSetBrandInfo', 'M');
		});

		// 브랜드 조회 팝업에서 호출
		var fnSetBrandInfo = function(result) {
			var arrbrandCd = [];
			var brandText = "";
			var bIndex = 0;
			$('#goodsSearchForm').find('#brandText').html('');
			$('#goodsSearchForm input[name=searchTxt]').val('');
			result.forEach(function(brand){
				bIndex++;
				arrbrandCd.push(brand.brandCd);
			});

			// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리
			if (bIndex == 1) {
				$('#goodsSearchForm input[name=searchTxt]').val(arrbrandCd[0]);
			}else{
				brandText = bIndex + " 개";
				$('#goodsSearchForm').find('#brandText').html(brandText);
			}
			var jsonData = JSON.stringify(arrbrandCd);
			$("#goodsSearchForm input[name=brandList]").val(jsonData);
		}

		// 초기화 클릭시
		$('#btnInit').on('click', function() {

			$('#goodsSearchForm')[0].reset();
			//$("#searchForm input[type=radio]").removeClass("checked");
			$("#goodsSearchForm input[type=checkbox]").removeClass("checked");
			//$("#searchForm input[type=radio]").parent("label").removeClass("checked");
			$("#goodsSearchForm input[type=checkbox]").parent("label").removeClass("checked");
			$("#goodsSearchForm input[type=radio][checked]").parent("label").addClass("checked");
			$("#multiBrand").empty();
			$('#goodsSearchForm input[name=brandList]').val('');
			$('#goodsSearchForm input[name=supplyCompList]').val('');
			$('#goodsSearchForm').find('#brandText').html('');
			$('#goodsSearchForm').find('#supplyCompText').html('');
			
			$(document).find('#goodsSearchForm').find(".multiCheckBox").each(function(i, e){
				let btnNm = $(this).find(".sltBtn").attr("data-name");
				$(this).find(".sltBtn").text(btnNm);
			});
		});

		$(document).ready(function() {
			cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '기간', 'X');
			// Create a agGrid
			gagaAgGrid.createGrid('gridList', gridOptions);
			gagaAgGrid.createGrid('gridCategoryList', gridCategoryOptions);
		});

		/*]]>*/
	</script>
</div>

</html>