<!DOCTYPE html>
<html lang="ko"
	  xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : DeliveryListForm.html
 * @desc    : 배송목록 Page
 *============================================================================
 * ISTYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.10   moon        최초 작성
 *******************************************************************************
 -->
<div id="main">
	<!-- 메인타이틀 영역 -->
	<div class="main-title">
	</div>
	<!-- //메인타이틀 영역 -->
	
	<!-- 메뉴 설명 -->
	<div class="infoBox menu-desc">
	</div>
	<!-- //메뉴 설명 -->
	<!-- 검색조건 영역 -->

	<div class="panelStyle">
		<!-- TITLE -->
		<div class="panelTitle">
			<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 <font color="red">기간, 키워드</font>중 하나를 꼭 입력해 주세요.</h3>
			<span class="panelControl">
				<i class="fa fa-chevron-up"></i>
			</span>
		</div>
		<!-- //TITLE -->
		<div class="panelContent">	
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/delivery/list/'}" onsubmit="fnSearchList(); return false;">
				<table class="frmStyle">
					<colgroup>
						<col style="width:8%;"/>
						<col style="width:12%;"/>
						<col style="width:8%;"/>
						<col style="width:12%;"/>
						<col style="width:8%;"/>
						<col style="width:12%;"/>
						<col style="width:8%;"/>
						<col style="width:12%;"/>
						<col style="width:8%;"/>
						<col style="width:12%;"/>
					</colgroup>
					<tr>
						<th>사이트</th>
						<td>
							<select name="siteCd" id="siteCd">
								<option value="">[전체]</option>
								<option th:if="${siteCdList}" th:each="oneData, status : ${siteCdList}" th:value="${oneData.cd}" th:text="${oneData.cdNm}"></option>
							</select>
						</td>
						<th>몰구분</th>
						<td colspan="3">
							<select name="mallGb" style="width: 100px;">
								<option value="" th:if="${sessionInfo.roleCd} != 'B000' and ${sessionInfo.roleCd} != 'C000'">[전체]</option>
								<option th:if="${mallGbList}" th:each="oneData, status : ${mallGbList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<span id="selfmall">
								<select name="supplyCompCd">
									<option value="" th:if="${sessionInfo.roleCd} != 'B000' and ${sessionInfo.roleCd} != 'C000'">[전체]</option>
									<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
								</select>
							</span>
							<span id="extmallVendor">
								<select name="vendorId">
									<option value="" th:if="${sessionInfo.roleCd} != 'B000' and ${sessionInfo.roleCd} != 'C000'">[전체]</option>
									<option th:if="${vendorList}" th:each="oneData, status : ${vendorList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
								</select>
								<select name="extmallId" style="width: 150px;">
									<option value="">[전체]</option>
								</select>
							</span>
						</td>
						<th>프론트구분</th>
						<td colspan="3">
							<select class="w130" name="frontGb" id="frontGb">
								<option value="">[전체]</option>
								<option value="P">PC</option>
								<option value="M">Mobile</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>주문자명</th>
						<td>
							<input type="text" class="" name="orderNm" placeholder="" maxlength="20"/>
						</td>
						<th>주문자휴대폰번호</th>
						<td>
							<input type="text" class="" name="orderPhnno" placeholder="" maxlength="20"/>
						</td>
						<th>주문상세번호</th>
						<td>
							<input type="text" class="" name="ordDtlNo" placeholder="" maxlength="20"/>
						</td>
						<th rowspan="4">키워드<i class="star"></i></th>
						<td rowspan="4" colspan="5">
							<select class="w130" name="search" id="search">
								<option value="searchOrdNo">주문번호</option>
								<option value="searchExtmallOrderId">외부몰주문번호</option>
							</select>
							<textarea class="textareaR3 w70p" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>수령인</th>
						<td>
							<input type="text" class="" name="recipNm" placeholder="" maxlength="20"/>
						</td>
						<th>송장번호</th>
						<td>
							<input type="text" class="" name="invoiceNo" placeholder="" maxlength="20"/>
						</td>
						<th>상품코드</th>
						<td>
							<input type="text" class="" name="goodsCd" placeholder="" maxlength="20"/>
						</td>
					</tr>
					<tr>
						<th>출고처유형</th>
						<td>
							<select class="w150" name="delvLocClsf" id="delvLocClsf">
								<option value="">[전체]</option>
								<option th:if="${delvTypeList}" th:each="oneData, status : ${delvTypeList}" th:value="${oneData.cd}" th:text="|[${oneData.cd}] ${oneData.cdNm}|"></option>
							</select>
						</td>
						<th>출고처</th>
						<td>
							<select name="delvLocCd" id="delvLocCd">
								<option value="">[전체]</option>
								<option th:if="${deliveryLocList}" th:each="oneData, status : ${deliveryLocList}" th:value="${oneData.cd}" th:text="${oneData.cdNm}"></option>
							</select>
						</td>
						<th>주문상세상태</th>
						<td>
							<div class="multiCheckBox" style="width:270px">
								<button type="button" class="sltBtn" style="overflow-x: hidden; padding-right:5px;">[전체]</button>
								<ul style="display: none; box-shadow: 3px 3px 3px; overflow-y: scroll; height: 112px;">
									<li th:if="${ordDtlStatList}" th:each="oneData, status : ${ordDtlStatList}">
										<label class="chkBox">
											<input type="checkbox" name="multiOrdDtlStat" th:value="${oneData.cd}" th:text="|[${oneData.cd}] ${oneData.cdNm}|">
										</label>
									</li>
								</ul>
							</div>
						</td>
					</tr>
					<tr>
						<th>배송지연일</th>
						<td>
							<input type="text" class="" name="delvDelayDays" data-valid-type="integer" placeholder="" maxlength="3" style="width:20%;"/>일
							이상(결제일 기준)
						</td>
						<th>결품여부</th>
						<td>
							<select name="soldoutYn" id="soldoutYn">
								<option value="">[전체]</option>
								<option value="Y">Yes</option>
								<option value="N" selected>No</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>기간</th>
						<td colspan="8">
							<select name="termGb" id="termGb">
								<option value="ordDt">주문등록일</option>
								<option value="delvDt">배송일자</option>
								<option value="delvStDt">배송시작일자</option>
							</select>
							<span id="terms"></span>
						</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" onclick="$('#searchForm')[0].reset(); fnInitCalendar();">초기화</button>
					<button type="button" id="btnExcel" class="btn btn-info btn-lg">엑셀다운로드</button>
					</li>
				</ul>
			</form>
		</div>
	</div>
	<!-- //검색조건 영역 -->

	<!-- 리스트 영역 -->
	<div class="panelStyle">
		<ul class="panelBar">
			<li class="left">
				<button type="button" id="btnSoldout" class="btn btn-danger btn-lg">품절처리</button>
				<!-- <button type="button" id="btnSave" class="btn btn-success btn-lg btnRight" onclick="deliveryInfoSave();">저장</button>
				<button type="button" id="btnWith" class="btn btn-success btn-lg btnRight">T</button> -->
			</li>
		</ul>
		<div class="panelContent" style="overflow: hidden;">
			<div id="gridDeliveryList" style="width:100%; height: 700px;" class="ag-theme-balham"></div>
		</div>
	</div>
	<!-- //리스트 영역 -->
