<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ShoplinkerStockForm.html
 * @desc    : 샵링커 재고전송이력 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.05.20   jmh     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->

		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->

		<form id="searchForm" name="searchForm" action="#" th:action="@{'/shoplinker/stock/result/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<input type="hidden" name="apiType" value="STOCK" />

			<!-- 검색조건 영역 -->
			<div class="panelStyle">
				<div class="panelTitle">
					<h3>
						<i class="fa fa-info-circle"></i>아래 검색조건 중 상품코드나 전송일자을 꼭 입력해 주세요.
						<br><i class="fa fa-info-circle"></i>[배치주기] 매일 10시, 15시
					</h3>
					<span class="panelControl">
						<i class="fa fa-chevron-up"></i>
					</span>
				</div>

				<div class="panelContent">
					<table class="frmStyle">
						<colgroup>
							<col style="width: 10%;"/>
							<col style="width: 25%;"/>
							<col style="width: 10%;"/>
							<col/>
							<col style="width: 8%;"/>
							<col style="width: 12%;"/>
							<col/>
						</colgroup>

						<tr>
							<th>전송일자</th>
							<td colspan="3" id="sellTerms"></td>

							<th rowspan="2">상품코드<em class="required" title="필수"></em></th>
							<td rowspan="2">
								<textarea class="textareaR2 w90p" name="condition" id="condition"></textarea>
							</td>
						</tr>
						<tr>
							<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>
								<!-- <input type="text" class="w100" name="brandCd" readonly="readonly"/> -->
								<span id="brandText"></span>
								<input type="hidden" name="brandList"/>
							</td>

							<th>IF결과</th>
							<td>
								<select name="apiResult" id="apiResult">
									<option value="">[전체]</option>
									<option value="true">전송완료</option>
									<option value="false">전송실패</option>
									<option value="error">오류</option>
								</select>
							</td>
						</tr>
					</table>

					<ul class="panelBar">
						<li class="center">
							<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
							<button type="button" class="btn btn-gray btn-lg" id="btnInit">초기화</button>
						</li>
					</ul>
				</div>
			</div>
			<!-- 검색조건 영역 -->

			<!-- 리스트 영역 -->
			<div class="panelStyle">
				<ul class="panelBar">
					<li>
						<button type="button" class="btn btn-default btn-lg" onclick="fnExcelDownLoad();">엑셀다운로드</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="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: 470px" class="ag-theme-balham"></div>

				<ul class="panelBar">
					<li class="center">
						<div class="tablePaging" id="listPagination"></div>
					</li>
				</ul>
			</div>
			<!-- //리스트 영역 -->

			<a href="javascript:void(0);" id="ExcelList" style="display: none;">엑셀다운로드</a>
		</form>

	</div>

<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=20210114"></script>
<script th:inline="javascript">
/*<![CDATA[*/

	var sessRoleCd 		= [[${sessionInfo.roleCd}]];
	var procGbValue = {"true":"전송완료", "false":"전송실패", "error":"오류"};

	let columnDefs = [
		{headerName: "No", width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "IF결과", field: "apiResult", width: 100, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(procGbValue, params.value); }
		},
		{headerName: "전송결과메세지", field: "apiMessage", width: 350, cellClass: 'text-center'},
		{headerName: "상품코드", field: "goodsCd", width: 130, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 250, cellClass: 'text-center'},
		{headerName: "옵션코드", field: "optCd", width: 130, cellClass: 'text-center'},
		{headerName: "옵션1", field: "optCd1", width: 130, cellClass: 'text-center'},
		{headerName: "옵션2", field: "optCd2", width: 130, cellClass: 'text-center'},
		{headerName: "재고", field: "quantity", width: 80, cellClass: 'text-center'},
		{headerName: "전송일시", field: "regDt", width: 150, cellClass: 'text-center'}
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	//페이징
	$('#searchForm select[name=pageSize]').on('change', function() {
		$("#searchForm input[name=pageNo]").val('1');
		fnListSearch();
	});

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

	// 브랜드 조회 팝업에서 호출
	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);
	}

	/**************** 검색 ********************************************************/
	$('#btnSearch').on('click', function() {
		$("#searchForm input[name=pageNo]").val('1');
		fnListSearch();
	});

	// 조회
	var fnListSearch = function() {

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

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

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

		var searchFlag = false;
		var cnt = 0;

		if( !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;
		}

		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)) {
				mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm input[name=stDate]').focus();
					}
				});
				return false;
			}

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

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

	}
	/**************** 검색 // *****************************************************/

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

		$('#searchForm')[0].reset();
		$("#multiBrand").empty();
		$('#searchForm input[name=brandList]').val('');
		$('#searchForm').find('#brandText').html('');
	});
	/**************** 초기화 클릭시 // *****************************************************/

	/**************** 엑셀다운로드 *****************************************************/
	var fnExcelDownLoad = function(){
		var formId = '#searchForm';
		if (gridOptions.api.getDisplayedRowCount() <= 0){
			mcxDialog.alert("조회된 데이터가 없습니다.<br/>다시 조회 후 다운로드 받으세요.");
			return;
		}

		var fromDate = parseInt($('#searchForm input[name=stDate]').val().replaceAll("-", ""));
		var toDate =parseInt($('#searchForm input[name=edDate]').val().replaceAll("-", ""));
		if( 4 < (toDate - fromDate)){
			mcxDialog.alert("전송일자를 3일 이내의 기간으로 설정 후 다운로드해주세요.");
			return;
		}

		var params =  $(formId).serialize();
		$('#ExcelList').attr({ href : '/shoplinker/stock/excel/list?' + params }).get(0).click();
	}
	/**************** 엑셀다운로드 // *****************************************************/

	$(document).ready(function() {

		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '등록일', 'X');
		$('.btnToday').trigger('click');

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

/*]]>*/
</script>

</html>
