<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : BrandForm.html
 * @desc    : 브랜드관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.04   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="@{'/business/brand/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col/>
						<col style="width:10%;"/>
						<col style="width:8%;"/>
					</colgroup>
					<tr>
						<th>공급업체</th>
						<td>
							<select name="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>
						</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>
						<th>검색어</th>
						<td>
							<input type="text" name="searchTxt" placeholder="브랜드코드/브랜드국문명/브랜드영문명/브랜드그룹명" maxlength="20"/>
						</td>
						<th>사용여부</th>
						<td>
							<select name="useYn">
								<option value="">[전체]</option>
								<option value="Y">[Y] Yes</option>
								<option value="N">[N] No</option>
							</select>
						</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" onclick="$('#searchForm')[0].reset();">초기화</button>
					</li>
				</ul>
			</form>
		</div>
		<!-- 검색조건 영역 -->

		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btn btn-default btn-lg" id="btnExcel">엑셀다운로드</button>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
			
			<div id="gridList" style="width: 100%; height: 470px" class="ag-theme-balham"></div>
		</div>
		<!-- //리스트 영역 -->
		
		<!-- 등록/수정 -->
		<div class="panelStyle">
			<form id="detailForm" name="detailForm" action="#" th:action="@{'/business/brand/save'}">
				<input type="hidden" name="mode" value="N"/>
				<input type="hidden" name="brandSupplyListInfo" />
				<table class="frmStyle" aria-describedby="등록/수정 폼">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:40%;"/>
						<col style="width:10%;"/>
						<col/>
					</colgroup>
					<tr>
						<th>브랜드코드</th>
						<td>
							<select name="brandGb">
								<option value="S">자사브랜드</option>
								<option value="E">입점브랜드</option>
							</select>
							<input type="text" class="w100" name="brandCd" placeholder="자동생성" maxlength="5" readonly="readonly"/>
							<span class="marL10 cRed"><i class="fa fa-info-circle" aria-hidden="true"></i> 자사브랜드인 경우 먼저 WMS에 등록되어 있는지를 확인해야 합니다.</span>
						</td>
						<th>브랜드명(영문/국문)<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w200" name="brandEnm" placeholder="브랜드영문명" maxlength="50" required="required" data-valid-name="브랜드영문명"/> / 
							<input type="text" class="w200" name="brandKnm" placeholder="브랜드국문명" maxlength="50" required="required" data-valid-name="브랜드국문명"/>
						</td>
					</tr>
					<tr>
						<th>브랜드그룹<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w200" name="brandGroupNm" maxlength="50" readOnly="readOnly"/>
							<input type="hidden" name="brandGroupNo" readOnly/>
							<button type="button" class="btn btn-success btn-lg" id="btnBrandGroup">브랜드그룹</button>
						</td>
						<th>노출순서<i class="required" title="필수"></i></th>
						<td class="infoTxt">
							<input type="text" class="w100 aR" name="dispOrd" maxlength="5" required="required" data-valid-name="노출순서" data-valid-type="numeric"/>
						</td>
						<!-- <th>브랜드명노출언어<i class="required" title="필수"></i></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="dispNmLang" value="EN" checked="checked">영문</label>
							<label class="rdoBtn"><input type="radio" name="dispNmLang" value="KR">국문</label>
						</td> -->
					</tr>
					<tr>
					<!--	
						<th>공급업체<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100" name="searchTxt" id="searchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchSupplyComp"><i class="fa fa-search"></i></button>
							<input type="text" class="w100" name="supplyCompNm" readonly="readonly"/>
							<input type="hidden" class="w100" name="supplyCompCd" />
						</td>
					
						<th>판매수수료율<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100 aR" name="sellFeeRate" value="0" maxlength="3" required="required" data-valid-name="판매수수료율" data-valid-type="real"/>%
						</td>
					-->		
						<th>유통구분<i class="required" title="필수"></i></th>
						<td>
							<select name="distributionGb" required="required" data-valid-name="유통구분">
								<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>
						<th>사용여부<i class="required" title="필수"></i></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="useYn" value="Y" checked="checked">Yes</label>
							<label class="rdoBtn"><input type="radio" name="useYn" value="N">No</label>
							<span class="marL10 cRed"><i class="fa fa-info-circle" aria-hidden="true"></i> No에 체크하면 "프론트"에 노출되지 않습니다.</span>
						</td>
					</tr>
					<!--  <tr>	
						<th>출고처<i class="required" title="필수"></i></th>
						<td>
							<select name="delvLocCd">
								<option value="">[선택]</option>
							</select>
						</td>
						<th>배송비정책<i class="required" title="필수"></i></th>
						<td>
							<select name="delvFeeCd" required="required" data-valid-name="배송비정책">
								<option value="">[선택]</option>
							</select>
							<span class="marL10 cRed"><i class="fa fa-info-circle" aria-hidden="true"></i> 변경된 배송정책은 이후 등록된 상품부터 적용됩니다.</span>
						</td>
					</tr>-->	
					<tr>
						<th>포인트적립율(PC정상)<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100 aR" name="pntPrate10" maxlength="3" required="required" data-valid-name="포인트적립율(PC정상)" data-valid-type="real"/>%
						</td>
						<th>포인트적립율(모바일정상)<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100 aR" name="pntMrate10" maxlength="3" required="required" data-valid-name="포인트적립율(모바일정상)" data-valid-type="real"/>%
						</td>
					</tr>
					<tr>
						<th>포인트적립율(PC이월)<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100 aR" name="pntPrate20" maxlength="3" required="required" data-valid-name="포인트적립율(PC이월)" data-valid-type="real"/>%
						</td>
						<th>포인트적립율(모바일이월)<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w100 aR" name="pntMrate20" maxlength="3" required="required" data-valid-name="포인트적립율(모바일이월)" data-valid-type="real"/>%
						</td>
					</tr>
				<!-- <tr id="brandImgArea" class="off">
					<th>브랜드이미지</th>
					<td colspan="3">
						<div class="uFile w300">
							<input id="file" name="file" type="file" class="uFileInput w300"/>
							<label for="file" class="uFileLabel">파일선택</label>
							<input type="hidden" name="logoFileNm" id="logoFileNm"/>
							<input type="hidden" name="sysFileNm" id="sysFileNm"/>
							<input type="hidden" name="newSysFileNm" id="newSysFileNm"/>
						</div>
						<input type="hidden" name="uploadDefaultUrl" id="uploadDefaultUrl" th:value="${@environment.getProperty('upload.default.view') + '/display/'}"/>
						<div id="imgView" class="off">
							<img id="bannerPreViewUrl" src="" style="height:100px"/>
						</div>
					</td>
				</tr> -->
					<tr id="brandMdArea" class="off">
						<th>담당MD</th>
						<td colspan="3" id="tdBrandMd">
							<div>
								<input type="text" class="w100" name="mdNm" onkeypress="if( event.keyCode==13 ){$('#mdIdx').val(0); cfnOpenMdListPopup('fnSetMdInfo', $(this).val());}"/>
								<button type="button" class="btn icn" id="btnSearchBrandMd" onclick="$('#mdIdx').val(0); cfnOpenMdListPopup('fnSetMdInfo');"><i class="fa fa-search"></i></button>
								<input type="text" class="w100" name="mdNo" readonly="readonly"/>
								<span class="marL10 cBlue"><i class="fa fa-info-circle" aria-hidden="true"></i> 정상/이월 모두 관리합니다.</span>
								<button type="button" class="btn btn-base btn-lg" id="btnAddBrandMd">추가</button>
								<button type="button" class="btn btn-success btn-lg" id="btnUpdateBrandMd">담당MD 수정</button>
								<span class="marL10 cRed"><i class="fa fa-info-circle" aria-hidden="true"></i> [담당MD 수정] 버튼을 눌러야 적용됩니다.</span>
								<input type="hidden" id="mdIdx" />
							</div>
						</td>
					</tr>
					<tr id="siteArea" class="off">
						<th>전시사이트</th>
						<td colspan="3">
							<label class="chkBox" th:if="${siteList}" th:each="oneData, status : ${siteList}" >
								<input type="checkbox" name="siteCd" th:value="${oneData.cd}" th:text="${oneData.cdNm}"/>
							</label>
							<button type="button" class="btn btn-success btn-lg" id="btnSaveSiteBrand">전시사이트 수정</button>
						</td>
					</tr>
				</table>
				<div>
					<ul class="panelBar">
						<li class="left">
							<button type="button" class="btn btn-base btn-lg" id="btnSearchSupplyComp">공급업체조회</button>
						</li>
					</ul>
					<div id="gridList2" style="width: 100%; height: 200px" class="ag-theme-balham"></div>
				</div>
			</form>
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btn btn-info btn-lg" id="btnNew">신규</button>
					<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
		</div>
		<!-- 등록/수정 -->
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	let supplyCompList = gagajf.convertToArray([[${supplyCompList}]]);
	let distributionGbList = gagajf.convertToArray([[${distributionGbList}]]);
	
	let columnDefs = [
		{headerName: "브랜드구분", field: "brandGb", width: 80, cellClass: 'text-center', hide: true},
		{
			headerName: "브랜드코드", field: "brandCd", width: 100, cellClass: 'text-center',
			cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "브랜드영문명", field: "brandEnm", width: 150, cellClass: 'text-center'},
		{headerName: "브랜드국문명", field: "brandKnm", width: 150, cellClass: 'text-center'},
		{headerName: "브랜드그룹번호", field: "brandGroupNo", width: 150, cellClass: 'text-center'},
		{headerName: "브랜드그룹명", field: "brandGroupNm", width: 150, cellClass: 'text-center'},
		/*{
			headerName: "공급업체", field: "supplyCompCd", width: 150, cellClass: 'text-center',
			valueGetter: function (params) {
				return gagaAgGrid.lookupValue(supplyCompList, params.data.supplyCompCd);
			}
		},*/
		{
			headerName: "유통구분", field: "distributionGb", width: 150, cellClass: 'text-center',
			valueGetter: function (params) {
				return gagaAgGrid.lookupValue(distributionGbList, params.data.distributionGb);
			}
		},
		/*{headerName: "출고처코드", field: "delvLocCd", width: 120, cellClass: 'text-center'},
		{headerName: "출고처명", field: "delvLocNm", width: 150, cellClass: 'text-center'},*/
		{headerName: "ERP브랜드코드", field: "erpBrandCd", width: 120, cellClass: 'text-center', hide: true},
		/*{
			headerName: "무료배송비기준",
			children : [
				{headerName: "기본배송비", field: "delvFee", width: 120, cellClass: 'text-center', valueFormatter: function(params) { return Number(params.value).addComma(); }},
				{headerName: "최소주문금액", field: "minOrdAmt", width: 120, cellClass: 'text-center', valueFormatter: function(params) { return Number(params.value).addComma(); }}
			]
		},
		{headerName: "판매수수료율(%)", field: "sellFeeRate", width: 150, cellClass: 'text-center'}, */
		{
			headerName: "포인트적립율(%)",
			children : [
				{headerName: "PC정상", field: "pntPrate10", width: 100, cellClass: 'text-center'},
				{headerName: "모바일정상", field: "pntMrate10", width: 100, cellClass: 'text-center'},
				{headerName: "PC이월", field: "pntPrate20", width: 100, cellClass: 'text-center'},
				{headerName: "모바일이월", field: "pntMrate20", width: 100, cellClass: 'text-center'}
			]
		},
		/*{headerName: "브랜드이미지", field: "brandImg", width: 150, cellClass: 'text-center', hide: true},*/
		{headerName: "노출순서", field: "dispOrd", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "사용여부", field: "useYn", width: 80, cellClass: 'text-center'}
	];

	let columnDefs2 = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "공급업체코드", field: "supplyCompCd", width: 150, cellClass: 'text-center'},
		{headerName: "공급업체명", field: "supplyCompNm", width: 300}
	];
	
	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);
	let gridOptions2 = gagaAgGrid.getGridOptions(columnDefs2);
	
	gridOptions2.rowSelection = "multiple";

	// Cell click
	gridOptions.onCellClicked = function(event) {
		if (event.colDef.field != 'brandCd')
			return;
		
		$("#detailForm input[name=mode]").val("U");
		$("#detailForm select[name=brandGb]").val(event.data.brandGb);
		$("#detailForm select[name=brandGb]").attr("disabled", "disabled");
		$("#detailForm input[name=brandCd]").val(event.data.brandCd);
		$("#detailForm input[name=brandEnm]").val(event.data.brandEnm);
		$("#detailForm input[name=brandKnm]").val(event.data.brandKnm);
		//$("#detailForm input:radio[name=dispNmLang]:input[value=" + event.data.dispNmLang + "]").click();
		//$("#detailForm input[name=rgbCd]").val(event.data.rgbCd);
		$("#detailForm input[name=brandKnm]").val(event.data.brandKnm);
		$("#detailForm input[name=brandGroupNm]").val(event.data.brandGroupNm);
		$("#detailForm input[name=brandGroupNo]").val(event.data.brandGroupNo);
		$("#detailForm input[name=erpBrandCd]").val(event.data.erpBrandCd);
		$("#detailForm select[name=distributionGb]").val(event.data.distributionGb);
		//$("#detailForm input[name=supplyCompCd]").val(event.data.supplyCompCd);
		//$("#detailForm input[name=supplyCompNm]").val(event.data.supplyCompNm);
		//fnGetSupplyCompCdList(event.data.supplyCompCd, event.data.delvFeeCd);
		
		// 출고처 정보
		//$.getJSON('/renderer/delvloc/list/' + event.data.supplyCompCd
		//	, function(delvLocList) {
		//		$('#detailForm select[name=delvLocCd]').empty().append('<option value="">[선택]</option>');
		//		$.each(delvLocList, function(idx, item) {
		//			var optionHtml = '<option value="' + item.cd + '">[' + item.cd + '] '+ item.cdNm + '</option>\n';
		//			$('#detailForm select[name=delvLocCd]').append(optionHtml);
		//		});
		//		
		//		$("#detailForm select[name=delvLocCd]").val(event.data.delvLocCd);
		//	}
		//);
		
		// 배송비 정책
		//cfnCreateCombo('/renderer/delvFee/list/' + event.data.supplyCompCd, $('#detailForm select[name=delvFeeCd]'), "[선택]", event.data.delvFeeCd);
		
		//$("#detailForm input[name=delvFee]").val(Number(event.data.delvFee).addComma());
		//$("#detailForm input[name=minOrdAmt]").val(Number(event.data.minOrdAmt).addComma());
		//$("#detailForm input[name=sellFeeRate]").val(event.data.sellFeeRate);
		$("#detailForm input[name=pntPrate10]").val(event.data.pntPrate10);
		$("#detailForm input[name=pntMrate10]").val(event.data.pntMrate10);
		$("#detailForm input[name=pntPrate20]").val(event.data.pntPrate20);
		$("#detailForm input[name=pntMrate20]").val(event.data.pntMrate20);
		$("#detailForm input:radio[name=useYn]:input[value=" + event.data.useYn + "]").click();
		$("#detailForm input[name=dispOrd]").val(event.data.dispOrd);
		
		/* var brandImg = event.data.logoFileNm;
		if(!gagajf.isNull(brandImg)){
			$("#logoFileNm").val(brandImg);
			$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+brandImg);
			$("#imgView").removeClass("off").addClass("on");
		}else {
			$("#orgFileNm").val('');
		}
		$('#detailForm input[name=file]').closest('div').find('label').text('파일선택'); */
		
		// 담당MD 영역 노출
		$("#brandMdArea").removeClass("off").addClass("on");
		fnGetBrandMdList(event.data.brandCd);
		
		// 전시사이트 영역 노출
		$("#siteArea").removeClass("off").addClass("on");
		fnGetBrandSiteList(event.data.brandCd);
		
		// 로고이미지 영역 노출
		//$("#brandImgArea").removeClass("off").addClass("on");
		
		// 공급업체정보 조회
		gagaAgGrid.fetch("/business/brand/supply/list/" + $('#detailForm input[name=brandCd]').val() , gridOptions2);
		
		$("#detailForm select[name=supplyCompCd]").val(event.data.supplyCompCd);
	}

	// 조회
	$('#btnSearch').on('click', function() {
		// Fetch data
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions, '#searchForm');
	});
	
	// 구매포인트적립율 설정
	let fnSetPntRate = function(brandGb) {
		let pntInfo = [[${pntInfo}]];
		
		if (brandGb == 'S') { // 자사브랜드
			$('#detailForm input[name=pntPrate10]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal1);
			$('#detailForm input[name=pntMrate10]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal2);
			$('#detailForm input[name=pntPrate20]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal3);
			$('#detailForm input[name=pntMrate20]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal4);
		} else { // 입점브랜드
			$('#detailForm input[name=pntPrate10]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal5);
			$('#detailForm input[name=pntMrate10]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal6);
			$('#detailForm input[name=pntPrate20]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal7);
			$('#detailForm input[name=pntMrate20]').val(gagajf.isNull(pntInfo) ? 0 : pntInfo.strSetVal8);
		}
	}
	
	// 브랜드구분 변경 시
	$('#detailForm select[name=brandGb]').on('change', function() {
		// 구매포인트적립율 설정
		fnSetPntRate($(this).val());
/*		
		$.getJSON('/renderer/supply/company/list/' + $(this).val()
			, function(result, status) {
				$('#detailForm select[name=supplyCompCd]').empty().append('<option value="">[선택]</option>');
				$.each(result, function(idx, item) {
					var optionHtml = '<option value="' + item.cd + '">[' + item.cd + '] '+ item.cdNm + '</option>\n';
					$('#detailForm select[name=supplyCompCd]').append(optionHtml);
				});
				$('#detailForm select[name=supplyCompCd]').trigger('change');
			});
*/			
	});
	
	
	// 공급업체 선택시
	$('#btnSearchSupplyComp').on('click', function() {
		var selfYn = "";
		selfYn = 'Y'; //자사
		if($("#detailForm select[name=brandGb]").val() == 'E'){	//입점
			selfYn = 'N';
		}

		cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M', $("#detailForm input[name=searchTxt]").val(), '' , selfYn);
	});
	
	// 공급업체 조회 팝업에서 호출
	var fnSetSupplyCompInfo = function(result) {
		//$("#detailForm input[name=supplyCompCd]").val(result[0].supplyCompCd);
		//$("#detailForm input[name=supplyCompNm]").val(result[0].supplyCompNm);
		
		if (result.length < 1) return;
		
		// 기존상품
		var brandSupplyList = gagaAgGrid.getAllRowData(gridOptions2);
		var idx = brandSupplyList.length+1; 
		
		var isExist = false;
		result.forEach(function(supply){
			isExist = false;

			gridOptions2.api.forEachNode(function(rowNode, index) {
				if (supply.supplyCompCd == rowNode.data.supplyCompCd){
					isExist = true;
				}
			});
			
			if(!isExist){
				var data = { 
						supplyCompCd: supply.supplyCompCd
						, supplyCompNm: supply.supplyCompNm
						};
				//그리드 마지막에 추가해야함
				gridOptions2.api.updateRowData({add: [data], addIndex: idx});
				
				idx++;
			
			}
		});
		gridOptions2.api.refreshCells();
		
		/* // 출고처 정보
		$.getJSON('/renderer/delvloc/list/' + result[0].supplyCompCd
			, function(delvLocList, status) {
				$('#detailForm select[name=delvLocCd]').empty().append('<option value="">[선택]</option>');
				$.each(delvLocList, function(idx, item) {
					var optionHtml = '<option value="' + item.cd + '">[' + item.cd + '] '+ item.cdNm + '</option>\n';
					$('#detailForm select[name=delvLocCd]').append(optionHtml);
				});
			}
		);
		
		cfnCreateCombo('/renderer/delvFee/list/' + result[0].supplyCompCd, $('#detailForm select[name=delvFeeCd]'), "[선택]"); */
	}
	
	// 브랜드담당MD 목록
	var fnGetBrandMdList = function(brandCd) {
		$.getJSON('/business/brand/md/list/' + brandCd
			, function(result, status) {
				$("#tdBrandMd input[name=mdNm]").val('');
				$("#tdBrandMd input[name=mdNo]").val('');
				
				$("#tdBrandMd div").each(function(idx) {
					if (idx > 0) {
						$(this).remove();
					}
				});
				
				for (var i = 0; i < result.length; i++) {
					if (result[i].formalGb == 'G009_10') {
						if (i == 0) {
							$("#brandMdArea input[name=mdNm]").val(result[i].mdNm);
							$("#brandMdArea input[name=mdNo]").val(result[i].mdNo);
						} else {
							$("#tdBrandMd").append(getBrandMdTag(result[i].mdNo, result[i].mdNm));
						}
					}
				}
			});
	}

	// 브랜드 노출사이트 목록
	var fnGetBrandSiteList = function(brandCd) {
		$.getJSON('/business/brand/site/list/' + brandCd
			, function(result) {
				// 전시사이트 체크박스 체크 제거
				$('#detailForm input:checkbox[name=siteCd]').prop('checked', false);
				$('#detailForm input:checkbox[name=siteCd]').parent("label").removeClass("checked");
				
				// 체크박스 개수
				var chkboxCnt = $('#detailForm input:checkbox[name=siteCd]').length;
	
				// 데이터 개수
				var dataCnt = result.length;
	
				if (dataCnt > 0) {
					for (var i = 0; i < chkboxCnt; i++) {
						for (var j = 0; j < dataCnt; j++){
							var data = result[j].siteCd;
							if ($('#detailForm input:checkbox[name=siteCd]').eq(i).val() == data) {
								$('#detailForm input:checkbox[name=siteCd]').eq(i).prop('checked', true);
								$("#detailForm input:checkbox[name=siteCd]").eq(i).parent("label").addClass("checked");
							}
						}
					}
				}
		});
	}
	
	var fnSetMdInfo = function(result) {
		var ind = $('#mdIdx').val();
		$("#tdBrandMd input[name=mdNo]").eq(ind).val(result[0].mdNo);
		$("#tdBrandMd input[name=mdNm]").eq(ind).val(result[0].mdNm);
	}
	
	//브랜드그룹 등록및 선택
	$("#btnBrandGroup").on("click", function() {
		cfnOpenBrandGroupListPopup("callBackBrandGroup", "S", "C");
	});
	var callBackBrandGroup = function(result) {
		$("#detailForm input[name=brandGroupNm]").val(result[0].brandGroupNm);
		$("#detailForm input[name=brandGroupNo]").val(result[0].brandGroupNo);
	}
	
	// 브랜드담당MD 수정
	$("#btnUpdateBrandMd").on("click", function() {
		var arrData = [];
		var brandCd = $("#detailForm input[name=brandCd]").val();
		var mdCnt = 0;
		
		$("#tdBrandMd div").each(function() {
			var mdNo = $(this).find("input[name=mdNo]").val();
			if (!gagajf.isNull(mdNo)) {
				mdCnt++;
			}
			
			var data = { brandCd : brandCd, mdNo : mdNo };
			arrData.push(data);
		});
		
		if (mdCnt == 0) {
			mcxDialog.alert('담당MD가 선택되지 않았습니다.');
			return false;
		}
		
		mcxDialog.confirm('담당MD를 수정하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(arrData);
				gagajf.ajaxJsonSubmit('/business/brand/md/save', jsonData);
			}
		});
	});
	
	// 전시사이트 수정
	$("#btnSaveSiteBrand").on("click", function() {
		var arrSiteBrand = [];
		var brandCd = $("#detailForm input[name=brandCd]").val();
		var brandGrpNm = $("#detailForm input[name=brandGrpNm]").val();
		var checkCnt = 0;
		
		$("#siteArea label").each(function() {
			let ele = $(this).find("input:checkbox[name=siteCd]");
			let siteCd = $(ele).val();
			let useYn = 'N';
			
			if ($(ele).is(':checked')) {
				useYn = 'Y';
				checkCnt++;
			}
		
			var data = { brandCd : brandCd, siteCd : siteCd, useYn : useYn, brandGrpNm : brandGrpNm };
			arrSiteBrand.push(data);
		});
		
		if (checkCnt <= 0) {
			mcxDialog.alert('전시될 사이트를 선택해 주세요.');
			return false;
		}
		
		mcxDialog.confirm('전시될 사이트를 수정하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(arrSiteBrand);
				gagajf.ajaxJsonSubmit('/business/brand/site/save', jsonData);
			}
		});
	});
	
	// 담당MD 추가 클릭 시
	$("#btnAddBrandMd").on("click", function() {
		$("#tdBrandMd").append(getBrandMdTag());
	});
	
	// 담당MD 태그
	var getBrandMdTag = function(mdNo, mdNm) {
		var i = $("#detailForm input[name=mdNm]").length;
		var tag = '<div>\n';
		tag += '	<input type="text" class="w100" name="mdNm" value="' + gagajf.convNull(mdNm,'') + '" onkeypress="if (event.keyCode == 13) { $(\'#mdIdx\').val(' + i + '); cfnOpenMdListPopup(\'fnSetMdInfo\', $(this).val());}"/>\n';
		tag += '	<button type="button" class="btn icn" id="btnSearchBrandMd" onclick="$(\'#mdIdx\').val(' + i + '); cfnOpenMdListPopup(\'fnSetMdInfo\');"><i class="fa fa-search"></i></button>\n';
		tag += '	<input type="text" class="w100" name="mdNo" value="' + gagajf.convNull(mdNo,'') + '" readonly="readonly"/>\n';
		tag += '	<button type="button" class="btn icn" onclick="fnDeleteRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button>\n';
		tag += '</div>\n';
		return tag;
	}
	
	// 담당MD 삭제 시
	var fnDeleteRow = function(obj) {
		$(obj).closest('div').remove();
	}
	
	var fnSaveCallback = function() {
		$('#btnSearch').click();
		$("#btnNew").click();
	}
	
	// 엑셀다운로드
	$('#btnExcel').on('click', function() {
		gagaAgGrid.exportToExcel('브랜드 목록', gridOptions);
	});
	
	// 신규 버튼 클릭
	$("#btnNew").on("click", function() {
		$("#detailForm")[0].reset();
		$("#detailForm input[name=mode]").val("N");
		$("#detailForm select[name=brandGb]").trigger('change');
		$("#detailForm select[name=brandGb]").removeAttr("disabled");
		//$('#detailForm select[name=delvLocCd]').empty().append('<option value="">[선택]</option>');
		//$('#detailForm select[name=delvFeeCd]').empty().append('<option value="">[선택]</option>');
		$("#detailForm input[name=brandGroupNo]").val("");
		$("#detailForm input[type=checkbox]").removeClass("checked");
		$("#detailForm input[type=checkbox]").parent("label").removeClass("checked");
		
		// 자사구매포인트적립율 설정
		fnSetPntRate('S');

		// 브랜드담당MD 영역은 수정 시 노출
		$("#brandMdArea").removeClass("on").addClass("off");
		
		// 전시사이트 영역은 수정 시 노출
		$("#siteArea").removeClass("on").addClass("off");
		
		// 로고이미지 영역은 수정 시 노출
		$("#brandImgArea").removeClass("on").addClass("off");
		
		// 그리드 삭제
		var allData = gagaAgGrid.getAllRowData(gridOptions2);
		allData.forEach(function(item, index) {
			gridOptions2.api.updateRowData({remove: [item]});
		});
		
	});
	
	//이미지 클릭시 미리보기
	$("#bannerPreViewUrl").click(function(){
		cfnOpenImagePreViewPopup('bannerPreimgView',$('#bannerPreViewUrl').attr('src'));
	});
	
	//첨부파일 등록
	$('#detailForm input[name=file]').on('change', function() {
		var file = this.files[0];
		file.name = 'test';
		if (typeof(file) == 'undefined'){
			return;
		}
		
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/display'
				, file
				, function(result) {
					$('#detailForm input[name=newSysFileNm]').val(result.newFileName);
					$('#detailForm input[name=sysFileNm]').val(result.newFileName);
					$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+result.newFileName);
					$("#imgView").removeClass("off").addClass("on");
				}
				, 'image'
		);
	});

	// 저장
	$("#btnSave").on("click", function() {
		// 입력 값 체크
		if (!gagajf.validation('#detailForm'))
			return false;
		
		if (gagajf.isNull($('#detailForm input[name=brandGroupNo]').val())){
			mcxDialog.alert("브랜드그룹을 선택해 주세요.");
			return false;
		}
		
		if("S" == $('#detailForm select[name=brandGb]').val()){
			if ("G065_20" == $('#detailForm select[name=distributionGb]').val()){
				mcxDialog.alertC("유통구분을 확인해 주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$("#detailForm select[name=distributionGb]").focus();
					}
				});
				return false;
			}
		}else{
			if ("G065_20" != $('#detailForm select[name=distributionGb]').val()){
				mcxDialog.alertC("유통구분을 확인해 주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$("#detailForm select[name=distributionGb]").focus();
					}
				});
				return false;
			}
		}
			
		if (Number($('#detailForm input[name=pntPrate10]').val())<0 || Number($('#detailForm input[name=pntPrate10]').val())>=100){
			mcxDialog.alertC("포인트적립율(PC정상)을 확인해 주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$("#detailForm input[name=pntPrate10]").focus();
				}
			});
			return false;
		}
		
		if (Number($('#detailForm input[name=pntMrate10]').val())<0 || Number($('#detailForm input[name=pntMrate10]').val())>=100){
			mcxDialog.alertC("포인트적립율(모바일정상)을 확인해 주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$("#detailForm input[name=pntMrate10]").focus();
				}
			});
			return false;
		}
		
		if (Number($('#detailForm input[name=pntPrate20]').val())<0 || Number($('#detailForm input[name=pntPrate20]').val())>=100){
			mcxDialog.alertC("포인트적립율(PC이월)을 확인해 주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$("#detailForm input[name=pntPrate20]").focus();
				}
			});
			return false;
		}
		
		if (Number($('#detailForm input[name=pntMrate20]').val())<0 || Number($('#detailForm input[name=pntMrate20]').val())>=100){
			mcxDialog.alertC("포인트적립율(모바일이월)을 확인해 주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$("#detailForm input[name=pntMrate20]").focus();
				}
			});
			return false;
		}
		//공급업체
		var allData = gagaAgGrid.getAllRowData(gridOptions2);
		if (allData.length <= 0){
			mcxDialog.alert("공급업체를 추가해 주세요.");
			return false;
		}
		
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				
				var jsonData = JSON.stringify(allData);
				$('#detailForm input[name=brandSupplyListInfo]').val(jsonData);
				
				gagajf.ajaxFormSubmit($('#detailForm').prop('action'), '#detailForm', function() {
					$('#btnNew').trigger('click');
					$('#btnSearch').trigger('click');

					// 그리드 삭제
					allData.forEach(function(item, index) {
						gridOptions2.api.updateRowData({remove: [item]});
					});
				});
			}
		});
	});
	
	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
		gagaAgGrid.createGrid('gridList2', gridOptions2);
		
		$('#detailForm select[name=brandGb]').trigger('change');
	});
/*]]>*/
</script>

</html>