</div>

<script th:inline="javascript">
	/*<![CDATA[*/

	var shipCompanyList =  gagajf.convertToArray([[${shipCompanyList}]]);

	var columnDefs = [
		{
			headerName: "결품",
			field: "soldout",
			width: 50,
			cellClass: 'text-center',
			headerCheckboxSelection: true,
			headerCheckboxSelectionFilteredOnly: true
			,
			checkboxSelection: function (params) {
				return (params.data.ordDtlStat == '20' || params.data.ordDtlStat == '25' || params.data.ordDtlStat == '30' || params.data.ordDtlStat == '34') ? true : false;
			}
		},
		{headerName: "지연일", field: "delvDelayDays", width: 85, cellClass: 'text-center'},
		{
			headerName: "주문번호", field: "ordNo", width: 95, cellClass: 'text-center',
			cellRenderer: function (params) {
				var roleCd = [[${sessionInfo.roleCd}]];
				if (!roleCd.startsWith("C")) {
					return "<a href=\"javascript:void(0);\" onclick=\"cfnOpenOrderDetailPopup('" + params.value + "');\">" + params.value + "</a>";
				} else {
					return params.value;
				}
			}
		},
		{headerName: "주문상세번호", field: "ordDtlNo", width: 85, cellClass: 'text-center'},
		{headerName: "사이트", field: "siteNm", width: 120, cellClass: 'text-center'},
		{headerName: "판매몰", field: "sellStoreNm", width: 150, cellClass: 'text-left'},
		{headerName: "판매몰명", field: "extmallNm", width: 150, cellClass: 'text-left'},
		{
			headerName: "주문일시", field: "ordDt", width: 150, cellClass: 'text-center',
			cellRenderer: function (params) {
				return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
			}
		},
		{
			headerName: "결제일시", field: "ordDt", width: 150, cellClass: 'text-center',
			cellRenderer: function (params) {
				return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
			}
		},
		{headerName: "몰구분", field: "mallGbNm", width: 70, cellClass: 'text-center'},
		{
			headerName: "주문자", field: "orderNm", width: 100, cellClass: 'text-center',
			cellRenderer: function (params) {
				var roleCd = [[${sessionInfo.roleCd}]];
				if (!roleCd.startsWith("C") && !gagajf.isNull(params.value) && params.data.mallGb === '10') {
					return '<a href="javascript:void(0);" onclick=\"cfnOpenCustDetailPopup(' + params.data.custNo + ');\">' + params.data.orderNm + '</a>';
				} else {
					return params.data.orderNm;
				}
			}
		},
		{headerName: "수령인", field: "recipNm", width: 100, cellClass: 'text-center'},
		{headerName: "공급업체", field: "supplyCompNm", width: 150, cellClass: 'text-center'},
		{
			headerName: "상품코드", field: "goodsCd", width: 120, cellClass: 'text-center',
			cellRenderer: function (params) {
				var roleCd = [[${sessionInfo.roleCd}]];
				if (!roleCd.startsWith("C")) {
					return "<a href=\"javascript:void(0);\" onclick=\"cfnOpenGoodsDetailPopup('U','" + params.value + "');\">" + params.value + "</a>";
				} else {
					return params.value;
				}
			}
		},
		{headerName: "상품명", field: "goodsNm", width: 280, cellClass: 'text-left'},
		{headerName: "색상", field: "colorKnm", width: 120, cellClass: 'text-center'},
		{headerName: "사이즈", field: "sizeCd", width: 70, cellClass: 'text-center'},
		{headerName: "주문수량", field: "ordQty", width: 80, cellClass: 'text-center'},
		{headerName: "취소수량", field: "cnclRtnQty", width: 80, cellClass: 'text-center'},
		{headerName: "판매수량", field: "saleQty", width: 80, cellClass: 'text-center'},
		{
			headerName: "판매금액", field: "saleAmt", width: 100, cellClass: 'text-center'
			, valueFormatter: function (params) {
				return params.value.addComma();
			}
		},
		{
			headerName: "실결제금액", field: "realOrdAmt", width: 100, cellClass: 'text-center'
			, valueFormatter: function (params) {
				return params.value.addComma();
			}
		},
		{headerName: "주문상세상태", field: "ordDtlStatNm", width: 100, cellClass: 'text-center'},
		{headerName: "출고처", field: "delvLocCd", width: 100, cellClass: 'text-center'},
		{headerName: "출고처명", field: "delvLocNm", width: 100, cellClass: 'text-center'},
		{headerName: "쇼핑백", field: "sbagEncloseYn", width: 80, cellClass: 'text-center'},
		{
			headerName: "출고택배사", field: "shipCompCd", width: 170, cellClass: 'text-center'
			, valueGetter: function (params) { return gagaAgGrid.lookupValue(shipCompanyList, params.data.shipCompCd); }
		},
		{headerName: "출고송장", field: "invoiceNo", width: 150, cellClass: 'text-left'},
		{headerName: "송장등록수정", field: "invoiceNo", width: 120, cellClass: 'text-center'
			, cellRenderer : function (params) {
				var buttonTag = '';
				if (Number(params.data.ordDtlStat) >= 20 && Number(params.data.ordDtlStat) <= 50 ) {
					buttonTag = '<button type="button"class="btn btn-success" onClick="fnSaveInvoiceNo('+params.data.ordDtlNo+');">송장등록수정</button>';
				}
				return buttonTag;
			}
		},
		{headerName: "배송완료처리", field: "ordDtlStat", width: 120, cellClass: 'text-center'
			, cellRenderer: function(params) {
				var buttonTag = '';
				if (params.data.ordDtlStat === '40' || params.data.ordDtlStat === '50' || params.data.ordDtlStat === '55' ) {
					buttonTag = '<button type="button"class="btn btn-success" onClick="deliveryComplete('+params.data.ordDtlStat+', '+params.data.ordNo+', '+params.data.ordDtlNo+');">배송완료</button>';
				}
				return buttonTag;
			}
		},
		{headerName: "외부몰주문번호", field: "extmallOrderId", width: 200, cellClass: 'text-left'},
		{headerName: "외부몰부주문번호", field: "agentOrderId", width: 200, cellClass: 'text-left'},
		{headerName: "원코드", field: "supplyGoodsCd", width: 120, cellClass: 'text-left'},
		{headerName: "결품여부", field: "soldoutYn", width: 80, cellClass: 'text-center'},
		{headerName: "배송메모", field: "delvMemo", width: 200, cellClass: 'text-left'},
		{headerName: "교환여부", field: "ordExchGb", width: 80, cellClass: 'text-left'}
	];

	//Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	//Grid editable
	//gridOptions.defaultColDef.editable = true;

	gridOptions.suppressRowClickSelection = true;
	gridOptions.rowSelection = 'multiple';
	gridOptions.isRowSelectable = function(rowNode) {
		return rowNode.data.ordDtlStat == '20' || rowNode.data.ordDtlStat == '25' || rowNode.data.ordDtlStat == '30' || rowNode.data.ordDtlStat == '34' || rowNode.data.ordDtlStat == '35';
	}
	gridOptions.getRowStyle = function (params) {
		if (params.data.ordExchGb === 'Y') {
			return {background: 'orange'}
		}
	}

	var fnInitCalendar = function () {
		$(".btnToday").trigger('click');
	}

	// 조회
	$('#btnSearch').on('click', function () {
		fnSearchList();
	});

	var fnSearchList = function () {
		if ($('#searchForm input[name=ordNo]').val() == '') {
			if ($('#stDate').val() == '') {
				mcxDialog.alert('시작 기간을 입력하세요.');
				return;
			}

			if ($('#edDate').val() == '') {
				mcxDialog.alert('종료 기간을 입력하세요.');
				return;
			}
		}

		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions, '#searchForm', function () {
		});
	}

	//엑셀다운로드
	$('#btnExcel').on('click', function () {
		var totalRows = gridOptions.api.getDisplayedRowCount();
		if (totalRows == 0) {
			mcxDialog.alert('조회된 내역이 없습니다.');
			return;
		}


		var date = new Date().format("YYYYMMDDHHmmss");
		var params = {

			fileName: "배송목록_" + date,
			sheetName: "DATA"
		}
		gridOptions.excelStyles = [
			{
				id: 'dateFormat',
				dataType: 'dateTime',
				numberFormat: {
					format: 'YYYY-MM-DD;@'
				}
			},
			{
				id: 'textFormat',
				dataType: 'string'
			}
		]

		gridOptions.api.exportDataAsExcel(params);
	});

	// 결품처리 버튼 클릭 시
	$('#btnSoldout').on('click', function () {
		var removedData = gagaAgGrid.removeRowData(gridOptions);

		if (removedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		mcxDialog.confirm('결품 처리하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function () {
				// delete 대신 update 처리해야 하므로 다음과 같이 useYn 값을 변환
				var updatedData = [];

				$.each(removedData, function (idx, item) {

					updatedData.push(item);
				});


				var jsonData = JSON.stringify(updatedData);
				gagajf.ajaxJsonSubmit('/delivery/list/soldout'
					, jsonData
					, function () {
						$('#btnSearch').trigger('click');
					});
			}
		});
	});

	// 배송완료처리
	var deliveryComplete = function (orgOrdDtlStat, ordNo, ordDtlNo) {
		mcxDialog.confirm('배송완료 처리를 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function () {
				var jsonData = {
					"ordNo": ordNo,
					"ordDtlNo": ordDtlNo,
					"orgOrdDtlStat": orgOrdDtlStat
				};
				var tranData = JSON.stringify(jsonData);
				gagajf.ajaxJsonSubmit('/delivery/complete/save', tranData, fnSearchList);
			}
		});

	}

	// 송장변경 팝업
	var fnSaveInvoiceNo = function (ordDtlNo) {
		var actionUrl = "/delivery/save/invoice/form?ordDtlNo=" + ordDtlNo ;
		cfnOpenModalPopup(actionUrl, 'popupSaveInvoice');
	};


	// 배송정보 저장
	var deliveryInfoSave = function () {

		var changeData = gagaAgGrid.getChangedData(gridOptions);

		if (changeData.length < 1) {
			mcxDialog.alert('변경 된 데이터가 없습니다.');
			return;
		}

		mcxDialog.confirm('저장 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function () {
				var updatedData = [];

				$.each(changeData, function (idx, item) {
					var param = new Object;
					param.shipCompCd = item.shipCompCd;
					param.invoiceNo = item.invoiceNo;
					param.ordDtlNo = item.ordDtlNo;

					updatedData.push(param);
				});

				var jsonData = JSON.stringify(updatedData);
				gagajf.ajaxJsonSubmit('/delivery/orderDetail/save', jsonData, fnSearchList);
			}
		});
	}


	// 벤더 콤보박스 변경 시
	$('#searchForm select[name=vendorId]').on('change', function () {
		var actionUrl = '/renderer/vendor/extmall/list/' + $(this).val();
		cfnCreateCombo(actionUrl, $('#searchForm select[name=extmallId]'), "[전체]");
	});


	// 몰구분 콤보박스 변경 시
	$('#searchForm select[name=mallGb]').on('change', function () {
		if ($(this).val() == '10') { // 자사몰
			$('#extmallVendor').hide();
			$('#selfmall').show();
			$('#searchForm select[name=vendorId]').val('');
			$('#searchForm select[name=extmallId]').val('');
		} else if ($(this).val() == '20') { // 외부몰
			$('#selfmall').hide();
			$('#extmallVendor').show();
			$('#searchForm select[name=supplyCompCd]').val('');
		} else {
			$('#selfmall').hide();
			$('#extmallVendor').hide();
			$('#searchForm select[name=vendorId]').val('');
			$('#searchForm select[name=supplyCompCd]').val('');
			$('#searchForm select[name=extmallId]').val('');
		}
	});

	$(document).ready(function () {
		gagaAgGrid.createGrid('gridDeliveryList', gridOptions);
		var hideList = ["btnThisWeek", "btnYesterWeek", "btnRecentMonth", "btnThisMonth", "btnYesterMonth", "btnRecent3Month"];
		cfnCreateCalendar('#terms', 'stDate', 'edDate', true, '주문', '', hideList);
		$(".btnToday").trigger('click');
		$('#extmallVendor').hide();
		$('#selfmall').hide();
		$('#searchForm select[name=mallGb]').trigger('change');
		//uifnFitGrid('auto'); // TO-BE 지워야됨  
	});

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