<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : DailyOrderForm.html
 * @desc    : 일자별주문 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.08.17   gagamel     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 -->
		<div class="panelStyle">
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/statistics/daily/order/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
				<input type="hidden" name="dayGb" value="D"/>
				
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:25%;"/>
						<col style="width:10%;"/>
						<col style="width:25%;"/>
						<col style="width:10%;"/>
						<col style="width:20%;"/>
					</colgroup>
					<tr>
						<th>매출기간<i class="required" title="필수" aria-hidden="true"></i></th>
						<td colspan="3" id="terms">
						</td>
						<th>물류구분</th>
						<td>
							<label class="chkBox checked"><input type="checkbox" name="distributionGbScm" value="SCM" checked="checked"/>입점</label>
							<label class="chkBox checked"><input type="checkbox" name="distributionGbWms" value="WMS" checked="checked"/>위탁</label>
						</td>
					</tr>
					<tr>
						<th>디바이스</th>
						<td>
							<label class="chkBox checked"><input type="checkbox" name="frontGbP" value="P" checked="checked"/>PC웹</label>
							<label class="chkBox checked"><input type="checkbox" name="frontGbM" value="M" checked="checked"/>모바일웹</label>
							<label class="chkBox checked"><input type="checkbox" name="frontGbA" value="A" checked="checked"/>APP</label>
						</td>
						<th>제휴몰</th>
						<td>
							<input type="text" class="w100" name="extmallIdSearchTxt" id="extmallIdSearchTxt" maxlength="20"/>
							<button type="button" class="btn icn" onclick="cfnOpenExtmallListPopup('fnSetExtmallInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="extmallIdTxt"></span>
							<input type="hidden" name="extmallIdList"/>
						</td>
						<th>공급업체</th>
						<td>
							<input type="text" class="w100" name="supplyCompCdSearchTxt" id="supplyCompCdSearchTxt" maxlength="20"/>
							<button type="button" class="btn icn" onclick="cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="supplyCompCdTxt"></span>
							<input type="hidden" name="supplyCompCdList"/>
						</td>
					</tr>
					<tr>
						<th>제휴채널</th>
						<td>
							<input type="text" class="w100" name="afLinkCdSearchTxt" id="afLinkCdSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" onclick="cfnOpenAfLinkListPopup('fnSetAfLinkInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="afLinkCdTxt"></span>
							<input type="hidden" name="afLinkCdList"/>
						</td>
						<th>브랜드</th>
						<td>
							<input type="text" class="w100" name="brandCdSearchTxt" id="brandCdSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" onclick="cfnOpenBrandListPopup('fnSetBrandInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="brandCdTxt"></span>
							<input type="hidden" name="brandCdList"/>
						</td>
						<th>품목</th>
						<td>
							<input type="text" class="w100" name="itemkindCdSearchTxt" id="itemkindCdSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" onclick="cfnOpenItemkindListPopup('fnSetItemkindInfo', 'M');"><i class="fa fa-search"></i></button>
							<span id="itemkindTxt"></span>
							<input type="hidden" name="itemkindList"/>
						</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>
					</li>
				</ul>
			</form>
		</div>
		<!-- 검색조건 영역 -->
		
		<div class="panelStyle">
			<div id="chart" class="chartUnit"></div>
		</div>
		
		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="left">
					<button type="button" class="btn btn-default btn-lg" id="btnExcel">엑셀다운로드</button>
				</li>
				<li class="right">
					<span class="btnGroup marR10">
						<button type="button" class="btn btn-default btn-lg active" id="dayGbD" onclick="fnSetDayGb('D');">일별</button>
						<button type="button" class="btn btn-default btn-lg" id="dayGbW" onclick="fnSetDayGb('W');">주별</button>
						<button type="button" class="btn btn-default btn-lg" id="dayGbM" onclick="fnSetDayGb('M');">월별</button>
					</span>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
			
			<div id="gridList" style="width: 100%; height: 470px" class="ag-theme-balham"></div>
		</div>
		<!-- //리스트 영역 -->
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	let columnDefs = [
		{ headerName: "일자", field: "day", width: 100, cellClass: 'text-center' },
		{
			headerName: "매출액", field: "totOrdAmt", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "전년동기매출액", field: "yoyTotOrdAmt", width: 150, cellClass: 'text-right', hide: true,
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{ headerName: "YOY(%)", field: "yoyRate", width: 100, cellClass: 'text-center' },
		{
			headerName: "자사직방문", field: "selfAmt", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "채널", field: "channelAmt", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "제휴몰", field: "extmallAmt", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "취/반품액", field: "cnclAmt", width: 120, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "주문수", field: "ordCnt", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "판매수", field: "sellQty", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		},
		{
			headerName: "취/반품수", field: "cnclQty", width: 150, cellClass: 'text-right',
			cellRenderer: function (params) { return gagaAgGrid.toAddComma(params.value); }
		}
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	gridOptions.autoGroupColumnDef = {
			headerName: "일자",
			field: "grouping",
			width: 200,
			cellRendererParams: {
				suppressCount: true
			}
		};
	
	// for expand everything
	gridOptions.groupDefaultExpanded = -1;
	
	// 제휴몰 조회 팝업에서 호출
	var fnSetExtmallInfo = function(result) {
		var arrExtmallId = [];
		var extmallIdTxt = "";
		var sIndex = 0;
		$('#extmallIdTxt').html('');
		$('#searchForm input[name=extmallIdSearchTxt]').val('');
		
		result.forEach(function(extmall) {
			sIndex++; 
			arrExtmallId.push(extmall.extmallId);
		});

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=extmallIdSearchTxt]').val(arrExtmallId[0]);
		} else {
			extmallIdTxt = sIndex + " 개";
			$('#extmallIdTxt').html(extmallIdTxt);
		}
		
		var jsonData = JSON.stringify(arrExtmallId);
		$("#searchForm input[name=extmallIdList]").val(jsonData);
	}
	
	// 업체 조회 팝업에서 호출
	var fnSetSupplyCompInfo = function(result) {
		var arrSupplyCompCd = [];
		var supplyCompCdTxt = "";
		var sIndex = 0;
		$('#supplyCompCdTxt').html('');
		$('#searchForm input[name=supplyCompCdSearchTxt]').val('');
		
		result.forEach(function(supplyComp) {
			sIndex++; 
			arrSupplyCompCd.push(supplyComp.supplyCompCd);
		});

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=supplyCompCdSearchTxt]').val(arrSupplyCompCd[0]);
		} else {
			supplyCompCdTxt = sIndex + " 개";
			$('#supplyCompCdTxt').html(supplyCompCdTxt);
		}
		
		var jsonData = JSON.stringify(arrSupplyCompCd);
		$("#searchForm input[name=supplyCompCdList]").val(jsonData);
	}
	
	// 제휴채널 조회 팝업에서 호출
	var fnSetAfLinkInfo = function(result) {
		var arrAfLinkCd = [];
		var afLinkCdTxt = "";
		var sIndex = 0;
		$('#afLinkCdTxt').html('');
		$('#searchForm input[name=afLinkCdSearchTxt]').val('');
		
		result.forEach(function(afLink) {
			sIndex++; 
			arrAfLinkCd.push(afLink.afLinkCd);
		});

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

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (bIndex == 1) {
			$('#searchForm input[name=brandCdSearchTxt]').val(arrBrandCd[0]);
		} else {
			brandCdTxt = bIndex + " 개";
			$('#brandCdTxt').html(brandCdTxt);
		}
		
		var jsonData = JSON.stringify(arrBrandCd);
		$("#searchForm input[name=brandCdList]").val(jsonData);
	}
	
	// 품목 조회 팝업에서 호출
	var fnSetItemkindInfo = function(result) {
		var arrItemkindCd = [];
		var itemkindCdTxt = "";
		var bIndex = 0;
		$('#itemkindCdTxt').html('');
		$('#searchForm input[name=itemkindCdSearchTxt]').val('');
		
		result.forEach(function(itemkind){
			bIndex++; 
			arrItemkindCd.push(itemkind.itemkindCd);
		});

		// 조회 값이 하나일 경우 화면에 코드 노출. 그 외는 갯수 처리 
		if (bIndex == 1) {
			$('#searchForm input[name=itemkindCdSearchTxt]').val(arrItemkindCd[0]);
		} else {
			itemkindCdTxt = bIndex + " 개";
			$('#itemkindCdTxt').html(itemkindCdTxt);
		}
		
		var jsonData = JSON.stringify(arrItemkindCd);
		$("#searchForm input[name=itemkindCdList]").val(jsonData);
	}
	
	// 검색
	$('#btnSearch').on('click', function() {
		// 입력 값 체크
		if (!gagajf.validation($('#searchForm')))
			return false;
		
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions, '#searchForm', fnCreateTotal);
	});
	
	// 합계 생성
	let fnCreateTotal = function() {
		// Draw chart
		fnDrawChart(gagaAgGrid.getAllRowData(gridOptions));
		
		let totOrdAmt = 0;
		let yoyTotOrdAmt = 0;
		let selfAmt = 0;
		let channelAmt = 0;
		let extmallAmt = 0;
		let cnclAmt = 0;
		let ordCnt = 0;
		let sellQty = 0;
		let cnclQty = 0;
		
		gridOptions.api.forEachNode(function(rowNode, index) {
			if (!rowNode.group) {
				if (typeof rowNode.data.totOrdAmt == 'number') { totOrdAmt += rowNode.data.totOrdAmt; }
				if (typeof rowNode.data.yoyTotOrdAmt == 'number') { yoyTotOrdAmt += rowNode.data.yoyTotOrdAmt; }
				if (typeof rowNode.data.selfAmt == 'number') { selfAmt += rowNode.data.selfAmt; }
				if (typeof rowNode.data.channelAmt == 'number') { channelAmt += rowNode.data.channelAmt; }
				if (typeof rowNode.data.extmallAmt == 'number') { extmallAmt += rowNode.data.extmallAmt; }
				if (typeof rowNode.data.cnclAmt == 'number') { cnclAmt += rowNode.data.cnclAmt; }
				if (typeof rowNode.data.ordCnt == 'number') { ordCnt += rowNode.data.ordCnt; }
				if (typeof rowNode.data.sellQty == 'number') { sellQty += rowNode.data.sellQty; }
				if (typeof rowNode.data.cnclQty == 'number') { cnclQty += rowNode.data.cnclQty; }
			}
		});

		let yoyRate = yoyTotOrdAmt > 0 ? gagaAgGrid.toFixed((totOrdAmt / yoyTotOrdAmt - 1) * 100, 1) : '';
		
		let data = {
			day: 'TOTAL',
			totOrdAmt: totOrdAmt, yoyTotOrdAmt: yoyTotOrdAmt, yoyRate: yoyRate,
			selfAmt: selfAmt, channelAmt: channelAmt, extmallAmt: extmallAmt,
			cnclAmt: cnclAmt, ordCnt: ordCnt, sellQty: sellQty, cnclQty: cnclQty
		};

		gagaAgGrid.setPinnedRowData(gridOptions, data, 'top');
	}
	
	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		$('#searchForm')[0].reset();
		
		$('#extmallIdTxt').html('');
		$('#searchForm input[name=extmallIdList]').val('');
		$('#supplyCompCdTxt').html('');
		$('#searchForm input[name=supplyCompCdList]').val('');
		$('#afLinkCdTxt').html('');
		$('#searchForm input[name=afLinkCdList]').val('');
		$('#brandCdTxt').html('');
		$('#searchForm input[name=brandCdList]').val('');
		$('#itemkindCdTxt').html('');
		$('#searchForm input[name=itemkindCdList]').val('');
	});
	
	// 엑셀다운로드
	$('#btnExcel').on('click', function() {
		gagaAgGrid.exportToExcel('일자별주문 목록', gridOptions);
	});
	
	// 일자구분 변경 시
	var fnSetDayGb = function(dayGb) {
		$('#searchForm input[name=dayGb]').val(dayGb);
		$('#dayGbD').removeClass('active');
		$('#dayGbW').removeClass('active');
		$('#dayGbM').removeClass('active');
		$('#dayGb' + dayGb).addClass('active');
		$('#btnSearch').trigger('click');
	}
	
	// 그래프 그리기
	var chart1;
	var fnDrawChart = function(data) {
		let dayList = [];
		let totOrdAmtList = [];
		let ordCntList = [];
		
		$(data).each(function(idx, item) {
			if ($('#dayGbD').hasClass('active')) {
				dayList.push(item.day.toDate('YYYY-MM-DD').format('MM-DD'));
			} else {
				dayList.push(item.day);
			}
			totOrdAmtList.push((item.totOrdAmt / 1000).toFixed(0));
			ordCntList.push(item.ordCnt);
		});
		
		chart1 = c3.generate({
			bindto: "#chart",
			padding: {
				bottom: 20 //adjust chart padding bottom
			},
			data: {
				x: 'x',
				json: {
					x: dayList,
					매출액: totOrdAmtList,
					주문건수: ordCntList
				},
				types: {
					매출액: 'bar',
					주문건수: 'line'
				}/* ,
				regions: {
					'data1': [
						{
							'start': 1,
							'end': 2,
							'style': 'dashed'
						}, {
							'start': 3
						}
					]
				} */
			},
			color: {
				pattern: ['#48C9B0', '#FF7043', '#FF7043']
			},
			legend: { padding: 15 }, //범례 item 우측 간격
			axis: {
				x: {
					type: 'category',
					padding: { left: 0.5, right: 0.5 }
				}/* ,
				y: {
					tick: {
						format: function(d) { return Number(d).addComma() + 'K'; }
					}
				} */
			},
			tooltip: {
				format: {
					title: function (d) {
						return '주문 통계 Chart';
					}
				}
			}/* ,
			bar: {
				width: { ratio: 0.2 } // 막대 폭 20%로 조절
			} */
		});
	}
	
	// LNB 또는 GNB 클릭시 차트 넓이 변경
	var chartResize = function() {
		setTimeout(function () {
			// 모든 차트 ID객체에 적용
			chart1.resize();
		}, 300);
	}
	
	$(document).ready(function() {
		cfnCreateCalendar('#terms', 'startDt', 'endDt', true, '주문');
		$('.btnRecentWeek').trigger('click');
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
	});
/*]]>*/
</script>

</html>
