<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsReinboundInformForm.html
 * @desc    : 재입고알림관리
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.18   eskim   최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/reinbound/inform/list'}">
		<input type="hidden" id="searchGb" name="searchGb" />
 		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중  하나를 꼭 입력해 주세요.</h3>
			</div>
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="10%"/>
						<col width="28%"/>
						<col width="10%"/>
						<col width="25%"/>
						<col width="10%"/>
						<col/>
					</colgroup>
					<tr>
						<th>업체/브랜드</th>
						<td colspan="3">
							<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>
							<select name="brandCd" id="brandCd">
								<option value="">[전체]</option>
							</select>
						</td>
						<th rowspan="3">키워드</th>
						<td rowspan="3">
							<select name="search" id="search">
								<option value="searchGoodsCd">상품코드</option>
								<option value="searchGoodsNm">상품명</option>
 							</select>
							<textarea class="textareaR3 w60p" name="condition" id="condition"></textarea>
						</td>
						
					</tr>
					<tr>
						<th>발송여부</th>
						<td colspan="3">
							<select id="alarmYn" name="alarmYn">
								<option value="">[전체]</option>
								<option value="N">미발송</option>
								<option value="Y">발송완료</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>카테고리</th>
						<td colspan="3">
							<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 colspan="5" id="sellTerms"></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="right">
					<!-- <button type="button" class="btn btn-primary btn-lg" id="reinboundInformSend">재입고알림 발송</button> -->
					검색결과 : <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 -->
	</div>

<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 uploadGoodsUrl = [[${@environment.getProperty('upload.goods.view')}]];

	var columnDefs = [
		{headerName: 'No', width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "브랜드명", field: "brandEnm", width: 130, cellClass: 'text-center'},
		{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: "goodsCd", width: 130, 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: "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: "optCd1", width: 100, cellClass: 'text-center'},
		{headerName: "사이즈", field: "optCd2" , width: 100, cellClass: 'text-center'},
		{headerName: "가용재고", field: "currStockQty" , width: 80, cellClass: 'text-center'},
		{headerName: "고객ID", field: "maskingCustId" , width: 100, cellClass: 'text-center'},
		{headerName: "고객명", field: "maskingCustNm" , width: 100, cellClass: 'text-center'},
		{headerName: "알림요청일시", field: "reqDt", width: 120, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDD").format("YYYY-MM-DD") : '';
			}
		},
		{headerName: "알림 발송일시", field: "informDt", width: 120, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD") : '';
			}
		},
		{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: 100, 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: 100, cellClass: 'text-center'},
		{headerName: "경과일수", field: "pastDays" , width: 100, cellClass: 'text-center', hide: true}
		
		
	];
	
	// 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 == "goodsNm"){
			cfnOpenGoodsDetailPopup('U',goodsCd);
		}else if (event.colDef.field == "goodsCd"){
			
		}
	}

	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		fnInit();
	});
	
	var fnInit = function(){
		$('#searchForm')[0].reset();
	}
	
	// 조회클릭시
	$('#btnSearch').on('click', function() {
		$("#searchForm input[name=pageNo]").val('1');
		fnReinboundInformListSearch();
	});

	// 조회
	var fnReinboundInformListSearch = function(gbn) {

		$("#searchForm input[name=searchGb]").val("BASIC");
		
		if(!fnConditionCheck()) return;
		
		gagaPaging.init('searchForm', fnSearchCallBack, 'goodsListPagination', $('#searchForm').find('#pageSize').val());
		gagaPaging.load($("#searchForm input[name=pageNo]").val());
	}

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

		if($("#searchForm input[name=searchGb]").val() == "EXCEL") return true;
		
		var searchFlag = false;
		var cnt = 0;

		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 != "termGb")) {
				if (!(el.value == null || el.value == "")) {
					cnt++;
				}
			}
		}
			
		if(cnt > 0) searchFlag = true;

		if(searchFlag == false){
			gagaAlert.alert("검색조건을 입력하세요.", function(){

			});
			return false;
		}
		
		var fromDate = $('#searchForm input[name=stDate]').val();
		var toDate = $('#searchForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				gagaAlert.alert("일자 조회시 시작일자와 종료일자를 입력하세요.", function() {
					$('#searchForm input[name=stDate]').focus();
				});
				return false;
			}

			if (fromDate > toDate) {
				gagaAlert.alert("시작일자는 종료일자 보다 클 수 없습니다.", function() {
					$('#searchForm input[name=stDate]').focus();
				});
				return false;
			} 
		}

		return true;
	}

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

	//페이징 
	$('#searchForm select[name=pageSize]').on('change', function() {
		$("#searchForm input[name=pageNo]").val('1');
		fnReinboundInformListSearch($("#searchForm input[name=searchGb]").val());
	});
	
	//업체변경시
	$('#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]'), "[전체]", "");
	});

	// 재입고알림 발송
	$('#reinboundInformSend').click(function(e) {
		var selectedData = gridOptions.api.getSelectedRows();

		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return false;
		}
		
		var arrRinbdInfoSq = [];
		var chkFlag = false;
		$.each(selectedData, function(idx, item) {

			if (!gagajf.isNull(item.informDt)){
				chkFlag = true;
				mcxDialog.alert(item.custId+'('+ item.custNm+ ') 의 '  + item.goodsCd +"상품은 이미 재입고알림 발송되었습니다.");
				return false;
			}

			if (item.currStockQty < 1 || item.soldoutYn == 'Y'){
				chkFlag = true;
				mcxDialog.alert(item.goodsCd +"상품( 사이즈 : " + item.optCd1 + " )은 가용재고가 없습니다.");
				return false;
			}
			
			if (item.pastDays > 15){
				chkFlag = true;
				mcxDialog.alert("요청일이 15일경과한 재입고알림은 발송할 수 없습니다.");
				return false;
			}
			
			arrRinbdInfoSq.push(item.rinbdInfoSq);
		});

		if (chkFlag){
			return;
		}

		mcxDialog.confirm('재입고알림을 발송하시겠습니까?',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {arrRinbdInfoSq : arrRinbdInfoSq
				};

				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/goods/reinbound/inform/send', jsonData, fnSendInstockCallBack);
			}
		});
	});

	// 재입고알림 발송 콜백
	var fnSendInstockCallBack = function(){
		fnReinboundInformListSearch();
	}
	
	$(document).ready(function() {
		
		var chkBeforSkipFlag = '&nbsp;&nbsp;<label class="chkBox"><input type="checkbox" name="beforSkipFlag" value="Y">경과데이터 제외</label>';
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '예약일', 'X');

		var selectCode = '<select  name="dateGbn" id="dateGbn">';
		selectCode += '<option value="reqDt" seledted>요청일</option>';
		selectCode += '<option value="alarmDt">발송일</option>';
		selectCode += '</select>';

		$("#searchForm").find('#sellTerms').prepend(selectCode);
		$("#searchForm").find('#sellTerms').append(chkBeforSkipFlag);

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

	});

/*]]>*/
</script>
 	
</html>