<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsSupplyPriceForm.html
 * @desc    : 입점 상품 가격 승인  관리
 *============================================================================
 * SISUN
 * 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>아래 검색조건 중 <font color="red">업체, 브랜드, 상품코드, 발생일</font> 중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="7%"/>
						<col/>
						<col width="7%"/>
						<col width="18%"/>
						<col width="7%"/>
						<col width="10%"/>
						<col width="7%"/>
						<col width="10%"/>
					</colgroup>
					<tr>
						<th>업체/브랜드<em class="required" title="필수"></em></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>브랜드<em class="required" title="필수"></em></th>
						<td>
							<input type="text" class="w100" name="searchTxt" id="searchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchBrand"><i class="fa fa-search"></i></button>
							<input type="text" class="w100" name="searchBrandCd" readonly="readonly"/>
						</td>
						<th>상품코드<em class="required" title="필수"></em></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>발생일<em class="required" title="필수"></em></th>
						<td colspan="7" 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>
				</li>
			</ul>
			<!-- //상단버튼 영역  -->
			<!-- 검색결과 영역 -->
			<div id="gridList" style="width: 100%; height: 550px;" class="ag-theme-balham"></div>
			<!-- 검색결과 영역 -->
		</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: "resGoodsPrice", width: 140, cellClass: 'text-right'
			,cellRenderer: function(params) {
				if (params.data.resGoodsPrice <= 0){
					return "-";
				}else{
					var gapPrice = Number(params.data.currPrice) - Number(params.data.resGoodsPrice);
					
					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: "sellFeeRate", width: 180, cellClass: 'text-right'
			,cellRenderer: function(params) {
				if (gagajf.isNull(params.data.sellFeeRate)){
					return "-";
				}else{
					var gapRate = Number(params.data.goodsSellFeeRate) - Number(params.data.sellFeeRate);
					
					if (gapRate >= 0){
						return '<font color="red"> '+ params.data.sellFeeRate +'</font>';
					}else{
						return '<font color="blue"> '+ params.data.sellFeeRate +'</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");
	}
	
	// 조회클릭시
	$('#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);
	}

	//검색 조건 확인
	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=goodsCd]").val())
				|| (!gagajf.isNull($("#goodsPriceHstForm input[name=stDate]").val()) && !gagajf.isNull($("#goodsPriceHstForm input[name=edDate]").val()))
				|| !gagajf.isNull($("#goodsPriceHstForm input[name=searchBrandCd]").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 != "cfrmYn")) {
					if (!(el.value == null || el.value == "")) {
						cnt++;
					}
				}
			}
			
			if(cnt > 0) searchFlag = true;
		*/	
		 }
		
		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		return true;
	}
	
	//업체변경시
	$('#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;
		}
		var checkFlag = false;
		$.each(selectedData, function(idx, item) {

			if (!gagajf.isNull(item.cfrmDt)){
				checkFlag = true;
				mcxDialog.alertC(item.goodsCd +" 상품은 승인된 상품입니다. ",{
					sureBtnText: "확인",
					sureBtnClick: function() {
						gridOptions.api.setFocusedCell(idx, "goodsCd", null);
					}
				});
				return false;
			}
		});
	
		if (checkFlag){
			return false;
		}
		
		mcxDialog.confirm('승인 하시겠습니까?',{
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(selectedData);
				gagajf.ajaxJsonSubmit('/goods/supply/price/save', jsonData, fnSaveGoodsPriceConfirmCollBack); 
			}
		});
	});	
	
	var fnSaveGoodsPriceConfirmCollBack = function(){
		fnGoodsPriceHstListSearch('N');
	}
	
	// 브랜드 조회 팝업에서 호출
	var fnSetBrandInfo = function(result) {
		$("#goodsPriceHstForm input[name=searchBrandCd]").val(result[0].brandCd);
	}
	
	// 브랜드 조회 선택시
	$('#btnSearchBrand').on('click', function() {

		if (gagajf.isNull($("#goodsPriceHstForm input[name=searchTxt]").val())){
			mcxDialog.alert('브랜드 검색어를 입력하세요.');
			return false;
		}
		
		cfnOpenBrandListPopup('fnSetBrandInfo', $("#goodsPriceHstForm input[name=searchTxt]").val());
		
	});
	
	$(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_A101") {
			$("#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]'), "[전체]");
		}
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);

	});

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

</html>