<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ShoplinkerInvoiceSendForm.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/invoice/send/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">

			<!-- 검색조건 영역 -->
			<div class="panelStyle">
				<div class="panelTitle">
					<h3>
						<i class="fa fa-info-circle"></i>아래 검색조건 중 주문번호나 등록일을 꼭 입력해 주세요.
						<br><i class="fa fa-info-circle"></i>[배치주기] 매일 1시간 마다실행
					</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:35%;"/>
							<col style="width:10%;"/>
							<col/>
							<col style="width:8%;"/>
							<col style="width:12%;"/>
						</colgroup>

						<tr>
							<th>배송시작일자</th>
							<td colspan="3" id="sellTerms"></td>

							<th rowspan="2">키워드</th>
							<td rowspan="2">
								<select name="search" id="search">
									<option value="ordNo">스타일24주문번호</option>
									<option value="agentOrderId">샵링커주문번호</option>
									<option value="extmallOrderId">쇼핑몰주문번호</option>
									<option value="deliveryInvoice">운송장번호</option>
								</select>
								<textarea class="textareaR2 w90p" name="condition" id="condition"></textarea>
							</td>
						</tr>
						<tr>
							<th>벤더/제휴몰</th>
							<td>
								<select name="vendorId" required="required" data-valid-name="벤더">
									<option th:if="${vendorList}" th:each="oneData, status : ${vendorList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
								</select>/
								<select name="extmallId">
									<option value="">[전체]</option>
									<option th:if="${extmallList}" th:each="oneData, status : ${extmallList}" th:value="${oneData.extmallId}" th:text="${'[' + oneData.extmallId + '] ' + oneData.extmallNm}"></option>
								</select>
							</td>

							<th>IF결과</th>
							<td>
								<select name="apiResult" id="apiResult">
									<option value="default">[전체-전송완료제외]</option>
									<option value="">[전체]</option>
									<option value="wait">전송예정</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="btnSendInvoice">송장전송</button>
							<!-- <button type="button" class="btn btn-primary btn-lg" id="btnInvoiceUpload">엑셀업로드</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="invoiceListPagination"></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 vendorList = gagajf.convertToArray([[${vendorList}]]);
	let extmallList = gagajf.convertToArray([[${extmallList}]]);

	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: 300, cellClass: 'text-center'},
		{headerName: "샵링커주문번호", field: "agentOrderId", width: 130, cellClass: 'text-center'},
		{headerName: "쇼핑몰주문번호", field: "extmallOrderId", width: 130, cellClass: 'text-center'},
		{
			headerName		: "스타일24 주문번호"
			, field			: 'ordNo'
			, width			: 120
			, cellClass		: 'text-center'
			, sortable		: true
			, cellRenderer	: function (params) {
				var roleCd = [[${sessionInfo.roleCd}]];
				if (!roleCd.startsWith("C") && "" != params.value) {
					return "<a href=\"javascript:void(0);\" onclick=\"fnOpenOrderDetailPopup('" + params.value + "');\">" + params.value + "</a>";
				} else {
					return params.value;
				}
			}
		},
		{headerName: "주문상세번호", field: "ordDtlNo", width: 120, cellClass: 'text-center'},
		{headerName: "배송업체", field: "shipCompNm", width: 150, cellClass: 'text-center'},
		{headerName: "송장번호", field: "deliveryInvoice", width: 130, cellClass: 'text-center'},
		{headerName: "배송시작일자", field: "delvStdt", width: 140, cellClass: 'text-center'},
		{headerName: "전송일시", field: "regDt", width: 140, cellClass: 'text-center'}
		/*{headerName: "xml", field: "xmlTxt", width: 100, cellClass: 'text-center', editable: true,
			cellEditor: 'agLargeTextCellEditor',
			cellRenderer: function(params) {
				params.value = '보기';
				return params.value;
			}
		},*/
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);

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


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

	// 조회
	var fnGoodsListSearch = function() {

		if(!fnConditionCheck()) return;
		gagaPaging.init('searchForm', fnSearchCallBack, 'invoiceListPagination', $('#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.invoiceList);
		gagaPaging.createPagination(result.pageing.pageable);

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

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

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

	/**************** 송장전송 ********************************************************/
	$('#btnSendInvoice').on('click', function() {

		var alertMsg = "송장전송을 진행하시겠습니까?";
		mcxDialog.confirm(alertMsg, {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {

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

					// 현재실행중인건 없음.
					if( 0 == result.runCnt){
						var actionUrl = '/shoplinker/invoice/send/register?stDate='+ $("#searchForm input[name=stDate]").val()+"&edDate="+ $("#searchForm input[name=edDate]").val();
						$.post(actionUrl, null, null, 'json');

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

				});
			}
		});
	});

	/**************** 엑셀다운로드 *****************************************************/
	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/invoice/excel/list?' + params }).get(0).click();
	}
	/**************** 엑셀다운로드 // *****************************************************/

	/**************** 엑셀업로드 방식 ********************************************************/
	/*
	$('#btnInvoiceUpload').on('click', function() {
		cfnExcelUploadPopup('shoplinkerUploadInvoice', 'shoplinkerUploadInvoice');
	});
	var shoplinkerUploadInvoice = function(result){
		var data = {procJob : result.procJob
				,excelFileNm : result.excelFileNm
				};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/shoplinker/invoice/send/excelupload/register', jsonData, fnGoodsUpdateCallBack);

	}

	var fnGoodsUpdateCallBack = function(result){
		var str = "";
		if( "TRUE" == result.RESULT_TYPE){
			str = "처리되었습니다. 결과조회로 성공여부를 확인해주세요.";
		}else{
			str = result.RESULT_MSG;
		}
		mcxDialog.alert(str);
	}*/
	/**************** 엑셀업로드 방식 // *****************************************************/


	$(document).ready(function() {

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

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

/*]]>*/
</script>

</html>
