<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsSupplyPriceForm.html
 * @desc    : 입점 상품 가격 승인  관리
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.18   eskim       최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<form id="goodsPriceHstForm" name="goodsPriceHstForm" action="#" th:action="@{'/goods/supply/price/list'}">
		<input type="hidden" id="confirmY" name="confirmY">
 		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="9%"/>
						<col width="42%"/>
						<col width="9%"/>
						<col width="15%"/>
						<col width="9%"/>
						<col/>
					</colgroup>
					<tr>
						<th>업체/브랜드</th>
						<td>
							<select name="supplyCompCd" id="supplyCompCd">
								<option value="" >[전체]</option>
								<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<select name="brandCd" id="brandCd">
								<option value="">[전체]</option>
							</select>
						</td>
						<th>상품코드</th>
						<td>
							<input type="text" class="w150" name="goodsCd" id="goodsCd" maxlength="50"/>
						</td>
						<th>승인여부</th>
						<td>
							<select  name="cfrmYn" id="cfrmYn">
								<option value="">[전체]</option>
								<option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
					</tr>
					<tr>
						<th>발생일</th>
						<td colspan="5" id="sellTerms"></td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" id="btnInit" >초기화</button>
						<button type="button" class="btn btn-info btn-lg" id="btnSearch" >조회</button>&nbsp;&nbsp;&nbsp;&nbsp;
						<!-- <button type="button" class="btn btn-base btn-lg" id="btnConfirmSearch" th:if="${sessionInfo.roleCd == 'G001_0000' OR sessionInfo.roleCd == 'G001_A000' OR sessionInfo.roleCd == 'G001_A101' OR sessionInfo.roleCd == 'G001_A100' OR sessionInfo.roleCd == 'G001_A001'}">미승인목록 조회</button> -->
					</li>
				</ul>
			</div>
			<!-- //검색조건 영역 -->
		</div>
		<!-- 패널 영역1 -->
		<div class="panelStyle">
			<!-- 상단버튼 영역  -->
			<ul class="panelBar">
				<li class="right">
					<!-- <button type="button" class="btn btn-success btn-lg" id="btnSaveGoodsPriceConfirm" th:if="${sessionInfo.roleCd == 'G001_0000' OR sessionInfo.roleCd == 'G001_A000' OR sessionInfo.roleCd == 'G001_A101' OR sessionInfo.roleCd == 'G001_A100' OR sessionInfo.roleCd == 'G001_A001'}">승인</button> -->
					검색결과 : <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: 550px;" class="ag-theme-balham"></div>
			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="goodsListPagination"></div>
				</li>
			</ul>
			<!-- 검색결과 영역 -->
		</div>
		</form>
		<!-- //패널 영역2 -->
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	var sessRoleCd = [[${sessionInfo.roleCd}]];
	var goodsStatList = gagajf.convertToArray([[${goodsStatList}]]);
	var formalGbList = gagajf.convertToArray([[${formalGbList}]]);
	var columnDefs = [];
	
	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: "brandEnm" , width: 100, cellClass: 'text-center'},
		{headerName: "상품코드", field: "goodsCd", width: 130, cellClass: 'text-center'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "상품상태", field: "goodsStat" , width: 100, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(goodsStatList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(goodsStatList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(goodsStatList, params.newValue); }
		},
		{headerName: "온라인 현재판매가", field: "currPrice", width: 120, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();}
		},
		{headerName: "판매가조정대상금액", field: "supplyGoodsPrice", width: 140, cellClass: 'text-right'
			,cellRenderer: function(params) {
				if (params.data.supplyGoodsPrice <= 0){
					return "-";
				}else{
					var gapPrice = Number(params.data.currPrice) - Number(params.data.supplyGoodsPrice);
					
					if (gapPrice >= 0){
						return '<font color="red"> '+ params.value.addComma() +'</font>';
					}else{
						return '<font color="blue"> '+ params.value.addComma() +'</font>';
					}

				}
			}
		},
		{headerName: "온라인 판매수수료", field: "goodsSellFeeRate", width: 140, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();}
		},
		{headerName: "판매수수료 조정대상수수료", field: "supplySellFeeRate", width: 180, cellClass: 'text-right'
			,cellRenderer: function(params) {
				if (gagajf.isNull(params.data.supplySellFeeRate)){
					return "-";
				}else{
					var gapRate = Number(params.data.goodsSellFeeRate) - Number(params.data.supplySellFeeRate);
					
					if (gapRate >= 0){
						return '<font color="red"> '+ params.data.supplySellFeeRate +'</font>';
					}else{
						return '<font color="blue"> '+ params.data.supplySellFeeRate +'</font>';
					}
				}	
			}
		},
		{headerName: "승인자", field: "cfrmNm", width: 130, cellClass: 'text-center'},
		{headerName: "승인일자", field: "cfrmDt" , 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: "regDt", width: 180, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "등록자", field: "regNm" , width: 100, cellClass: 'text-center'}
		
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	// 중복 선택 가능
	gridOptions.rowSelection = 'multiple';
 	gridOptions.suppressRowClickSelection = true;
	//gridOptions.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
	
	// Row Click
	gridOptions.onCellClicked = function(event) {
		var goodsCd = event.data.goodsCd;
		if (event.colDef.field == "goodsCd"){
			cfnOpenGoodsDetailPopup('U',goodsCd);
		}
	}
	
	gridOptions.excelStyles = [
			{
				id: 'text-center',
				dataType: 'string',
				font: {size : 10, bold: false}
			},
			{
				id: 'text-left',
				dataType: 'string',
				font: {size : 10, bold: false}
			},
			{
				id: 'text-right',
				font: {size : 10, bold: false}
			}
		]
		
	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		fnInit();
	});
	
	var fnInit = function(){
		$('#goodsPriceHstForm')[0].reset();
		//$("#goodsPriceHstForm input[type=radio]").removeClass("checked");
		$("#goodsPriceHstForm input[type=checkbox]").removeClass("checked");
		//$("#goodsPriceHstForm input[type=radio]").parent("label").removeClass("checked");
		$("#goodsPriceHstForm input[type=checkbox]").parent("label").removeClass("checked");
		$("#goodsPriceHstForm input[type=radio][checked]").parent("label").addClass("checked");
		fnSupplyBrandInit();
	}
	
	// 조회클릭시
	$('#btnSearch').on('click', function() {
		fnGoodsPriceHstListSearch('N');
	});

	// 미승인목록 조회클릭시
	$('#btnConfirmSearch').on('click', function() {
		fnGoodsPriceHstListSearch('Y');
	});
	
	// 조회
	var fnGoodsPriceHstListSearch = function(confirmY) {
		
		$("#goodsPriceHstForm input[name=confirmY]").val(confirmY);
		
		if(!fnConditionCheck()) return;
		
		//var formId = "#goodsPriceHstForm";
		//gagaAgGrid.fetch($(formId).prop('action'), gridOptions, formId);
		gagaPaging.init('goodsPriceHstForm', fnSearchCallBack, 'goodsListPagination', $('#goodsPriceHstForm').find('#pageSize').val());
		gagaPaging.load($("#goodsPriceHstForm input[name=pageNo]").val());
	}

	//검색 조건 확인
	var fnConditionCheck = function(){
		var formId = '#goodsPriceHstForm';
		var form = document.goodsPriceHstForm;

		if ($("#goodsPriceHstForm input[name=confirmY]").val() == "Y") return true;
		
		var searchFlag = false;
		var cnt = 0;

		/* if( !gagajf.isNull($("#goodsPriceHstForm select[name=supplyCompCd]").val())
				|| !gagajf.isNull($("#goodsPriceHstForm input[name=condition]").val())
				|| (!gagajf.isNull($("#goodsPriceHstForm input[name=stDate]").val()) && !gagajf.isNull($("#goodsPriceHstForm input[name=edDate]").val()))
			){
			searchFlag = true;
		}else{ */
			for (i = 0; i < form.elements.length; i++ ) {
				var el = form.elements[i];
				
				if ($(el).prop("type") == "text" || ($(el).prop("type") == "select-one" && el.name != "search" && el.name != "dateGbn" && el.name != "pageSize")) {
					if (!(el.value == null || el.value == "")) {
						cnt++;
					}
				}
			}
			
			if(cnt > 0) searchFlag = true;
			
		/* } */
		
		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		return true;
	}
	
	var fnSearchCallBack = function(result){

		$('#goodsPriceHstForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
		$('#goodsPriceHstForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
		$('#goodsPriceHstForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
		$('#goodsPriceHstForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
		gridOptions.api.setRowData(result.goodsList);
		gagaPaging.createPagination(result.pageing.pageable);
		
	}

	//페이징
	$('#goodsPriceHstForm select[name=pageSize]').on('change', function() {
		$("#goodsPriceHstForm input[name=pageNo]").val('1');
		fnGoodsPriceHstListSearch('N');
	});
	
	//업체변경시
	$('#goodsPriceHstForm select[name=supplyCompCd]').on('change', function() {
		var actionUrl = '/renderer/supplyCompany/brand/list/' + $(this).val();

		if(sessRoleCd == "G001_A1001"){
			actionUrl = '/renderer/brand/AuthBrandlist';
		}
		$("#goodsPriceHstForm select[name=brandCd] option:gt(0)").remove();

		cfnCreateCombo(actionUrl, $('#goodsPriceHstForm select[name=brandCd]'), "[전체]", "");
		
	});
	
	//브랜드 변경시
	$('#goodsPriceHstForm select[name=brandCd]').on('change', function() {
		
		var supplyCompCd = $('#goodsPriceHstForm select[name=supplyCompCd]').val();
		var brandCd = $('#goodsPriceHstForm select[name=brandCd]').val();
		$("#goodsPriceHstForm select[name=sellStoreCd] option:gt(0)").remove();
		if (!gagajf.isNull(brandCd)){
			var url = "/renderer/extmall/sellstore/list/"+supplyCompCd+"/"+brandCd+"/";
			cfnCreateCombo(url, $('#goodsPriceHstForm select[name=sellStoreCd]'), "[전체]", "");	
		}
		
	});
	
	// 승인 클릭 시
	$('#btnSaveGoodsPriceConfirm').on('click', function() {
		
		if ($("#goodsPriceHstForm input[name=confirmY]").val() != "Y"){
			mcxDialog.alert("미승인목록 조회후 승인하세요.");
			return false;
		}
		
		var selectedData = gagaAgGrid.selectedRowData(gridOptions);
		
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		mcxDialog.confirm('승인 하시겠습니까?',{
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(selectedData);
				gagajf.ajaxJsonSubmit('/goods/price/hst/save', jsonData, fnSaveGoodsPriceConfirmCollBack); 
			}
		});
	});	
	
	var fnSaveGoodsPriceConfirmCollBack = function(){
		fnGoodsPriceHstListSearch('Y');
	}
	
	// 업체 브랜드 초기화
	var fnSupplyBrandInit = function(){
		$("#goodsPriceHstForm select[name=supplyCompCd]").val([[${sessionInfo.supplyCompCd}]]);
		//$("#goodsPriceHstForm select[name=supplyCompCd]").attr("disabled", true);
		//$("select[disabled]").addClass("formControl");
		var actionUrl = '/renderer/brand/AuthBrandlist';
		cfnCreateCombo(actionUrl, $('#goodsPriceHstForm select[name=brandCd]'), "[전체]");
	}
	
	$(document).ready(function() {
		
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '등록일', 'X');

		var selectCode = '<select  name="dateGbn" id="dateGbn">';
		selectCode += '<option value="R" seledted>가격변경일</option>';
		selectCode += '<option value="P">승인일자</option>';
		selectCode += '</select>';
		
		$("#goodsPriceHstForm").find('#sellTerms').prepend(selectCode);
		
		
		if(sessRoleCd == "G001_B000") {
			fnSupplyBrandInit();
		}
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
		
	});

/*]]>*/
</script>
 	</div>

</html>