<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsSizeStockForm.html
 * @desc    : 상품 사이즈별 재고 현황
 *============================================================================
 * SISUN
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.17   eskim       수정
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<form id="goodsSizeStockForm" name="goodsSizeStockForm" action="#" th:action="@{'/stock/sizeStock/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>
				<span class="panelControl">
					<i class="fa fa-chevron-up"></i>
				</span>
			</div>
			<!-- //TITLE -->
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="9%"/>
						<col width="16%"/>
						<col width="9%"/>
						<col width="16%"/>
						<col width="9%"/>
						<col width="16%"/>
						<col width="9%"/>
						<col/>
					</colgroup>
					<tr>
						<th>업체/브랜드<em class="required" title="필수"></em></th>
						<td colspan="3">
							<select name="supplyCompCd" id="supplyCompCd">
								<option value="" >[전체]</option>
								<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<select name="brandCd" id="brandCd">
								<option value="">[전체]</option>
							</select>
						</td>
						<th>품목</th>
						<td colspan="3">
							<select name="itemkindCd" id="itemkindCd">
								<option value="">[전체]</option>
								<option th:if="${itemkindList}" th:each="oneData, status : ${itemkindList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
					</tr>
					<tr>
						<th>키워드<em class="required" title="필수"></em></th>
						<td colspan="3">
							<select name="search" id="search">
								<option value="searchGoodsCd">상품코드</option>
								<option value="searchGoodsNm">상품명</option>
								<option value="searchGoodsNum">품번</option>
								<option value="searchSupplyGoodsCd">업체상품코드</option>
							</select>
							<input type="text" class="w150" name="condition" id="condition" maxlength="50"/>
						</td>
						<th>상품상태</th>
						<td>
							<select  name="goodsStat" id="goodsStat">
								<option value="">[전체]</option>
								<option th:if="${goodsStatList}" th:each="oneData, status : ${goodsStatList}" 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>
					<tr>	
						<th>년도/시즌</th>
						<td colspan="3">
							<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="optCd1" id="optCd1">
								<option value="">[전체]</option>
								<option th:if="${colorList}" th:each="oneData, status : ${colorList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>사이즈</th>
						<td>
							<input type="text" class="w80" name="optCd2" id="optCd2" maxlength="50"/>
						</td>
						
					</tr>
					<tr>
						<th>품절여부</th>
						<td>
							<select  name="soldOutYn" id="soldOutYn">
								<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>담당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>
						<th>재고수량</th>
						<td colspan="3">
							<input type="text" class="w70" name="stockQtySt" id="stockQtySt" maxlength="5" data-valid-type="numeric"/> ~ <input type="text" class="w70" name="stockQtyEd" id="stockQtyEd" maxlength="5" data-valid-type="numeric"/>
						</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 class="left">
					<select id="excelSample" name="excelSample">
						<option value="">[선택]</option>
						<option value="SF003">상품엑셀조회양식</option>
						<option value="SF008" th:if="${sessionInfo.roleCd == 'G001_B000' }">상품사이즈품절/안전재고양식</option>
						<option value="EXCELDOWN">엑셀다운로드</option>
					</select>
					<button type="button" class="btn btn-default btn-lg" id="btnExcelSampleDownLoad">다운로드</button>
					<button type="button" class="btn btn-base btn-lg" id="btnGoodsExcelSearch">엑셀조회</button>
					<button type="button" class="btn btn-success btn-lg" id="btnGoodsExcelSave" th:if="${sessionInfo.roleCd == 'G001_B000' }">품절/안전재고 저장</button>
				</li>
				<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="100" selected="selected">100개씩 보기</option>
						<option value="500">500개씩 보기</option>
						<option value="1000">1000개씩 보기</option>
						<option value="5000">5000개씩 보기</option>
					</select>
					<input type="hidden" name="pageNo" id="pageNo" value ="1"/>
				</li>
			</ul>
			<!-- //상단버튼 영역  -->
			<div id="gridList" style="width: 100%; height:550px" class="ag-theme-balham"></div>
			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="goodsListPagination"></div>
				</li>
			</ul>
			<!-- 검색결과 영역 -->
		</div>
		<label class="off">
			<a href="javascript:void(0);" id="GoodsSizeStockExcelList" style="display: none;">사이즈별 재고현황 엑셀다운로드</a>
		</label>
		</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 goodsStatList = gagajf.convertToArray([[${goodsStatList}]]);
	var formalGbList = gagajf.convertToArray([[${formalGbList}]]);
	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('goodsSizeStockForm',params.node.rowIndex, 'A');}
		},
		{headerName: "브랜드명", field: "brandEnm", width: 130, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 200, cellClass: 'text-left'},
		{headerName: "품목", field: "itemkindNm", width: 180, cellClass: 'text-left'},
		{headerName: "상품상태", field: "goodsStat" , width: 120, 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: "goodsCd", width: 140, cellClass: 'text-center',
			cellRenderer: function(params) {
				if (params.data.sizeSoldoutYn == "Y"){
					return '<a href="javascript:void(0);" style="color:red">' + params.value + '</a>';
				}else{
					return '<a href="javascript:void(0);">' + params.value + '</a>';	
				}
			}	
		},
		{headerName: "색상", field: "optCd1", width: 100, cellClass: 'text-center'},
		{headerName: "사이즈", field: "optCd2", width: 100, cellClass: 'text-center'},
		{headerName: "품절여부", field: "soldoutYn", width: 100, cellClass: 'text-center',
			cellStyle : function(params){
				var color = "";
				if (params.value == "Y"){
					color = "red";
				}
				return { 'color': color}
			} 
		},
		
		{headerName: "재고", field: "currStockQty", width: 100, cellClass: 'text-right',
			valueFormatter: function(params) {	return params.value.addComma();}
		},
		{headerName: "안전재고", field: "baseStockQty", width: 100, cellClass: 'text-right',
			valueFormatter: function(params) {	return params.value.addComma();}
		},
		{headerName: "출고대기", field: "saleStockQty", width: 100, cellClass: 'text-right',
			valueFormatter: function(params) {	return params.value.addComma();}
		},
		{headerName: "판매가능재고", field: "ableStockQty", width: 100, cellClass: 'text-right',
			valueFormatter: function(params) {	return params.value.addComma();},
			cellStyle : function(params){
				var color = "";
				if (params.value <= 0){
					color = '#ff96689c';
				}
				return { 'background-color': color};
			}
		}
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

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

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

	gridOptions.getRowStyle = function(params) {
		if ("G008_00" == params.data.goodsStat  || "G008_10" == params.data.goodsStatG008_ || "20" == params.data.goodsStat || "G008_30" == params.data.goodsStat) {
			return { background: '#23c6c8' };
		}
	}
	
	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		fnInit();
	});
	
	var fnInit = function(){
		
		$('#goodsSizeStockForm')[0].reset();
		//$("#goodsSizeStockForm input[type=radio]").removeClass("checked");
		$("#goodsSizeStockForm input[type=checkbox]").removeClass("checked");
		//$("#goodsSizeStockForm input[type=radio]").parent("label").removeClass("checked");
		$("#goodsSizeStockForm input[type=checkbox]").parent("label").removeClass("checked");
		//$("#goodsSizeStockForm input[type=radio][checked]").parent("label").addClass("checked");
		$("#goodsSizeStockForm select[name=supplyCompCd]").val([[${sessionInfo.supplyCompCd}]]);
		fnSupplyBrandInit();
	}
	
	// 조회클릭시
	$('#btnSearch').on('click', function() {
		$("#goodsSizeStockForm input[name=pageNo]").val('1');
		fnGoodsListSearch('BASIC');
	});

	// 조회
	var fnGoodsListSearch = function(gbn) {
		
		if (typeof(gbn) != 'undefined' &&  gbn == 'EXCEL'){
			$("#goodsSizeStockForm input[name=searchGb]").val("EXCEL");
		}else if (typeof(gbn) != 'undefined' &&  gbn == 'EXCELRESULT'){
			$("#goodsSizeStockForm input[name=searchGb]").val("EXCELRESULT");
		}else{
			$("#goodsSizeStockForm input[name=searchGb]").val("BASIC");
		}
		
		if(!fnConditionCheck()) return;
		
		gagaPaging.init('goodsSizeStockForm', fnSearchCallBack, 'goodsListPagination', $('#goodsSizeStockForm').find('#pageSize').val());
		gagaPaging.load($("#goodsSizeStockForm input[name=pageNo]").val());
	}

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

		if($("#goodsSizeStockForm input[name=searchGb]").val() == "EXCEL" || $("#goodsSizeStockForm input[name=searchGb]").val() == "EXCELRESULT") {
			return true;
		}
		
		var searchFlag = false;
		var cnt = 0;

		/* if( !gagajf.isNull($("#goodsSizeStockForm select[name=supplyCompCd]").val())
				|| !gagajf.isNull($("#goodsSizeStockForm input[name=condition]").val())
				|| (!gagajf.isNull($("#goodsSizeStockForm input[name=stDate]").val()) && !gagajf.isNull($("#goodsSizeStockForm 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" && el.name != "excelSample")) {
					if (!(el.value == null || el.value == "")) {
						cnt++;
					}
				}
			}

			if(cnt > 0) searchFlag = true;
			
		/* } */
		
		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		
		/* if(!gagajf.isNull($("#goodsSizeStockForm input[name=currPriceSt]").val()) && !gagajf.isNull($("#goodsSizeStockForm input[name=currPriceEd]").val())){
			if (Number($("#goodsSizeStockForm input[name=currPriceSt]").val().removeComma()) > Number($("#goodsSizeStockForm input[name=currPriceEd]").val().removeComma()) ){
				mcxDialog.alertC("판매가를 확인해 주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$("#goodsSizeStockForm input[name=currPriceEd]").focus();
					}
				});
				return false;
			}
		} */
		
		/* if(!gagajf.isNull($("#goodsSizeStockForm input[name=dcRateSt]").val()) && !gagajf.isNull($("#goodsSizeStockForm input[name=dcRateEd]").val())){
			if (Number($("#goodsSizeStockForm input[name=dcRateSt]").val().removeComma()) > Number($("#goodsSizeStockForm input[name=dcRateEd]").val().removeComma()) ){
				mcxDialog.alertC("할인율를 확인해 주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$("#goodsSizeStockForm input[name=dcRateEd]").focus();
					}
				});
				return false;
			}
		} */
		
		/* var fromDate = $('#goodsSizeStockForm input[name=stDate]').val();
		var toDate = $('#goodsSizeStockForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#goodsSizeStockForm input[name=stDate]').focus();
					}
				});
				return false;
			}

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

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

	
	//업체변경시
	$('#goodsSizeStockForm select[name=supplyCompCd]').on('change', function() {
		var supplyCompCd = $(this).val();
		
		var actionUrl = '/renderer/supplyCompany/brand/list/' + supplyCompCd;

		if(sessRoleCd == "G001_B000"){
			actionUrl = '/renderer/brand/AuthBrandlist';
		}
		$("#goodsSizeStockForm select[name=brandCd] option:gt(0)").remove();

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

	});
	
	//엑셀양식 다운로드
	$('#btnExcelSampleDownLoad').on('click', function (){
		var gb = $("#goodsSizeStockForm select[name=excelSample]").val();
		if (gagajf.isNull(gb)){
			mcxDialog.alertC("다운로드 할 양식을 선택해주세요", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsSizeStockForm select[name=excelSample]').focus();
				}
			});
			return false;
		}
		if ("EXCELDOWN" == gb){
			fnGoodsExcelDownLoad('');
		}else{
			cfnDownloadSampleFile($("#goodsSizeStockForm select[name=excelSample]").val());	
		}
	});
	
	//엑셀다운로드
	var fnGoodsExcelDownLoad = function(flag){
		var formId = '#goodsSizeStockForm';
		
		if(!fnConditionCheck()) return;
		
		if (gridOptions.api.getDisplayedRowCount() <= 0){
			mcxDialog.alert("조회된 데이터가 없습니다.<br/>다시 조회 후 다운로드 받으세요.");
			return;
		}
		
		var params =  $(formId).serialize();
		$('#GoodsSizeStockExcelList').attr({ href : '/stock/sizeStock/excel/list?' + params }).get(0).click();
	}
	
	//엑셀 상품 조회
	$('#btnGoodsExcelSearch').on('click', function() {
		cfnExcelUploadPopup('goodsSizeStockExcelUpload', 'goodsSizeStockExcelSearch');
	});
	
	var goodsSizeStockExcelSearch = function(result){
		var data = {procJob : result.procJob
					,excelFileNm : result.excelFileNm
					};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnGoodsSizeStockExcelSearchCallBack);
	}
	
	var fnGoodsSizeStockExcelSearchCallBack = function(result){
		fnGoodsListSearch("EXCEL");
	}
	
	//엑셀 상품 사이즈별 품절 저장
	$('#btnGoodsExcelSave').on('click', function() {
		cfnExcelUploadPopup('goodsSizeStockExcelUpload', 'goodsSizeStockExcelSave');
	});
	
	var goodsSizeStockExcelSave = function(result){
		mcxDialog.confirm('품절/안전재고 변경을 진행하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {procJob : result.procJob
						,excelFileNm : result.excelFileNm
						};
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/stock/sizeSoldout/excelupload/save', jsonData, fnGoodsSizeStockExcelSaveCallBack);
			}
		});	
	}
	
	var fnGoodsSizeStockExcelSaveCallBack = function(result){
		fnGoodsListSearch("EXCELRESULT");
	}
	
	// 업체 브랜드 초기화
	var fnSupplyBrandInit = function(){
		$("#goodsSizeStockForm select[name=supplyCompCd]").val([[${sessionInfo.supplyCompCd}]]);
		//$("#goodsSizeStockForm select[name=supplyCompCd]").attr("disabled", true);
		//$("select[disabled]").addClass("formControl");
		var actionUrl = '/renderer/brand/AuthBrandlist';
		cfnCreateCombo(actionUrl, $('#goodsSizeStockForm select[name=brandCd]'), "[전체]");
	}
	
	$(document).ready(function() {
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
		//$('.ag-header-group-cell').each(function(item){$(this).css('text-align', 'center')});
		//$('.ag-header-group-cell-label').each(function(item){$(this).css('display', 'inline-block')});

		// 입점 사용자 브랜드 조회 처리
		if(sessRoleCd == "G001_B000") {
			fnSupplyBrandInit();
		}

	});

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

</html>