<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : OrderSellerListForm.html
 * @desc    : 입점업체미발주목록조회 Page
 *============================================================================
 * SISUN
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.16   jsh77b       최초 작성
 *******************************************************************************
 -->
 
<div id="main">
	<!-- 메인타이틀 영역 -->
	<div class="main-title">
	</div>
	<!-- //메인타이틀 영역 -->
	
	<!-- 메뉴 설명 -->
	<div class="infoBox menu-desc">
	</div>
	
	<form id="searchForm" name="searchForm" action="#" th:action="@{'/order/seller/unorder/list'}">
		<input type="hidden" id="searchGb" name="searchGb" />
		<input type="hidden" id="imageViewYn" name="imageViewYn" />
		<input type="hidden" name="pageNo" id="pageNo" value ="1"/>
		
		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<!-- 검색조건 영역 -->
			<!-- TITLE -->
			<div class="panelTitle">
				<h3>
					<i class="fa fa-info-circle"></i>아래 검색조건 중 <font color="red">주문번호</font> 또는 <font color="red">검색조건</font> 하나를 꼭 입력해 주세요.
				</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:15%;"/>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
					</colgroup>
					<tr>
						<th>업체/브랜드<em class="required" title="필수"></em></th>
						<td colspan="5">
							<select name="supplyCompCd" id="supplyCompCd">
								<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<span id="multiBrand"></span>
						</td>
					</tr>
					<tr>
						<th>주문번호</th>
						<td>
							<input type="text" name="ordNo" placeholder="" maxlength="20"/>
						</td>
						<th>주문자명</th>
						<td>
							<input type="text" name="ordNm" placeholder="" maxlength="20"/>
						</td>
						<th>상품코드</th>
						<td>
							<input type="text" name="goodsCd" placeholder="" maxlength="20"/>
						</td>
						<th>주문상세상태</th>
						<td>
							<select name="ordDtlStat" id="ordDtlStat">
								<option value="G013_20" selected>결제완료</option>
								<option value="G013_30">상품준비중</option>
								<option value="G013_40">배송준비중</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>조회일자</th>
						<td colspan="7">
							<select name="searchDateGb">
								<option value="ordDt">주문일자</option>
							</select>
							<span id="terms"></span>
						</td>
					</tr>
				</table>
				
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-info btn-lg" id="btnOrderSearch">조회</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-info btn-lg" onclick="cfnDownloadSampleFile('SF020');">입점송장번호등록다운로드</button>
				</li>
				<li class="aR">
					<button type="button" id="btnExcelDown" class="btn btn-info btn-lg">엑셀다운로드</button>
					<button type="button" id="btnInvoiceExcelUpLoad" class="btn btn-success btn-lg">송장엑셀업로드</button>
					<button type="button" id="btnSave" class="btn btn-success btn-lg">저장</button>
				</li>
			</ul>
			
			<div class="panelContent" style="overflow: hidden;">
				<div id="gridList" style="width: 100%; height: 700px;" class="ag-theme-balham lh30"></div>
			</div>
		</div>
		
		<!-- //리스트 영역 -->
		<label class="off">
			<a href="javascript:void(0);" id="excelList" style="display: none;">엑셀다운로드</a>
		</label>

	</form>
</div>

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

<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=20210114"></script>

<script th:inline="javascript">
/*<![CDATA[*/
var sessRoleCd 		= [[${sessionInfo.roleCd}]];
var shipCompanyList = gagajf.convertToArray([[${shipCompanyList}]]);

var columnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
	{headerName: "입점업체",			field:"supplyCompNm",		width:100, cellClass: 'text-center'},
	{headerName: "입점업체코드",		field:"supplyCompCd",		width:100, cellClass: 'text-center', hide: true},
	{headerName: "브랜드",			field:"brandKnm",			width:100, cellClass: 'text-center'},
	{headerName: "주문번호",			field:"ordNo",				width:100, cellClass: 'text-center'},
	{headerName: "주문상세번호",		field:"ordDtlNo",			width:100, cellClass: 'text-center'},
	{headerName: "주문상세상태",		field:"ordDtlStatNm", 		width:100, cellClass: 'text-center'},
	{headerName: "주문자명",			field:"ordNm",				width:100, cellClass: 'text-center'},
	{headerName: "주문일시",			field:"ordDt",				width:100, cellClass: 'text-center',
		cellRenderer		: function (params) {
			return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
		}
	},
	{headerName: "결제수단",			field:"payMeansNm",			width:100, cellClass: 'text-center'},
	{headerName: "주문자휴대전화",		field:"ordPhnno",			width:100, cellClass: 'text-center'},
	{headerName: "수령자명",			field:"recipNm",			width:100, cellClass: 'text-center'},
	{headerName: "수령자휴대전화",		field:"recipPhnno",			width:120, cellClass: 'text-center'},
	{headerName: "수령자우편번호",		field:"recipZipcode",		width:120, cellClass: 'text-center'},
	{headerName: "수령자기본주소",		field:"recipBaseAddr",		width:120, cellClass: 'text-center'},
	{headerName: "수령자상세주소",		field:"recipDtlAddr",		width:120, cellClass: 'text-center'},
	{headerName: "업체상품코드",		field:"supplyGoodsCd",		width:100, cellClass: 'text-center'},
	{headerName: "상품코드",			field:"goodsCd",			width:100, cellClass: 'text-center'},
	{headerName: "상품명",			field:"goodsNm",			width:100, cellClass: 'text-center'},
	{headerName: "옵션1",			field:"optCd1",				width:100, cellClass: 'text-center'},
	{headerName: "옵션2",			field:"optCd2",				width:100, cellClass: 'text-center'},
	{headerName: "주문수량",			field:"ordQty",				width:100, cellClass: 'text-center'},
	{headerName: "취소수량",			field:"cnclRtnQty",			width:100, cellClass: 'text-center'},
	{headerName: "주문금액",			field:"ordAmt",				width:100, cellClass: 'text-center'},
	{headerName: "할인금액",			field:"totDcAmt",			width:100, cellClass: 'text-center'},
	{headerName: "실결제금액",		field:"realOrdAmt",			width:100, cellClass: 'text-center'},
	{headerName: "배송업체",			field:"shipCompCd",			width:150, cellClass: 'text-left'
		, editable 			: true
		, cellEditor		: 'agRichSelectCellEditor'
		, cellStyle			: {color: '#fffff', 'background-color': '#aaaaff'}
		, cellEditorParams	: {
			values: gagaAgGrid.extractValues(shipCompanyList)
		}
		, valueFormatter: function (params) {
			return gagaAgGrid.lookupValue(shipCompanyList, params.value);
		}
		, valueParser: function (params) {
			return gagaAgGrid.lookupKey(shipCompanyList, params.newValue);
		}
	},
	{headerName: "송장",				field:"invoiceNo",			width:150, cellClass: 'text-left', editable : true
		, cellStyle			: {color: '#fffff', 'background-color': '#aaaaff'}	}
];

var gridOptions = gagaAgGrid.getGridOptions(columnDefs);
gridOptions.suppressRowClickSelection = true;
gridOptions.rowSelection = 'multiple';
gridOptions.stopEditingWhenGridLosesFocus = true;

// 조회버튼
$('#btnOrderSearch').on('click', function() {
	fnSearch();
});

// 검색
var fnSearch = function() {
	var formId = '#searchForm';
	var ordNo = $('#searchForm input[name=ordNo]').val();
	var stDate = $('#stDate').val();
	var edDate = $('#edDate').val();

	if (!gagajf.isNull(stDate)) {
		if (gagajf.isNull(edDate)) {
			mcxDialog.alert('종료 기간을 입력하세요.');
			return;
		}
	}

	if (!gagajf.isNull(edDate)) {
		if (gagajf.isNull(stDate)) {
			mcxDialog.alert('종료 기간을 입력하세요.');
			return;
		}
	}

	gagaPaging.init('searchForm', fnSearchCallBack, 'orderListPagination', 100);
	gagaPaging.load($("#searchForm input[name=pageNo]").val());

	//gagaAgGrid.fetch($(formId).prop('action'), gridOptions, formId);
}

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

// 엑셀다운로드 시 주문상태 변경
$('#btnExcelDown').on('click', function () {
	
	var selectedData = gridOptions.api.getSelectedRows();

	if (selectedData.length == 0) {
		mcxDialog.alert('선택된 행이 없습니다.');
		return;
	}
	
	mcxDialog.confirm('엑셀 다운로드 하시겠습니까?', {
		cancelBtnText	: "취소",
		sureBtnText		: "확인",
		sureBtnClick	: function(){
			var jsonData = JSON.stringify(selectedData);
			gagajf.ajaxJsonSubmit('/order/seller/unorder/status/save', jsonData, fnExcelDownCollback);
		}
	});
});

