<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsItemkindForm.html
 * @desc    : 품목변경관리 목록
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.10.30   eskim       최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/list'}" onsubmit="return false;">
		<input type="hidden" id="searchGb" name="searchGb" />
 		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<!-- TITLE -->
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<!-- //TITLE -->
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="10%"/>
						<col width="25%"/>
						<col width="10%"/>
						<col width="25%"/>
						<col width="10%"/>
						<col/>
					</colgroup>
					<tr>
						<th>카테고리</th>
						<td colspan="5">
							<input name="siteCd" id="siteCd" type="hidden" value="G000_10"/>
							<input name="selLvl" id="selLvl" type="hidden"/>
							<input name="cateNo" id="cateNo" type="hidden"/>
							<input name="cateType" id="cateType" type="hidden"/>
							<select name="cateGb" id="cateGb" onchange="fnChangeSelect($(this).val(), 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>
							<select id="selCate1" name="cate1No" onchange="fnChangeSelect($(this).val(), 2);">
								<option value="">[카테고리1]</option>
							</select>
							<select id="selCate2" name="cate2No" onchange="fnChangeSelect($(this).val(), 3);">
								<option value="">[카테고리2]</option>
							</select>
							<select id="selCate3" name="cate3No" onchange="fnChangeSelect($(this).val(), 4);">
								<option value="">[카테고리3]</option>
							</select>
							<select id="selCate4" name="cate4No" onchange="fnChangeSelect($(this).val(), 5);">
								<option value="">[카테고리4]</option>
							</select>
							<select id="selCate5" name="cate5No" >
								<option value="">[카테고리5]</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>업체</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>브랜드</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 rowspan="3">키워드</th>
						<td rowspan="3">
							<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 w50p" name="condition" id="condition"></textarea>
						</td>
						
					</tr>
					<tr>
					<th>품목</th>
						<td>
							<input type="text" class="w100" name="itemkindSearchTxt" id="itemkindSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchItemkind"><i class="fa fa-search"></i></button>
							<span id="itemkindText"></span>
							<input type="hidden" name="itemkindList"/>
						</td>
						<th>담당MD</th>
						<td>
							<select  name="mdNo" id="mdNo">
								<option value="">[전체]</option>
								<option th:if="${brandMdList}" th:each="oneData, status : ${brandMdList}" th:value="${oneData.cd}" th:text="${oneData.cdNm}"></option>
							</select>
						</td>
					</tr>
					<tr>
						<th>년도/시즌</th>
						<td>
							<select  name="styleYear" id="styleYear">
								<option value="">[전체]</option>
								<option th:if="${styleYearList}" th:each="oneData, status : ${styleYearList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<select  name="seasonCd" id="seasonCd">
								<option value="">[전체]</option>
								<option th:if="${seasonList}" th:each="oneData, status : ${seasonList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>정상/이월 구분</th>
						<td>
							<select  name="formalGb" id="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>
						
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" id="btnInit" >초기화</button>
						<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="btnGoodsExcelUpLoad">엑셀조회</button>
					<input class="w100" type="text" id="itemKindCd" placeholder="변경할 품목코드" onkeyup="$(this).val($(this).val().replace(/[^a-zA-Z0-9]/gi, '').toUpperCase());" />
					<button type="button" class="btn btn-dark btn-sm" id="btnChangeItemKindCd" >선택 상품 품목코드 변경</button>
					<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
					<strong class="cBlue">* 저장 버튼을 눌러 저장해야 실제로 변경 됩니다.</strong>
				</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="goodsListPagination"></div>
				</li>
			</ul>
		</div>
		</form>
		<!-- //패널 영역2 -->
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	var sessRoleCd = [[${sessionInfo.roleCd}]];
	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('searchForm',params.node.rowIndex, '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=""  onerror="this.src=\'/image/no.png\';"/>';
			}
		},
		{headerName: "브랜드명", field: "brandEnm", width: 130, cellClass: 'text-center'},
		{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'
		
		},
		{headerName: "상품명", field: "goodsNm", width: 200, cellClass: 'text-left'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "품목명", field: "itemkindNm", width: 250, cellClass: 'text-left',
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		},
		{headerName: "기존품목코드", field: "itemkindCd", width: 150, cellClass: 'text-center' },
		{headerName: "변경품목코드", field: "itemkindCdNew", width: 150, cellClass: 'text-center', editable : true,
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 9, required: true, onblur: '$(this).val($(this).val().toUpperCase())' }
		}
	];

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

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

	gridOptions.stopEditingWhenGridLosesFocus = true;

	// Row Click
	gridOptions.onCellClicked = function(event) {
		var goodsCd = event.data.goodsCd;
		if (event.colDef.field == "goodsNm"){
			cfnOpenGoodsDetailPopup('U',goodsCd);
			//cfnOpenFrontGoodsPopup(goodsCd, event.data.siteCd);
		}
	}

	var fnChangeSelect = function(val, selLvl){
		$("#cateNo").val('');
		if (1 < selLvl){ //상품검색용 카테고리 설정
			$("#cateNo").val(val);
		}
		$("#searchForm input[name=selLvl]").val(selLvl);
		$("#searchForm input[name=searchGb]").val("BASIC");
		gagajf.ajaxFormSubmit('/display/category/list', "#searchForm", fnChangeCategory);
	}

	var fnChangeCategory = function(data){
		var selLvl = $("#searchForm input[name=selLvl]").val();
		var html = '<option value="">[선택]</option>';
		for(var i=1; i<6; i++){
			if(i>selLvl){
				$("#selCate"+i).html(html);
			}
		}
		for(var i=0; i<data.length; i++){
			var cd = '';
			var nm = '';
			if(data[i].useYn=='Y'){
				
					cd = data[i].cateNo;
					nm = data[i].cateNm;
					$("#cateType").val(data[i].cateType);
				
				html += '<option value="'+cd+'">['+cd+'] '+nm+'</option>';
			}
		}
		$("#selCate"+selLvl).html(html);
	}

	// 조회
	$('#btnSearch').on('click', function() {
		
		if (event.keyCode === 13) return false;
		
		if(gagajf.isNull($("#selCate2").val()) && gagajf.isNull($("#supplyCompCd").val()) && gagajf.isNull($("#condition").val()) 
			&& gagajf.isNull($("#styleYear").val()) && gagajf.isNull($("#formalGb").val()) && gagajf.isNull($("#mdNo").val())
			&& gagajf.isNull($("#searchForm input[name=supplyCompList]").val()) && gagajf.isNull($("#searchForm input[name=brandList]").val())
			&& gagajf.isNull($("#searchForm input[name=itemkindList]").val())
			){
			mcxDialog.alert('검색조건을 입력해 주세요.');
			return;
		}
		
		$("#searchForm input[name=searchGb]").val("BASIC");
		fnSearch();
	});

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

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

	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.goodsList);
		gagaPaging.createPagination(result.pageing.pageable);
	}

	//엑셀 상품 조회
	$('#btnGoodsExcelUpLoad').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){
		$("#searchForm input[name=searchGb]").val("EXCEL");
		fnSearch();
	}

	$("#btnInit").on("click", function(){
		$("#searchForm")[0].reset();
		$('#searchForm input[name=brandList]').val('');
		$('#searchForm input[name=supplyCompList]').val('');
		$('#searchForm').find('#brandText').html('');
		$('#searchForm').find('#supplyCompText').html('');
		$('#searchForm input[name=itemkindList]').val('');
		$('#searchForm').find('#itemkindText').html('');
	});

	$("#btnChangeItemKindCd").on("click", function(){
		if($("#itemKindCd").val()==''){
			mcxDialog.alert('품목코드를 입력해 주세요.');
			return;
		}
		var selectedData = gagaAgGrid.selectedRowData(gridOptions);
		selectedData.forEach(function(data){
			data.itemkindCdNew = $("#itemKindCd").val();
		});
		gridOptions.api.refreshCells();
	});

	
	// 업체 조회 선택시
	$('#btnSearchSupplyComp').on('click', function() {
		cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M');
	});
	
	// 업체 조회 팝업에서 호출
	var fnSetSupplyCompInfo = function(result) {
		var arrSupplyComp = [];
		var supplyCompText = "";
		var sIndex = 0;
		$('#searchForm').find('#supplyCompText').html('');
		$('#searchForm input[name=supplyCompSearchTxt]').val('');
		result.forEach(function(supplyComp){
			sIndex++; 
			arrSupplyComp.push(supplyComp.supplyCompCd);
		});

		// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=supplyCompSearchTxt]').val(arrSupplyComp[0]);
		}else{
			supplyCompText = sIndex + " 개";
			$('#searchForm').find('#supplyCompText').html(supplyCompText);	
		}
		var jsonData = JSON.stringify(arrSupplyComp);
		$("#searchForm input[name=supplyCompList]").val(jsonData);
	}
	
	// 브랜드 조회 팝업에서 호출
	var fnSetBrandInfo = function(result) {
		var arrbrandCd = [];
		var brandText = "";
		var bIndex = 0;
		$('#searchForm').find('#brandText').html('');
		$('#searchForm input[name=searchTxt]').val('');
		result.forEach(function(brand){
			bIndex++; 
			arrbrandCd.push(brand.brandCd);
		});

		// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리 
		if (bIndex == 1) {
			$('#searchForm input[name=searchTxt]').val(arrbrandCd[0]);
		}else{
			brandText = bIndex + " 개";
			$('#searchForm').find('#brandText').html(brandText);	
		}
		var jsonData = JSON.stringify(arrbrandCd);
		$("#searchForm input[name=brandList]").val(jsonData);
	}
	
	// 브랜드 조회 선택시
	$('#btnSearchBrand').on('click', function() {
		/* if (gagajf.isNull($("#searchForm input[name=searchTxt]").val())){
			mcxDialog.alert('브랜드 검색어를 입력하세요.');
			return false;
		} */
		cfnOpenBrandListPopup('fnSetBrandInfo', 'M');
	});
	
	// 품목 조회 선택시
	$('#btnSearchItemkind').on('click', function() {
		cfnOpenItemkindListPopup('fnSetItemkindInfo', 'M');
	});
	
	// 품목 조회 팝업에서 호출
	var fnSetItemkindInfo = function(result) {
		var arrItemkind = [];
		var itemkindText = "";
		var sIndex = 0;
		$('#searchForm').find('#itemkindText').html('');
		$('#searchForm input[name=itemkindSearchTxt]').val('');
		result.forEach(function(itemkind){
			sIndex++; 
			arrItemkind.push(itemkind.itemkindCd);
		});

		// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=itemkindSearchTxt]').val(arrItemkind[0]);
		}else{
			itemkindText = sIndex + " 개";
			$('#searchForm').find('#itemkindText').html(itemkindText);	
		}
		var jsonData = JSON.stringify(arrItemkind);
		$("#searchForm input[name=itemkindList]").val(jsonData);
	}
	
	$("#btnSave").on("click", function(){
		var rowData = gagaAgGrid.getAllRowData(gridOptions);
		var dataArr = [];
		rowData.forEach(function(row){
			if(typeof row.itemkindCdNew!='undefined' && row.itemkindCdNew!=''){
				var data = {  goodsCd : row.goodsCd
							, itemkindCd : row.itemkindCdNew
				}
				dataArr.push(data);
			}
		});
		if(dataArr.length==0){
			mcxDialog.alert('변경된 데이터가 없습니다.');
			return;
		}
		mcxDialog.confirm('저장하시겠습니까?',{
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(dataArr);
				console.log(jsonData);
				gagajf.ajaxJsonSubmit('/goods/itemKind/change/save', jsonData, fnSearch);
			}
		});
	});
	
	// 업체변경시
	$('#searchForm select[name=supplyCompCd]').on('change', function() {
		var actionUrl = '/renderer/supplyCompany/brand/list/' + $(this).val();
		if(sessRoleCd == "G001_B000"){
			actionUrl = '/renderer/brand/AuthBrandlist';
		}
		$("#searchForm select[name=brandCd] option:gt(0)").remove();

		cfnCreateCombo(actionUrl, $('#searchForm select[name=brandCd]'), "[전체]", "");
	});

	$(document).ready(function() {

		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
	});

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

</html>