<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ExtmallUsacRegisterForm.html
 * @desc    : 제휴몰정산가격업로드 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.8.02    jmh         최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/ocm/extmall/usac/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>
				
				<table class="frmStyle" aria-describedby="검색조건">
					<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>매출기간<i class="required" title="필수" aria-hidden="true"></i></th>
						<td colspan="3" id="terms"></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="textareaR3 w90p" name="condition" id="condition"></textarea>
						</td>
						<!-- <th>정산등록여부</th>
						<td>
							<select name="usacYn" id="usacYn">
								<option value="">[전체]</option>
								<option value="Y">Y</option>
								<option value="N">N</option>
							</select>
						</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>유통구분</th>
						<td>
							<select name="distributionGb">
								<option value="">[전체]</option>
								<option th:if="${distributionGbList}" th:each="oneData, status : ${distributionGbList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>						
					</tr>
					<tr>
						<th>공급업체</th>
						<td>
							<input type="text" class="w100" name="supplyCompSearchTxt" id="supplyCompSearchTxt" maxlength="20"/>
							<button type="button" class="btn icn" onclick="cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="supplyCompTxt"></span>
							<input type="hidden" name="supplyCompList"/>
						</td>
						<th>브랜드</th>
						<td>
							<input type="text" class="w100" name="brandSearchTxt" id="brandSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" onclick="cfnOpenBrandListPopup('fnSetBrandInfo', 'M');"><i class="fa fa-search"></i></button>
							<!-- <input type="text" class="w100" name="brandCd" readonly="readonly"/> -->
							<span id="brandTxt"></span>
							<input type="hidden" name="brandList"/>
						</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="btnUsacUpload">엑셀업로드</button>
					</li>
				</ul>
				<!-- <p class="dot">엑셀업로드시 <font color="red">엑셀다운로드</font> 받은 후 <font color="red">정산가</font> 부분만 작성 또는 수정 후 업로드해주세요.</p> -->
			</div>
			<!-- 검색조건 영역 -->
	
			<!-- 리스트 영역 -->
			<div class="panelStyle">
				<ul class="panelBar">
					<li>
						<button type="button" class="btn btn-default btn-lg" onclick="cfnDownloadSampleFile('SF024');">엑셀업로드 양식 다운로드</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="listPagination"></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[*/
	let vendorList = gagajf.convertToArray([[${vendorList}]]);
	let extmallList = gagajf.convertToArray([[${extmallList}]]);
	let supplyCompList = gagajf.convertToArray([[${supplyCompList}]]);
	let distributionGbList = gagajf.convertToArray([[${distributionGbList}]]);

	let columnDefs = [
		{ headerName: "단품이력일련번호", field: "ordDtlItemHstSq", width: 125, cellClass: 'text-center' },
		{ headerName: "주문번호", field: "ordNo", width: 100, cellClass: 'text-center' },
		{ headerName: "주문상세번호", field: "ordDtlNo", width: 100, cellClass: 'text-center' },
		{ headerName: "상품코드", field: "goodsCd", width: 120, cellClass: 'text-center' },
		{ headerName: "상품명", field: "goodsNm", width: 200 },
		{ headerName: "옵션코드", field: "optCd", 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: "itemQty", width: 100, cellClass: 'text-center' },
		{ headerName: "단품단가", 			field: "itemPrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{ headerName: "단품단가", 			field: "itemPrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{ headerName: "정산가", 			field: "usacPrice",				width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'},
			cellStyle : function(params){
				return { 'background-color': '#ff96689c'};
			} 
		},
		
		{ headerName: "제휴몰명", field: "extmallNm", width: 100, cellClass: 'text-center' },
		{ headerName: "공급업체명", field: "supplyCompNm", width: 100, cellClass: 'text-center' },
		{ headerName: "브랜드명", field: "brandEnm", width: 100, cellClass: 'text-center' },
		{ headerName: "유통구분명", field: "distributionGbNm", width: 100, cellClass: 'text-center' },
		{ headerName: "등록자", field: "regNm", width: 100, cellClass: 'text-center'},
		{ headerName: "등록일", field: "regDt", width: 100, cellClass: 'text-center'},
		{ headerName: "수정자", field: "updNm", width: 100, cellClass: 'text-center'},
		{ headerName: "수정일", field: "updDt", width: 100, cellClass: 'text-center'},
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);
	
	
	// 벤더 콤보박스 변경 시
	$('#searchForm select[name=vendorId]').on('change', function() {
		$.getJSON('/renderer/vendor/extmall/list/' + $(this).val()
				, function(result, status) {
					if (status == 'success') {
						$('#searchForm select[name=extmallId]').empty().append('<option value="">[전체]</option>');
						$.each(result, function(idx, data) {
							var optionHtml = '<option value="' + data.cd + '">[' + data.cd + '] '+ data.cdNm + '</option>\n';
							$('#searchForm select[name=extmallId]').append(optionHtml);
						});
					}
				});
	});
	
	// 업체 조회 팝업에서 호출
	var fnSetSupplyCompInfo = function(result) {
		var arrSupplyComp = [];
		var supplyCompTxt = "";
		var sIndex = 0;
		$('#supplyCompTxt').html('');
		$('#searchForm input[name=supplyCompSearchTxt]').val('');
		
		result.forEach(function(supplyComp) {
			sIndex++; 
			arrSupplyComp.push(supplyComp.supplyCompCd);
		});

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=supplyCompSearchTxt]').val(arrSupplyComp[0]);
		} else {
			supplyCompTxt = sIndex + " 개";
			$('#supplyCompTxt').html(supplyCompTxt);
		}
		
		var jsonData = JSON.stringify(arrSupplyComp);
		$("#searchForm input[name=supplyCompList]").val(jsonData);
	}
	
	// 브랜드 조회 팝업에서 호출
	var fnSetBrandInfo = function(result) {
		var arrbrandCd = [];
		var brandTxt = "";
		var bIndex = 0;
		$('#brandTxt').html('');
		$('#searchForm input[name=brandSearchTxt]').val('');
		
		result.forEach(function(brand){
			bIndex++; 
			arrbrandCd.push(brand.brandCd);
		});

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (bIndex == 1) {
			$('#searchForm input[name=brandSearchTxt]').val(arrbrandCd[0]);
		} else {
			brandTxt = bIndex + " 개";
			$('#searchForm').find('#brandTxt').html(brandTxt);
		}
		
		var jsonData = JSON.stringify(arrbrandCd);
		$("#searchForm input[name=brandList]").val(jsonData);
	}
	
	
	//페이징
	$('#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, 'listPagination', $('#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=salesStdt]").val()) && !gagajf.isNull($("#searchForm input[name=salesEddt]").val()))
			){
			searchFlag = true;
		}else{
			
		}

		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}

		var fromDate = $('#searchForm input[name=salesStdt]').val();
		var toDate = $('#searchForm input[name=salesEddt]').val();

		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {

			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm input[name=salesStdt]').focus();
					}
				});
				return false;
			}

			if (fromDate > toDate) {
				mcxDialog.alertC("등록 시작일자는 종료일자 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm input[name=salesStdt]').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.list);
		gagaPaging.createPagination(result.pageing.pageable);

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

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

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

		cfnExcelUploadPopup('createExtmallUsac', 'createExtmallUsac');
	});

	var createExtmallUsac = function(result){
		
		var data = {procJob : result.procJob
				,excelFileNm : result.excelFileNm
				};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/ocm/extmall/usac/excelupload/save', jsonData, fnExtmallUsacCreateCallBack);
	}
	
	var fnExtmallUsacCreateCallBack = function(result){
		$("#searchForm input[name=pageNo]").val('1');
		fnGoodsListSearch();
	}
	
	/**************** 엑셀업로드 // *****************************************************/

	/**************** 엑셀다운로드 *****************************************************/
	var fnExcelDownLoad = function(){
		var formId = '#searchForm';
		if (gridOptions.api.getDisplayedRowCount() <= 0){
			mcxDialog.alert("조회된 데이터가 없습니다.<br/>다시 조회 후 다운로드 받으세요.");
			return;
		}
		/*
		var fromDate = parseInt($('#searchForm input[name=salesStdt]').val().replaceAll("-", ""));
		var toDate =parseInt($('#searchForm input[name=salesEddt]').val().replaceAll("-", ""));
		if( 4 < (toDate - fromDate)){
			mcxDialog.alert("3일 이내의 기간으로 설정 후 다운로드해주세요.");
			return;
		}*/

		var params =  $(formId).serialize();
		$('#ExcelList').attr({ href : '/ocm/extmall/usac/excel/list?' + params }).get(0).click();
	}
	/**************** 엑셀다운로드 // *****************************************************/
	
	// 초기화 클릭시
	/* $('#btnInit').on('click', function() {
		$('#searchForm')[0].reset();
		$('#searchForm input[name=brandList]').val('');
		$('#searchForm input[name=supplyCompList]').val('');
		$('#brandTxt').html('');
		$('#supplyCompTxt').html('');
	}); */
	
	// 엑셀다운로드
	/* $('#btnExcel').on('click', function() {
		gagaAgGrid.exportToExcel('상품정산 목록', gridOptions);
	}); */
	
	$(document).ready(function() {
		cfnCreateCalendar('#terms', 'salesStdt', 'salesEddt', true, '매출');
		$('.btnToday').trigger('click');
		
		//$('#extmallVendor').hide();
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
	});
/*]]>*/
</script>

</html>