// 엑셀다운로드
var fnExcelDownCollback = function(flag){
	var selectedData = gridOptions.api.getSelectedRows();

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

	let ordDtlNoArr = new Array();
	for(let i = 0 ; i < selectedData.length ; i++) {
		ordDtlNoArr.push(selectedData[i].ordDtlNo);
	}

	let order = {
		ordDtlNoArr : ordDtlNoArr
	};

	// var jsonData = JSON.stringify(order);
	/*gagajf.ajaxJsonSubmit('/order/seller/unorder/excel/list', jsonData, null);*/
	$('#excelList').attr({ href : '/order/seller/unorder/excel/list?ordDtlNoArr=' + ordDtlNoArr }).get(0).click();

	// $('#excelList').attr({ href : '/order/seller/unorder/excel/list' }).get(0).click();
}

// 송장 엑셀 업로드
$('#btnInvoiceExcelUpLoad').on('click', function() {
	cfnExcelUploadPopup('invoiceExcelUpload', 'invoiceExcelUpload');
});

var invoiceExcelUpload = function(result){
	mcxDialog.confirm('송장 변경을 진행하시겠습니까?', {
		cancelBtnText	: "취소"
		, sureBtnText	: "확인"
		, sureBtnClick	: function(){
			var data = {
				procJob 		: result.procJob
				, excelFileNm 	: result.excelFileNm
			};
			
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/order/seller/unorder/invoice/excelupload/save', jsonData, fnInvoiceSaveCollback);
		}
	});	
}

// 송장번호 저장후 
var fnInvoiceSaveCollback = function(result){
	mcxDialog.alert(result.msg);
	fnSearch();
	return;
}

//송장번호 저장시
$('#btnSave').on('click', function () {
	
	var selectedData = gridOptions.api.getSelectedRows();

	if (selectedData.length == 0) {
		mcxDialog.alert('선택된 행이 없습니다.');
		return;
	}
	
	var checkFlag = false;
	$.each(selectedData, function(idx, item) {
		if (gagajf.isNull(item.shipCompCd)){
			checkFlag = true;
			mcxDialog.alert('배송업체를 선택하세요.');
			return;
		}
		
		if (gagajf.isNull(item.invoiceNo)){
			checkFlag = true;
			mcxDialog.alert('송장번호를 입력하세요.');
			return;
		}
	});
	
	if (checkFlag){
		return false;
	}
	
	mcxDialog.confirm('저장 하시겠습니까?', {
		cancelBtnText	: "취소",
		sureBtnText		: "확인",
		sureBtnClick	: function(){
			var jsonData = JSON.stringify(selectedData);
			gagajf.ajaxJsonSubmit('/order/seller/unorder/invoice/save', jsonData, fnInvoiceSaveCollback);

		}
	});
	
});

// 초기화 클릭시
$('#btnInit').on('click', function() {
	$('#searchForm')[0].reset();
	$("#multiBrand").empty();
});

// 자사/입점 변경여부
$("#searchForm input[name=selfYn]").bind('click change', function () {
	var radioValue = $(this).val();
	var selfGb = "S";	// 자사 공급 업체
	
	if (radioValue == "N"){
		selfGb = "E";	//입점 공급업체
	}
	
	var actionUrl = '/renderer/supply/company/list/'+ selfGb;	

	$('#searchForm').find('#multiBrand').empty();

	cfnCreateCombo(actionUrl, $('#searchForm select[name=supplyCompCd]'), "[전체]", "");
});
	
// 업체변경시
$('#searchForm select[name=supplyCompCd]').on('change', function() {
	var actionUrl = '/renderer/supplyCompany/brand/list/' + $(this).val();

	if (sessRoleCd == "G001_B000") {
		actionUrl = '/renderer/brand/AuthBrandlist';
	}
	
	cfnCreateMultiCombo(actionUrl,"multiBrand",  "[전체]",null, 'Y');
});

// 업체 브랜드 초기화
var fnSupplyBrandInit = function(){
	$("#searchForm select[name=supplyCompCd]").val([[${sessionInfo.supplyCompCd}]]);
	$('#searchForm').find('#multiBrand').empty();
	
	var actionUrl = '/renderer/brand/AuthBrandlist';
	
	cfnCreateMultiCombo(actionUrl,"multiBrand",  "[전체]",null, 'Y');
}

//초기설정
$(document).ready(function() {
	// 달력기능 활성화
	cfnCreateCalendar('#terms', 'stDate', 'edDate', true, '주문');
	gagaAgGrid.createGrid('gridList', gridOptions);
	gridOptions.api.hideOverlay();
	
	if(sessRoleCd == "G001_B000") {
		fnSupplyBrandInit();
	}
});

</script>

</html>





