<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ShoplinkerGoodsSendForm.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/goods/send/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<!-- 검색조건 영역 -->
			<div class="panelStyle">
				<div class="panelTitle">
					<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 상품코드나 등록일을 꼭 입력해 주세요.</h3>
					<span class="panelControl">
						<i class="fa fa-chevron-up"></i>
					</span>
				</div>

				<div class="panelContent">
					<table class="frmStyle">
						<colgroup>
							<col style="width: 8%;"/>
							<col style="width: 18%;"/>
							<col style="width: 8%;"/>
							<col style="width: 18%;"/>
							<col style="width: 8%;"/>
							<col style="width: 19%;"/>
							<col style="width: 8%;"/>
							<col style="width: 13%;"/>
						</colgroup>
						<tr>
							<th>전송일자<em class="required" title="필수"></em></th>
							<td colspan="5" 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>API구분</th>
							<td>
								<select name="apiType" id="apiType" required="required" data-valid-name="API구분">
									<option value="">[전체]</option>
									<option value="OPTION">단품</option>
									<option value="PRODUCT">상품</option>
									<option value="NOTI">품목(고시)</option>
									<option value="CERT">인증</option>
									<option value="IMAGE">이미지</option>
								</select>
							</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>
							<button type="button" class="btn btn-primary btn-lg" id="btnGoodsUpload">엑셀업로드</button>
							<!-- <button th:if="${sessionInfo.userId == 'jmh'}" type="button" class="btn btn-default btn-lg" onclick="fnTest();">테스트</button> -->
						</li>
					</ul>
					<p class="dot">엑셀업로드시 한번에 최대 500개까지 가능합니다.</p>
					<p class="dot">업로드 후 약 10분 이상 작업소요시간이 걸릴 수 있습니다.</p>
				</div>
			</div>
			<!-- 검색조건 영역 -->

			<!-- 리스트 영역 -->
			<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-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="goodsListPagination"></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 apiTypeValue = {"OPTION":"단품", "PRODUCT":"상품", "NOTI":"품목(고시)", "CERT":"인증", "IMAGE":"이미지" };
	var procGbValue = {"true":"전송완료", "false":"전송실패", "error":"오류"};

	let columnDefs1 = [
		{headerName: "No", width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "샵링커 상품코드", field: "apiProductId", width: 130, cellClass: 'text-center'},
		{
			headerName: "API구분", field: "apiType", width: 100, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(apiTypeValue, params.value); }
		},
		{headerName: "IF결과", field: "apiResult", width: 100, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(procGbValue, params.value); }
		},
		{headerName: "IF결과메세지", field: "apiMessage", width: 300, cellClass: 'text-left'},
		{headerName: "자사 상품코드", field: "goodsCd", width: 150, cellClass: 'text-center'},
		{headerName: "옵션코드", field: "optCd", width: 150, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 300, cellClass: 'text-left'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "xml", field: "xmlTxt", width: 100, cellClass: 'text-center', editable: true,
			cellEditor: 'agLargeTextCellEditor',
			cellRenderer: function(params) {
				params.value = '<button type="button"class="btn btn-success">보기</button>';
				return params.value;
			}
		},
		{headerName: "등록자", field: "regNm", width: 100, cellClass: 'text-center'},
		{
			headerName: "전송일자", field: "regDt", width: 150, cellClass: 'text-center',
			cellRenderer: function (params) { return gagaAgGrid.toDateTimeFormat(params.value); }
		}
	];

	let columnDefs2 = [
		{headerName: "No", width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "샵링커 상품코드", field: "apiProductId", width: 130, cellClass: 'text-center'},
		{
			headerName: "API구분", field: "apiType", width: 100, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(apiTypeValue, params.value); }
		},
		{headerName: "IF결과", field: "apiResult", width: 100, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(procGbValue, params.value); }
		},
		{headerName: "IF결과메세지", field: "apiMessage", width: 300, cellClass: 'text-left'},
		{headerName: "자사 상품코드", field: "goodsCd", width: 150, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 300, cellClass: 'text-left'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "등록자", field: "regNm", width: 100, cellClass: 'text-center'},
		{
			headerName: "전송일자", field: "regDt", width: 150, cellClass: 'text-center',
			cellRenderer: function (params) { return gagaAgGrid.toDateTimeFormat(params.value); }
		}
	];

	let gridOptions;
	if (sessRoleCd == "G001_0000") { // SUPER관리자
		gridOptions = gagaAgGrid.getGridOptions(columnDefs1);
	} else {
		gridOptions = gagaAgGrid.getGridOptions(columnDefs2);
	}

	// 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"){

			//cfnOpenFrontGoodsPopup(goodsCd, event.data.siteCd);
		}
	}

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

	// 브랜드 조회 선택시
	$('#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');
		fnGoodsListSearch();
	});

	// 조회
	var fnGoodsListSearch = function() {

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

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

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

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

	/**************** 엑셀업로드 ********************************************************/
	$('#btnGoodsUpload').on('click', function() {

		var jsonData = JSON.stringify({apiType : "GOODS"});
		gagajf.ajaxJsonSubmit('/shoplinker/check/api_runable', jsonData, function(result) {

			// 현재실행중인건 없음.
			if( 0 == result.runCnt){
				cfnExcelUploadPopup('shoplinkerUploadGoods', 'shoplinkerUploadGoods');

			}else{
				mcxDialog.alert(result.runStdt+"에 호출한 건이 현재 실행중입니다.");
			}
		});
	});

	var shoplinkerUploadGoods = function(result){
		var dateStr = new Date().format("YYYYMMDDHHmmss");
		var actionUrl = "/shoplinker/goods/send/excelupload/register";
		let params = {};
		params.procJob = result.procJob;
		params.excelFileNm = result.excelFileNm;
		params.sid = dateStr;

		// 수량체크 로직 추가(500개 초과시 알림창 표시위함)
		var jsonData = JSON.stringify(params);
		gagajf.ajaxJsonSubmit(actionUrl+'/chk', jsonData, function(result2) {

			// post 전송
			$.post(actionUrl, $.param(params));
	 	});
	}
	/**************** 엑셀업로드 // *****************************************************/

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

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

	/**************** 테스트용  *******************************************************/
    // 테스트- 실제 샵링커 호출
	var fnTest = function(){
		var data = {procJob : "1"
				,excelFileNm : "2"
				};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/shoplinker/apiTest2', jsonData, null);
	}
	/**************** 테스트용 // *****************************************************/


	$(document).ready(function() {

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

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

/*]]>*/
</script>

</html>
