<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ShoplinkerOrderForm.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="orderCollectionForm" name="orderCollectionForm" action="#" th:action="@{'/shoplinker/check/api_runable'}" th:method="post">

			<div class="panelStyle">
				<div class="panelTitle">
					<h3>
						<i class="fa fa-info-circle"></i>[배치주기]
					</h3>
					<!-- 아이콘 툴팁 -->
					<div class="iconTooltip">
						<i class="fa fa-info" aria-hidden="true"></i>
						<span class="left aL" style="width:550px;">
							<em>* 배치주기 *</em><br/>
							- 공휴일,토,일 : 수집안함 (샵링커 수집주문건 없음)<br/>
							- 월요일 5시 : 저번주 금요일 15:00 ~ 금일 05:00 &nbsp;(저번 주 금요일이 공휴일일 경우 그 전날)<br/>
							- 화~금 5시 : 어제 15:00 ~ 금일 05:00 &nbsp;(어제가 공휴일일 경우 그 전날) <br/>
							- 월~금 6시~15 한시간 단위 :<br/>
							&nbsp;&nbsp;&nbsp;&nbsp;ex) 6시 : 05:00 ~ 06:00<br/>
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;7시 : 06:00 ~ 07:00<br/>
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br/>
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;15시 : 14:00 ~ 15:00<br/>
						</span>
					</div>
					<!-- //아이콘 툴팁 -->

					<span class="panelControl">
						<i class="fa fa-chevron-up"></i>
					</span>
				</div>

				<div class="panelContent">
					<table class="frmStyle">
						<colgroup>
							<col style="width:10%;"/>
							<col/>
						</colgroup>
						<tr>
							<th>샵링커 주문수집일<em class="required" title="필수"></em></th>
							<td colspan="7">
								<input name="apiStDate" id="apiStDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="주문수집일" />
								&nbsp;&nbsp;&nbsp;&nbsp;
								<button type="button" class="btn btn-primary btn-lg" id="btnCollection">주문수집</button>
								&nbsp;<span class="runable_info"></span>
							</td>
						</tr>
					</table>
					<p class="dot">실패사유가 <font color="red">가용재고없음</font>일 경우 고객에게 알림이 발송된 건으로 엑셀업로드를 하지 말아주세요.</p>
					<p class="dot">샵링커 주문수집 => 제휴몰 주문등록 => (제휴몰 주문등록 성공목록만) STYLE24에 주문등록이 됩니다.</p>
					<p class="dot">샵링커 주문수집 시 동일한 목록은 '제휴몰 주문등록'이 되지 않습니다. </p>
					<p class="dot">[제휴몰 주문등록 상태]가 <font color="red">미매핑</font>건은 옵션정보가 없는것으로 <font color="red">제휴몰주문업로드</font> 해주세요.(딜상품)</p>
				</div>
			</div>
		</form>

		<form id="searchForm" name="searchForm" action="#" th:action="@{'/shoplinker/order/collection/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<!-- 검색조건 영역 -->
			<div class="panelStyle">

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

					<tr>
						<th>주문수집일자<em class="required" title="필수"></em></th>
						<td colspan="3">
							<span id="terms">
							</span>
						</td>

						<th rowspan="3">키워드</th>
						<td rowspan="3">
							<select name="search" id="search">
								<option value="ordNo">스타일24주문번호</option>
								<option value="shoplinkerOrderId">샵링커주문번호</option>
								<option value="mallOrderId">쇼핑몰주문번호</option>
							</select><br>
							<textarea class="textareaR2 w90p" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>벤더/제휴몰</th>
						<td colspan="4">
							<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>
					</tr>
					<tr>
						<th>제휴몰 주문등록 상태</th>
						<td>
							<select name="uploadStat">
								<option value="">[전체]</option>
								<option th:if="${uploadStatList}" th:each="oneData, status : ${uploadStatList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>실패사유</th>
						<td colspan="2">
							<select name="uploadFailCd">
								<option value="">[전체]</option>
								<option th:if="${uploadFailList}" th:each="oneData, status : ${uploadFailList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></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-default btn-lg" onclick="fnTest();">테스트</button> -->
					</li>
				</ul>
			</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="shoplinkerOrderListPagination"></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 statusValue = {"Y":"판매중", "N":"판매중지"};
	var apiGbValue = {"10":"상품등록", "11":"상품수정"};
	var procGbValue = {"1":"전송완료", "0":"전송실패"};

	let vendorList = gagajf.convertToArray([[${vendorList}]]);
	let extmallList = gagajf.convertToArray([[${extmallList}]]);
	let uploadStatList = gagajf.convertToArray([[${uploadStatList}]]);
	let uploadFailList = gagajf.convertToArray([[${uploadFailList}]]);

	let columnDefs = [
		{headerName: "No", width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "제휴몰주문등록 상태", field: "uploadStat" , width: 130, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(uploadStatList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(uploadStatList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(uploadStatList, params.newValue); }
		},
		{headerName: "실패사유", field: "uploadFailCd" , width: 150, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(uploadFailList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(uploadFailList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(uploadFailList, params.newValue); }
		},
		{headerName: "업로드실패사유", field: "uploadFailReason", width: 200, cellClass: 'text-center'},
		{
			headerName		: "스타일24 주문번호"
			, field			: 'ordNo'
			, width			: 130
			, 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			: 'shoplinkerOrderId'
			, width			: 130
			, cellClass		: 'text-center'
			, sortable		: true
			, cellRenderer	: function (params) {
				var roleCd = [[${sessionInfo.roleCd}]];
				if (!roleCd.startsWith("C")) {
					return "<a href=\"javascript:void(0);\" onclick=\"fnReOpenSlkOrderDetailPopup('" + params.value + "');\">" + params.value + "</a>";
				} else {
					return params.value;
				}
			}
		},
		{headerName: "쇼핑몰 주문번호", field: "extmallOrderId", width: 130, cellClass: 'text-center'},
		{headerName: "쇼핑몰 명", field: "mallName", width: 130, cellClass: 'text-center'},
		{headerName: "배송상태[발주확인]", field: "baesongStatus", width: 130, cellClass: 'text-center'},
		{headerName: "주문 상품번호", field: "orderProductId", width: 130, cellClass: 'text-center'},
		{headerName: "샵링커 상품번호", field: "shoplinkerProductId", width: 130, cellClass: 'text-center'},
		{headerName: "자사 상품코드", field: "partnerProductId", width: 130, cellClass: 'text-center'},
		{headerName: "상품명", field: "productName", width: 130, cellClass: 'text-center'},
		{headerName: "주문수량", field: "quantity", width: 130, cellClass: 'text-center'},
		{headerName: "주문금액", 			field: "orderPrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "판매단가", 			field: "salePrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "공급가", 			field: "supplyPrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "옵션명", field: "sku", width: 130, cellClass: 'text-center'},
		{headerName: "주문수집일자", field: "orderRegDate", 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: "extmallRegDt", width: 130, cellClass: 'text-center'}
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	// Cell click
	gridOptions.onCellClicked = function(event) {
		if (event.colDef.field != 'extmallId')
			return;

		$('#detailForm select[name=vendorId]').val(event.data.vendorId);
		$('#detailForm input[name=extmallId]').val(event.data.extmallId);
		$('#detailForm input[name=extmallUserId]').val(event.data.extmallUserId);
		$('#detailForm input[name=extmallNm]').val(event.data.extmallNm);
		$('#detailForm select[name=supplyCompCd]').val(event.data.supplyCompCd);
		$('#detailForm input[name=sellStoreCd]').val(event.data.sellStoreCd);
		$('#detailForm input[name=stockSellRate]').val(event.data.stockSellRate);
		$('#detailForm input[name=priceAcceptRate]').val(event.data.priceAcceptRate);

		if (event.data.dwdpYn == 'Y') {
			$('#detailForm input:radio[name=dwdpYn]').eq(0).trigger('click');
		} else {
			$('#detailForm input:radio[name=dwdpYn]').eq(1).trigger('click');
		}

		if (event.data.cnclsmsSendYn == 'Y') {
			$('#detailForm input:radio[name=cnclsmsSendYn]').eq(0).trigger('click');
		} else {
			$('#detailForm input:radio[name=cnclsmsSendYn]').eq(1).trigger('click');
		}

		if (event.data.useYn == 'Y') {
			$('#detailForm input:radio[name=useYn]').eq(0).trigger('click');
		} else {
			$('#detailForm input:radio[name=useYn]').eq(1).trigger('click');
		}
	}


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

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

	// 조회
	var fnGoodsListSearch = function() {

		if(!fnConditionCheck()) return;
		gagaPaging.init('searchForm', fnSearchCallBack, 'shoplinkerOrderListPagination', $('#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;
		}

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

	$(document).ready(function() {

		cfnCreateCalendar('#terms', 'stDate', 'edDate', true, '수집');
		$('.btnToday').trigger('click');

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

		fnGetCallRunableInfo(0);

	});


	$('#btnCollection').on('click', function() {

		if( gagajf.isNull($("#orderCollectionForm input[name=apiStDate]").val())){
			mcxDialog.alert("샵링커 주문일 입력하세요.");
			return;
		}

		var testDate = Number($("#orderCollectionForm input[name=apiStDate]").val().replaceAll("-", ""));
		if( testDate < 20210501 || 20210701 < testDate){
			mcxDialog.alert("※ 테스트 주문수집시 ※<br>실제운영 주문건을 가져오므로 5월부터 ~ 7월이전 사이 날짜로 조회해주세요.");
			return;
		}

		mcxDialog.confirm("주문수집을 진행하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {

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

					// 현재실행중인건 없음.
					if( 0 == result.runCnt){
						var actionUrl = '/shoplinker/order/collection/receiveList/' + $('#apiStDate').val();
						$.post(actionUrl, null, null, 'json');

						$("#btnCollection").html("주문수집중");
						$("#btnCollection").removeClass("btn-primary");
						$("#btnCollection").addClass("btn-dark");
						setTimeout(function(){
							fnGetCallRunableInfo(1);
						}, 20000 );
					}else{
						mcxDialog.alert(result.runStdt+"에 호출한 건이 현재 실행중입니다.<br>"+result.txt);
					}
				});
			}
		});
	});

	// 진행상태 확인
	function fnGetCallRunableInfo(num){

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

			if( null != result  ){
				if( 0 == result.runCnt){
					// 재호출 안함.
					$("#btnCollection").html("주문수집");
					$("#btnCollection").addClass("btn-primary");
					$("#btnCollection").removeClass("btn-dark");

					if( (5 < $(".runable_info").html().length) || (num == 1)){
						var resultTxt = result.txt;
						if( null != resultTxt ){
							resultTxt = resultTxt.replace("제휴몰", "제휴몰남은수 "+result.remainExtCnt.addComma());
							resultTxt = resultTxt.replace("스타일24", "스타일24남은수 "+result.remainStyleCnt.addComma() )
							$(".runable_info").html(resultTxt);
						}
					}

				}else{
					// 현재 진행중
					$("#btnCollection").html("주문수집중");
					$("#btnCollection").removeClass("btn-primary");
					$("#btnCollection").addClass("btn-dark");

					var resultTxt = result.txt;
					if( null != resultTxt ){
						resultTxt = resultTxt.replace("제휴몰", "제휴몰남은수 "+result.remainExtCnt.addComma());
						resultTxt = resultTxt.replace("스타일24", "스타일24남은수 "+result.remainStyleCnt.addComma() )
						$(".runable_info").html(resultTxt);
					}

					setTimeout(function(){
						fnGetCallRunableInfo(0);
					}, 20000 );
				}
			}
		});
	}

	var fnOpenOrderDetailPopup = function (ordNo) {
		currOrdNo = ordNo;
		cfnOpenOrderDetailPopup(ordNo);
	};

	var fnReOpenOrderDetailPopup = function () {
		cfnOpenOrderDetailPopup(currOrdNo);
	};

	var fnReOpenSlkOrderDetailPopup = function (shoplinkerOrderId) {
		cfnOpenSlkOrderPopup(shoplinkerOrderId);
	};

	var fnReOpenExtmallOrderDetailPopup = function (ordNo) {
		cfnOpenExtmallOrderPopup(ordNo);
	};

/*]]>*/
</script>

</html>
