<!DOCTYPE html>
<html lang="ko"
	  xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : MorebetterPopupForm.html
 * @desc    : 다다익선 등록 화면
 *============================================================================
 * STYLE24
 * Copyright(C) 2019 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.12.29   bin2107     최초 작성
 *******************************************************************************
 -->
<div class="modalPopup frGoodsPro" data-width="1100">
	<div class="panelStyle" style="max-height:700px;overflow-y:scroll;">
		<div class="panelTitle">
			<strong th:text="${'다다익선 ' + (mode == 'N' ? '등록' : '상세')}">다다익선 등록</strong>
			<button type="button" class="close" onclick="fnMorebetterFormClose()"><i class="fa fa-times"></i></button>
		</div>

		<form id="moreBetterForm" name="moreBetterForm" action="#" th:action="@{'/marketing/morebetter/save'}"> <!--th:method="post" >-->
			<input type="hidden" name="mode" th:value="${mode}"/>
			<input type="hidden" name="supplyCompList"/>			<!-- 공급업체 리스트 -->
			<input type="hidden" name="brandList"/>					<!-- 브랜드 리스트 -->
			<input type="hidden" name="applyGoodsList"/>			<!-- 적용상품 리스트 -->
			<input type="hidden" name="exceptGoodsList"/>			<!-- 제외상품 리스트 -->
			<input type="hidden" name="burdenList"/>				<!-- 업체 분담율 리스트 -->
			<input type="hidden" name="sectionGbList"/>				<!-- 다다익선 구간/혜택 리스트 -->

			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="10%"/>
						<col width="40%"/>
						<col width="10%"/>
						<col width="40%"/>
					</colgroup>
					<tr>
						<th>프로모션명<em class="required" title="필수"></em></th>
						<td>
							<!-- 수정시 프로모션명 입력 : before -->
							<input class="w50p" type="text" id="tmtbNm" name="tmtbNm" maxlength="30" required="required" data-valid-name="프로모션명"/>
						</td>
						<th>프로모션ID</th>
						<td>
							<!-- 프로모션 ID 입력 : before -->
							<label th:if="${mode == 'N'}">
								<input class="w50p" type="text" id="disTmtbSq1" name="disTmtbSq" maxlength="30" th:value="${params.tmtbSq}" disabled=""/> *자동생성
							</label>
							<label th:if="${mode == 'U'}">
								<input class="w50p" type="text" id="disTmtbSq2" name="disTmtbSq" maxlength="30" th:value="${tmtbSeq}" disabled=""/>
							</label>
							<input type="hidden" id="tmtbSq" name="tmtbSq"/>
						</td>
					</tr>
					<tr>
						<th>시작일<em class="required" title="필수"></em></th>
						<td>
							<input type="hidden" name="tmtbStdt" id="tmtbStdt" required="required" data-valid-name="다다익선시작일시">
							<input type="text" class="schDate w100" name="eventStdt" id="eventStdt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
							<select name="eventStHH" id="eventStHH" data-valid-name="다다익선시작(시)" style="width: 65px;"> <!--th:disabled="${mode == 'U'}"-->
								<th:block th:each="num, index : ${#numbers.sequence(0,23)}">
									<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${tmtbMstInfo.eventStHH == #numbers.formatInteger(num,2)}">시간</option>
								</th:block>
							</select>
							<select name="eventStMM" id="eventStMM" data-valid-name="다다익선시작(분)" style="width: 65px;">
								<th:block th:each="num, index : ${#numbers.sequence(0,59)}">
									<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}분|" th:selected="${tmtbMstInfo.eventStMM == #numbers.formatInteger(num,2)}">분</option>
								</th:block>
							</select>
						</td>
						<th>종료일<em class="required" title="필수"></em></th>
						<td>
							<input type="hidden" name="tmtbEddt" id="tmtbEddt" required="required" data-valid-name="다다익선종료일시">
							<input type="text" class="schDate w100" name="eventEddt" id="eventEddt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
							<select name="eventEdHH" id="eventEdHH" data-valid-name="다다익선종료(시)" style="width: 65px;">
								<th:block th:each="num, index : ${#numbers.sequence(0,23)}">
									<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${tmtbMstInfo.eventEdHH == #numbers.formatInteger(num,2)}">시간</option>
								</th:block>
								<option th:text="24시" th:value="24"></option>
							</select>
							<select name="eventEdMM" id="eventEdMM" data-valid-name="다다익선종료(분)" style="width: 65px;">
								<th:block th:each="num, index : ${#numbers.sequence(0,59)}">
									<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}분|" th:selected="${tmtbMstInfo.eventEdMM == #numbers.formatInteger(num,2)}">분</option>
								</th:block>
							</select>
						</td>
					</tr>
					<tr>
						<th>할인 구간<em class="required" title="필수"></em></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="sectionGb" id="sectionGbQty" value="G810_10" checked="checked"/>수량</label>
							<label class="rdoBtn"><input type="radio" name="sectionGb" id="sectionGbAmt" value="G810_11"/>금액</label>
							<input type="hidden" id="applyGb" name="applyGb"/>
						</td>
						<th>할인 구분<em class="required" title="필수"></em></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="dcWay" id="dcWayQty" value="G240_10" checked="checked"/>할인금액</label>
							<label class="rdoBtn"><input type="radio" name="dcWay" id="dcWayAmt" value="G240_11"/>할인율</label>
						</td>
					</tr>
					<tr>
						<th>상태<em class="required" title="필수"></em></th>
						<td>
							<!-- 상태 입력 : before
                            <input class="w50p" type="text" id="disTmtbStat" name="disTmtbStat" maxlength="30" th:value="${params.tmtbStat}" disabled=""/>-->
							<label class="rdoBtn" th:if="${tmtbStatList}" th:each="oneData, status : ${tmtbStatList}" ><input type="radio" id="disTmtbStat" name="disTmtbStat" th:value="${oneData.cd}" th:text="${oneData.cdNm}" data-valid-name="상태" disabled="disabled"/></label>
							<input type="hidden" id="tmtbStat" name="tmtbStat"/>
						</td>
					</tr>

				</table>
			</div>
			<div class="panelStyle" style="margin:unset;">
				<!-- TITLE -->
				<div class="panelTitle">
					<h2>할인 구간</h2>
					<span class="panelControl">
						<i class="fa inner-fa-chevron-up"></i>    <!-- 열림/닫힘 화살표 -->
					</span>
				</div>
				<!-- //TITLE -->
				<div class="inner-panelContent">
					<div class="panelContent">
						<table class="frmStyle">
							<colgroup>
								<col width="10%"/>
								<col width="90%"/>
							</colgroup>
							<tr>
								<th>할인 구간</th>
								<td>
									<div class="padding10">
										<span class="buttonSpan">
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddSectionRow">행추가</button>
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnDelSectionRow">행삭제</button>
										</span>
										<br/>
										<div id="gridSectionGbList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>
			<div class="panelStyle" style="margin:unset;">
				<!-- TITLE -->
				<div class="panelTitle">
					<h2>적용 대상 상품 등록</h2>
					<span class="panelControl">
							<i class="fa inner-fa-chevron-up"></i>    <!-- 열림/닫힘 화살표 -->
						</span>
				</div>
				<!-- //TITLE -->
				<div class="inner-panelContent">
					<!--<div><i class="fa fa-info-circle"></i> 브랜드/공급업체/상품 중 1가지는 필수로 지정하셔야 합니다.</div>
                    <div><i class="fa fa-info-circle"></i> 브랜드와 공급업체는 지정 시, 해당 브랜드의 공급처와 같은 AND조건으로 적용됩니다.(예시:A브랜드 상품 중 B업체 상품만)</div>
                    <div><i class="fa fa-info-circle"></i> 공급업체와 브랜드를 적용하시더라도 적용상품은 별개로 등록된 상품을 기준으로 사은품 지급기준으로 적용하실 수 있습니다.</div>-->

					<div class="panelContent">
						<table class="frmStyle">
							<colgroup>
								<col width="10%"/>
								<col width="90%"/>
							</colgroup>
							<tr>
								<th>공급업체/브랜드</th>
								<td>
									<!-- 수정시 프로모션명 입력 : before -->
									<div class="padding10" style="display:inline-block;width:49%;">
										<!--<span>공급업체 설정</span>-->
										<div class="padding10 inner-tb-solid">
											<span class="buttonSpan">
												<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddCompany">업체 추가</button>
												<button type="button" class="btn btnRight btn-success btn-lg" id="btnDeleteCompany">선택삭제</button>
											</span>
											<br/>
											<div id="gridFGPromotionCompanyList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
										</div>
									</div>
									<div class="padding10" style="display:inline-block;width:49%;">
										<!--<span>브랜드 설정</span>-->
										<div class="padding10 inner-tb-solid">
											<span class="buttonSpan">
												<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddBrand">브랜드 추가</button>
												<button type="button" class="btn btnRight btn-success btn-lg" id="btnDeleteBrand">선택삭제</button>
											</span>
											<br/>
											<!-- 브랜드 선택 팝업(단수 선택 팝업... 복수를 새로 만들어야하는지 ? 아니면 변수처리해야하는지 ? -->
											<div id="gridFGBrandList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th>적용상품</th>
								<td>
									<div class="padding10">
										<span class="buttonSpan">
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddApplyGoods">상품 추가</button>
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnDeleteApplyGoods">선택삭제</button>
										</span>
										<br/>
										<div id="gridFGApplyGoodsList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
									</div>
								</td>
							</tr>
							<tr class="off"> <!---->
								<th>업체&브랜드상품</th>
								<td>
									<div class="padding10" style="display: none;"> <!---->
										<div id="gridDuplicateGoodsList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>

			<div class="panelStyle" style="margin:unset;">
				<!-- TITLE -->
				<div class="panelTitle">
					<h2>제외 대상 상품</h2>
					<span class="panelControl">
							<i class="fa inner-fa-chevron-up"></i>    <!-- 열림/닫힘 화살표 -->
						</span>
				</div>
				<!-- //TITLE -->
				<div class="inner-panelContent">
					<div class="panelContent">
						<table class="frmStyle">
							<colgroup>
								<col width="10%"/>
								<col width="90%"/>
							</colgroup>
							<tr>
								<th>제외 대상</th>
								<td>
									<div class="padding10">
										<span class="buttonSpan">
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddExceptGoods">상품 추가</button>
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnDeleteExtGoods">선택삭제</button>
										</span>
										<br/>
										<div id="gridFGExceptGoodsList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>

			<div class="panelStyle" style="margin:unset;">
				<!-- TITLE -->
				<div class="panelTitle">
					<h2>업체 분담율</h2>
					<span class="panelControl">
						<i class="fa inner-fa-chevron-up"></i>    <!-- 열림/닫힘 화살표 -->
					</span>
				</div>
				<!-- //TITLE -->
				<div class="inner-panelContent">
					<div class="panelContent">
						<table class="frmStyle">
							<colgroup>
								<col width="10%"/>
								<col width="90%"/>
							</colgroup>
							<tr>
								<th>업체 분담율</th>
								<td>
									<div class="padding10">
										<span class="buttonSpan">
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnAddApplyBurden">업체추가</button>
											<button type="button" class="btn btnRight btn-success btn-lg" id="btnDelApplyBurden">선택삭제</button>
										</span>
										<br/>
										<div id="gridApplyBurdenList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>

			<div class="panelStyle" style="margin:unset;" th:if="${mode == 'U'}">
				<div class="inner-panelContent">
					<div class="panelContent">
						<table class="frmStyle">
							<colgroup>
								<col width="10%"/>
								<col width="40%"/>
								<col width="10%"/>
								<col width="40%"/>
							</colgroup>
							<tr>
								<th>등록자</th>
								<td>
									<span id="regInfo">등록자이름(연.월.일 시간:분:초)</span>
								</td>
								<th>최종수정자</th>
								<td>
									<span id="updInfo">수정자이름(연.월.일 시간:분:초)</span>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>
		</form>

		<ul class="panelBar">
			<li  class="right">
				<button type="button" class="btn btnRight btn-success btn-lg" id="btnSearchList">목록</button>
				<button type="button" class="btn btnRight btn-success btn-lg tmtbButton" id="btnMorebetterSave" style="display: none;">저장</button>
				<!--<button type="button" th:if="${mode == 'N'}" class="btn btnRight btn-success btn-lg" id="btnMorebetterSave">저장</button>
				<button type="button" th:if="${mode == 'U'}" class="btn btnRight btn-success btn-lg" id="btnMorebetterUpdate">수정</button>-->
				<button type="button" class="btn btnRight btn-success btn-lg tmtbButton" id="btnChangeStatIng" style="display: none;">진행</button>
				<button type="button" class="btn btnRight btn-success btn-lg tmtbButton" id="btnMorebetterDelete" style="display: none;">삭제</button>
				<button type="button" class="btn btnRight btn-success btn-lg tmtbButton" id="btnMorebetterStop" style="display: none;">중지</button>
			</li>
		</ul>
	</div>
</div>

<script th:inline="javascript">
	// 상세 조회시 데이터 리스트
	let confirmBtnText = ["확인", "취소"];
	var mode = [[${mode}]];
	var tmtbMstInfo = [[${tmtbMstInfo}]];
	var tmtbSectionValList = [[${tmtbSectionValList}]];
	var tmtbSupplyCompList = [[${tmtbSupplyCompList}]];
	var tmtbBrandList = [[${tmtbBrandList}]];
	var tmtbApplyGoodsList = [[${tmtbApplyGoodsList}]];
	var tmtbExceptGoodsList = [[${tmtbExceptGoodsList}]];
	var tmtbBurdenList = [[${tmtbBurdenList}]];

	// 공통 코드 리스트
	var FGAddGoodsStatList = gagajf.convertToArray([[${goodsStatList}]]);		// 상품 상태 리스트
	var sectionGbList = gagajf.convertToArray([[${sectionGbList}]]);	// 할인구간 리스트
	var dcWayList = gagajf.convertToArray([[${dcWayList}]]);	// 할인구분 리스트
	var applyGoodsGbList = gagajf.convertToArray([[${applyGoodsGbList}]]);	// 적용 상품구분 목록
	var exceptGoodsGbList = gagajf.convertToArray([[${exceptGoodsGbList}]]);	// 제외 상품구분 목록

	// 공급업체 리스트 설정
	var columnFGCompanyList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "공급처ID", field: "supplyCompCd", width: 120, cellClass: 'text-center'},
		{headerName: "공급업체명", field: "supplyCompNm", width: 150, cellClass: 'text-center'},
		{headerName: "적용대상", field: "targetGb", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "시퀀스", field: "tmtbGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "삭제여부", field: "delYn", width: 150, cellClass: 'text-center', hide: true}
	];
	// 브랜드 리스트 설정
	var columnBrandList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "브랜드ID", field: "brandCd", width: 110, cellClass: 'text-center'},
		{headerName: "브랜드명", field: "brandEnm", width: 120, cellClass: 'text-center'},
		{headerName: "공급업체명", field: "supplyCompNm", width: 150, cellClass: 'text-center'},
		{headerName: "적용대상", field: "targetGb", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "시퀀스", field: "tmtbGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "삭제여부", field: "delYn", width: 150, cellClass: 'text-center', hide: true}
	];
	// 적용상품 리스트 설정
	var columnApplyGoodsList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "상품구분", field: "goodsGb", width: 100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(applyGoodsGbList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(applyGoodsGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(applyGoodsGbList, params.newValue); }
		},
		{headerName: "상품코드", field: "goodsCd", width: 120, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 120, cellClass: 'text-center'},
		{headerName: "적용대상", field: "targetGb", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "시퀀스", field: "tmtbGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "실제적용대상 시퀀스", field: "tmtbApplyGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "삭제여부", field: "delYn", width: 150, cellClass: 'text-center', hide: true}
	];
	// 제외상품 리스트 설정
	var columnExceptGoodsList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "상품구분", field: "goodsGb", width: 100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(exceptGoodsGbList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(exceptGoodsGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(exceptGoodsGbList, params.newValue); }
		},
		{headerName: "상품코드", field: "goodsCd", width: 120, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 120, cellClass: 'text-center'},
		{headerName: "적용대상", field: "targetGb", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "시퀀스", field: "tmtbGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "실제적용대상 시퀀스", field: "tmtbApplyGoodsSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "삭제여부", field: "delYn", width: 150, cellClass: 'text-center', hide: true}
	];

	// 업체분담율 리스트 설정
	var columnApplyBurdenList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "업체ID", field: "tmtbSupplyCd" , width: 120, cellClass: 'text-center', editable: false},
		{headerName: "업체명", field: "supplyCompNm" , width: 120, cellClass: 'text-center', editable: false},
		{headerName: "분담율(%)", field: "tmtbBurdenRate" , width: 120, cellClass: 'text-center',required: true
			,editable: true
			,cellRenderer: function (params) {
				if(params.value > 100) {
					mcxDialog.alert('분담율은 100을 넘을 수 없습니다.');
					return 0;
				}else{
					return params.value;
				}
			}
			// ,valueFormatter: function(params) {
			// 	if(params.value && params.value > 0) {
			// 		return params.value.addComma();
			// 	} else {
			// 		return '0';
			// 	}
			// },
			//cellEditor: 'textCellEditor',
			,cellEditorParams: { maxlength: 3, validType: 'numeric'}
		},
		{headerName: "사용여부", field: "useYn" , width: 120, cellClass: 'text-center', hide: true},
		{headerName: "시퀀스", field: "tmtbBurdenSq", width: 150, cellClass: 'text-center', hide: true}
	];

	// 구간 할인/혜택 설정
	var columnSectionGbList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "시퀀스", field: "tmtbSq", width: 100, cellClass: 'text-center', hide: true},
		{headerName: "할인구간", field: "sectionGb", width: 100, cellClass: 'text-center', editable: false,
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(sectionGbList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(sectionGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(sectionGbList, params.newValue); }
		},
		{headerName: "구간값", field: "sectionVal", width: 100, cellClass: 'text-right', required: true
			,valueFormatter: function(params) {
				if(params.value && params.value > 0) {
					return params.value.addComma();
				} else {
					return '0';
				}
			},
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "할인구분", field: "dcWay", width: 100, cellClass: 'text-center', editable: false,
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(dcWayList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(dcWayList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(dcWayList, params.newValue); }
		},
		{headerName: "할인값", field: "dcVal", width: 100, cellClass: 'text-right', required: true
			,valueFormatter: function(params) {
				if(params.value && params.value > 0) {
					if(params.data.dcWay == "G240_11"){
						if(params.value.length > 2){
							mcxDialog.alert('할인율은 100이하로 설정해주세요.');
							params.data.dcVal = '0';
							return '0';
						}
					}
					return params.value.addComma();
				} else {
					return '0';
				}
			},
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "구간시퀀스", field: "tmtbSectionSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "할인값시퀀스", field: "tmtbValSq", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "삭제여부", field: "delYn", width: 150, cellClass: 'text-center', hide: true}
	];
	// 다른 다다익선 사용중인 중복상품 엑셀 리스트 설정
	var columnDuplicateGoodsList = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "상품코드", field: "goodsCd", width: 120, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 120, cellClass: 'text-center'}
	];

	// 공급업체 리스트 설정
	var gridOptionsFGCompanyList = gagaAgGrid.getGridOptions(columnFGCompanyList);
	gridOptionsFGCompanyList.rowSelection = "multiple";
	// 브랜드 리스트 설정
	var gridOptionsFGBrandList = gagaAgGrid.getGridOptions(columnBrandList);
	gridOptionsFGBrandList.rowSelection = "multiple";
	// 적용상품 리스트 설정
	var gridOptionsFGApplyGoodsList = gagaAgGrid.getGridOptions(columnApplyGoodsList);
	// Grid editable
	gridOptionsFGApplyGoodsList.defaultColDef.editable = true;
	gridOptionsFGApplyGoodsList.rowSelection = "multiple";
	// 제외상품 리스트 설정
	var gridOptionsFGExceptGoodsList = gagaAgGrid.getGridOptions(columnExceptGoodsList);
	gridOptionsFGExceptGoodsList.rowSelection = "multiple";
	// 업체분담율 리스트 설정
	var gridOptionsApplyBurdenList = gagaAgGrid.getGridOptions(columnApplyBurdenList);
	gridOptionsApplyBurdenList.defaultColDef.editable = true;
	gridOptionsApplyBurdenList.rowSelection = "multiple";
	// 구간 할인/혜택 설정
	var gridOptionsSectionGbList = gagaAgGrid.getGridOptions(columnSectionGbList);
	// Grid editable
	gridOptionsSectionGbList.defaultColDef.editable = true;
	// Add on options
	//gridOptionsSectionGbList.suppressRowClickSelection = true;
	gridOptionsSectionGbList.rowSelection = "multiple";
	//gridOptionsSectionGbList.stopEditingWhenGridLosesFocus = true;

	// 다른 다다익선 사용중인 중복상품 엑셀 리스트 설정
	var gridOptionsDuplicateGoodsList = gagaAgGrid.getGridOptions(columnDuplicateGoodsList);
	gridOptionsDuplicateGoodsList.rowSelection = "multiple";

	$(document).ready(function() {
		// 1.그리드 그리기
		gagaAgGrid.createGrid("gridFGPromotionCompanyList", gridOptionsFGCompanyList);
		gagaAgGrid.createGrid("gridFGBrandList", gridOptionsFGBrandList);
		gagaAgGrid.createGrid("gridFGApplyGoodsList", gridOptionsFGApplyGoodsList);
		gagaAgGrid.createGrid("gridFGExceptGoodsList", gridOptionsFGExceptGoodsList);
		gagaAgGrid.createGrid("gridApplyBurdenList", gridOptionsApplyBurdenList);
		gagaAgGrid.createGrid("gridSectionGbList", gridOptionsSectionGbList);
		gagaAgGrid.createGrid("gridDuplicateGoodsList", gridOptionsDuplicateGoodsList);

		// 일단 버튼 숨김
		$(".tmtbButton").hide();

		// 2. 그리드 데이터 바인딩
		if(mode == "U"){
			gridOptionsFGCompanyList.api.setRowData(tmtbSupplyCompList);
			gridOptionsFGBrandList.api.setRowData(tmtbBrandList);
			gridOptionsFGApplyGoodsList.api.setRowData(tmtbApplyGoodsList);
			gridOptionsFGExceptGoodsList.api.setRowData(tmtbExceptGoodsList);
			gridOptionsSectionGbList.api.setRowData(tmtbSectionValList)
			gridOptionsApplyBurdenList.api.setRowData(tmtbBurdenList);

			$('#moreBetterForm input[name=tmtbNm]').val(tmtbMstInfo.tmtbNm);
			$('#moreBetterForm input[name=eventStdt]').val(tmtbMstInfo.eventStdt);
			$('#moreBetterForm input[name=eventEddt]').val(tmtbMstInfo.eventEddt);
			$('#moreBetterForm #regInfo').text(tmtbMstInfo.regNm + "(" + tmtbMstInfo.regDt + ")");
			$('#moreBetterForm #updInfo').text(tmtbMstInfo.updNm + "(" + tmtbMstInfo.updDt + ")");
			$("input:radio[name='disTmtbStat']:radio[value="+tmtbMstInfo.tmtbStat+"]").prop('checked', true); // 선택하기
			$("input:radio[name='sectionGb']:radio[value="+tmtbMstInfo.sectionGb+"]").prop('checked', true); // 선택하기
			$("input:radio[name='dcWay']:radio[value="+tmtbMstInfo.dcWay+"]").prop('checked', true); // 선택하기

			let edDtArr = tmtbMstInfo.tmtbEddt.split(" ");
			if(edDtArr[1] == "23:59:59") {
				edHour = "24";
				edMinute = "00";
				$('#moreBetterForm #eventEdHH option:last').show().prop("selected", true);
				$("#moreBetterForm #eventEdMM option").hide();
				$('#moreBetterForm #eventEdMM option:first').show().prop("selected", true);
			}

			if(tmtbMstInfo.tmtbStat == "G232_10"){
				$("#btnMorebetterSave").show();		// 저장버튼
				$("#btnChangeStatIng").show();		// 진행버튼
				$("#btnMorebetterDelete").show();	// 삭제버튼
				$("#moreBetterForm .buttonSpan").show();	//행추가,삭제버튼
			}else if(tmtbMstInfo.tmtbStat == "G232_11"){
				$("#btnMorebetterSave").hide();		// 저장버튼
				$("#btnMorebetterStop").show();		// 중지버튼
				$("#btnMorebetterDelete").show();	// 삭제버튼
				$("#moreBetterForm .buttonSpan").hide();	//행추가,삭제버튼
			}else{
				$("#moreBetterForm .buttonSpan").hide();	//행추가,삭제버튼
			}
		}

		// 구분 -> 대기로 체크
		if(mode=="N"){
			$("input:radio[name='disTmtbStat']:radio[value='G232_10']").prop('checked', true); // 선택하기
			$("#btnMorebetterSave").show();	// 저장버튼
			$("#moreBetterForm .buttonSpan").show();

			if(tmtbMstInfo.eventEdHH == "24"){
				$("#moreBetterForm #eventEdHH option:last").show().prop("selected", true);
				$("#moreBetterForm #eventEdMM option").hide();
				$('#moreBetterForm #eventEdMM option:first').show().prop("selected", true);
			}
		}
		//cfnCreateCalendar('#tmtbTerms', 'tmtbStdt', 'tmtbEddt', true, '행사기간', 'X');
		cfnCreateCalendar('#tmtbTerms', 'eventStdt', 'eventEddt', true, '행사기간', 'X');
	});

	// 종료시간 클릭 시
	$("#moreBetterForm #eventEdHH").bind('click change', function () {
		if(this.value == 24) {
			$("#moreBetterForm #eventEdMM option").hide();
			$('#moreBetterForm #eventEdMM option:first').show().prop("selected", true);
		} else {
			$("#moreBetterForm #eventEdMM option").show();
		}
	});

	var fnGoodsGbCheck = function (){
		let applyGoodsData = gagaAgGrid.getAllRowData(gridOptionsFGApplyGoodsList);
		var checkCnt = 0;
		$.each(applyGoodsData, function(idx, item) {
			if(item.goodsGb == 'G800_10'){
				checkCnt++;
			}
		});

		if(checkCnt < 1){
			mcxDialog.alert("기본상품을 1개 이상 지정해주세요.");
			return false;
		}

		return true;
	};

	var fnBurdenValueCheck = function (){
		let burdenData = gagaAgGrid.getAllRowData(gridOptionsApplyBurdenList);
		let totalValue = 0;
		$.each(burdenData, function(idx, item) {
			totalValue += parseInt(item.tmtbBurdenRate);
		});

		if(totalValue > 100) {
			mcxDialog.alert("업체분담율의 합이 100을 넘을수 없습니다.");
			return false;
		}

		return true;
	};

	var checkDateValidation = function (){
		if (gagajf.isNull($('#moreBetterForm input[name=eventStdt]').val())) {
			mcxDialog.alert("시작일자를 입력하세요.");
			$('#moreBetterForm input[name=tmtbStdt]').focus();
			return false;
		}

		if (gagajf.isNull($('#moreBetterForm input[name=eventEddt]').val())) {
			mcxDialog.alert("종료일자를 입력하세요.");
			$('#moreBetterForm input[name=eventEddt]').focus();
			return false;
		}

		var eventStDt = "";
		var eventEdDt = "";

		eventStDt = $('#moreBetterForm input[name=eventStdt]').val()+$('#moreBetterForm select[name=eventStHH]').val()+$('#moreBetterForm select[name=eventStMM]').val()+'00';
		if($('#moreBetterForm select[name=eventEdHH]').val() == "24"){
			eventEdDt = $('#moreBetterForm input[name=eventEddt]').val()+'235959';
		}else{
			eventEdDt = $('#moreBetterForm input[name=eventEddt]').val()+$('#moreBetterForm select[name=eventEdHH]').val()+$('#moreBetterForm select[name=eventEdMM]').val()+'00';
		}

		eventStDt = eventStDt.replace(/[^0-9]/g, '');
		eventEdDt = eventEdDt.replace(/[^0-9]/g, '');

		if (eventStDt > eventEdDt) {
			mcxDialog.alert("시작일자는 종료일자 보다 클 수 없습니다.");
			$('#moreBetterForm input[name=tmtbStdt]').focus();
			return false;
		}

		$('#moreBetterForm input[name=tmtbStdt]').val(eventStDt);
		$('#moreBetterForm input[name=tmtbEddt]').val(eventEdDt);

		return true;
	}

	// 저장
	$('#btnMorebetterSave').on('click', function() {
		// validation
		if (!gagajf.validation('#moreBetterForm')){
			return false;
		}

		// 기간체크
		if(!checkDateValidation()){
			return false;
		}

		// 적용상품 그리드에 기본상품 1개이상 있는지 체크
		if(!fnGoodsGbCheck()) {
			return false;
		}

		// 업체분담율 토탈 100% 넘는지 체크
		// if(!fnBurdenValueCheck()) {
		// 	return false;
		// }

		// 각 ag-grid list 수량
		let allSupplyCompData = gagaAgGrid.getAllRowData(gridOptionsFGCompanyList);
		let allBrandData = gagaAgGrid.getAllRowData(gridOptionsFGBrandList);
		let allApplyGoodsData = gagaAgGrid.getAllRowData(gridOptionsFGApplyGoodsList);
		let allExceptGoodsData = gagaAgGrid.getAllRowData(gridOptionsFGExceptGoodsList);
		let allApplyBurdenData = gagaAgGrid.getAllRowData(gridOptionsApplyBurdenList);
		let allSectionGbData = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

		if(allSectionGbData.length < 1){
			mcxDialog.alert("할인구간을 설정해주세요.");
			return false;
		}

		// 공급업체+브랜드 상품조회
		var multiSupplyCompCd = [];
		$.each(allSupplyCompData, function(idx, item) {
			multiSupplyCompCd.push(item.supplyCompCd);
		});

		var multiBrand = [];
		$.each(allBrandData, function(idx, item) {
			multiBrand.push(item.brandCd);
		});

		var multiApplyGoods = [];
		$.each(allApplyGoodsData, function(idx, item) {
			multiApplyGoods.push(item.goodsCd);
		});

		var multiExceptGoods = [];
		$.each(allExceptGoodsData, function(idx, item) {
			multiExceptGoods.push(item.goodsCd);
		});

		var data = {
			mode : $('#moreBetterForm input[name=mode]').val()
			, tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
			, tmtbNm : $('#moreBetterForm input[name=tmtbNm]').val()
			, tmtbStat : $('input:radio[name="disTmtbStat"]:checked').val()
			, tmtbStdt : $('#moreBetterForm input[name=tmtbStdt]').val()
			, tmtbEddt : $('#moreBetterForm input[name=tmtbEddt]').val()
			, sectionGb : $('input:radio[name="sectionGb"]:checked').val()
			, applyGb : $('input:radio[name="sectionGb"]:checked').val()
			, dcWay : $('input:radio[name="dcWay"]:checked').val()
			, supplyCompList : allSupplyCompData
			, brandList : allBrandData
			, applyGoodsList : allApplyGoodsData
			, gridApplyGoodsList : allApplyGoodsData
			, exceptGoodsList : allExceptGoodsData
			, burdenList : allApplyBurdenData
			, sectionGbList : allSectionGbData
			, multiSupplyCompCd : multiSupplyCompCd
			, multiBrand : multiBrand
			, multiApplyGoods : multiApplyGoods
			, multiExceptGoods : multiExceptGoods
		};

		var jsonData = JSON.stringify(data);

		gagajf.ajaxJsonSubmit($('#moreBetterForm').prop('action'), jsonData, fnMorebetterSaveCollback);
	});

	var fnMorebetterSaveCollback = function(result){
		if(result.duplicateYn == "Y"){
			for(let i=0; i<result.duplicateGoodsList.length; i++){
				gagaAgGrid.addRowData(gridOptionsDuplicateGoodsList, {"goodsCd" : result.duplicateGoodsList[i].goodsCd, "goodsNm" : result.duplicateGoodsList[i].goodsNm});
			}
			mcxDialog.alert("다른 다다익선에서 사용중인 상품이 존재합니다.");
			gagaAgGrid.exportToExcel('다다익선 중복상품 목록', gridOptionsDuplicateGoodsList);
			fnMorebetterFormClose();
			$('#btnInit').trigger('click');
			$('#btnSearch').trigger('click');
		}else{
			//mcxDialog.alert(result.message);
			fnMorebetterFormClose();
			$('#btnInit').trigger('click');
			$('#btnSearch').trigger('click');
		}
	}

	// 공급업체 설정 / 업체 추가 콜백함수
	var fnSetPopupComapnyInfo = function(result) {
		// 기존 리스트 데이터 for
		for(let i = 0 ; i < result.length ; i++) {
			let addChk = true, gridListValue = gagaAgGrid.getAllRowData(gridOptionsFGCompanyList);		// 받아온 모든 데이터

			// 받아온 data for
			for(let j = 0 ; j < gridListValue.length ; j++) {
				// 동일한 data는 추가하지 않음
				if(gridListValue[j].supplyCompCd == result[i].supplyCompCd) {	addChk = false;	}		// 중복체크
			}

			// 중복되지 않은 데이터 리스트에 추가
			if(addChk) {
				gagaAgGrid.addRowData(gridOptionsFGCompanyList, {"supplyCompCd" : result[i].supplyCompCd, "supplyCompNm" : result[i].supplyCompNm, "targetGb" : "G260_13"});
			}
		}

		// 브랜드 데이터 체크
		/*let allBrandCnt = gagaAgGrid.getAllRowData(gridOptionsFGBrandList).length;
		if(allBrandCnt<1){
			mcxDialog.alert('브랜드를 추가해주세요.');
			return;
		}*/
	};

	// 브랜드 설정 / 브랜드 추가 콜백함수 (단수로 가져오므로 복수일 경우에 수정 확인 필요)
	var fnSetPopupBrandInfo = function(result) {
		for(let i = 0 ; i < result.length ; i++) {
			let addChk = true, gridListValue = gagaAgGrid.getAllRowData(gridOptionsFGBrandList);		// 받아온 모든 데이터

			// 받아온 data for
			for(let j = 0 ; j < gridListValue.length ; j++) {
				if(gridListValue[j].brandCd == result[i].brandCd) {	addChk = false;	}					// 중복체크
			}

			// 중복되지 않은 데이터 리스트에 추가
			if(addChk) {
				gagaAgGrid.addRowData(gridOptionsFGBrandList, {"brandCd" : result[i].brandCd, "brandEnm" : result[i].brandEnm, "supplyCompNm" : result[i].supplyCompNm, "targetGb" : "G260_12"});
			}
		}

		// 공급업체 데이터 체크
		/*var allSupplyCompData = gagaAgGrid.getAllRowData(gridOptionsFGCompanyList);
		var allBrandData = gagaAgGrid.getAllRowData(gridOptionsFGBrandList);

		if(allSupplyCompData.length < 1){
			mcxDialog.alert('공급업체를 추가해주세요.');
			return;
		}*/
	};

	// 분담업체율 설정 / 업체 추가 콜백함수
	var fnSetPopupApplyBurdenInfo = function(result) {
		// 기존 리스트 데이터 for
		for(let i = 0 ; i < result.length ; i++) {
			//console.log('old i::'+i+"::"+result[i].supplyCompCd);
			let addChk = true, gridListValue = gagaAgGrid.getAllRowData(gridOptionsApplyBurdenList);		// 받아온 모든 데이터

			// 받아온 data for
			for(let j = 0 ; j < gridListValue.length ; j++) {
				//console.log('new add j::'+j+":supplyCompCd:"+gridListValue[j].tmtbSupplyCd);
				// 동일한 data는 추가하지 않음
				if(gridListValue[j].tmtbSupplyCd == result[i].supplyCompCd) {	addChk = false;	}		// 중복체크
			}

			// 중복되지 않은 데이터 리스트에 추가
			if(addChk) {
				//gagaAgGrid.addRowData(gridOptionsApplyBurdenList, result[i], "tmtbSupplyCd");
				gagaAgGrid.addRowData(gridOptionsApplyBurdenList, {"tmtbSupplyCd" : result[i].supplyCompCd, "supplyCompNm" : result[i].supplyCompNm, "useYn" : result[i].useYn});
			}
		}
	};

	// 적용 상품 리스트 콜백함수
	var fnSetPopupApplyGoodsInfo = function(result) {
		gridAddGoodsList(gridOptionsFGApplyGoodsList, result , "apply");
	};

	// 제외 상품 리스트 콜백함수
	var fnSetPopupExceptGoodsInfo = function(result) {
		gridAddGoodsList(gridOptionsFGExceptGoodsList, result , "except");
	};

	// ag-grid 상품관련 list 콜백함수
	function gridAddGoodsList(OriginGridListOption, result, gubun) {
		var goodsGbVal = "G800_10";
		if(gubun == 'except'){
			goodsGbVal = "G800_30";
		}

		let addCnt = 0;
		let failCnt = 0;
		let dupliCnt = 0;
		let goodsDCnt = 0;

		for(let i = 0 ; i < result.length ; i++) {
			let addChk = true, gridListValue = gagaAgGrid.getAllRowData(OriginGridListOption);		// 받아온 모든 데이터
			if(result[i].goodsType == 'G056_D'){ //딜상품 제외
				addChk = false;
				goodsDCnt++;
			}
			// 받아온 data for
			for(let j = 0 ; j < gridListValue.length ; j++) {
				if(gridListValue[j].goodsCd == result[i].goodsCd) { // 중복체크
					addChk = false;
					dupliCnt++;
				}
			}

			// 중복되지 않은 데이터 리스트에 추가
			if(addChk) {
				//gagaAgGrid.addRowData(OriginGridListOption, result[i], "goodsCd");
				gagaAgGrid.addRowData(OriginGridListOption, {"goodsGb": goodsGbVal, "goodsCd" : result[i].goodsCd, "goodsNm" : result[i].goodsNm, "targetGb" : "G260_10" , "delYn" : "N"});
				addCnt++;
			}
		}
		uifnPopupClose('popupGoods');
		failCnt = result.length - addCnt - dupliCnt - goodsDCnt;
		mcxDialog.alert("데이터가 적용되었습니다.<br/>" + addCnt + "건 성공, "+ dupliCnt + "건 중복, "+ goodsDCnt + "건 딜상품 제외, " + failCnt + "건 실패");
	}

	// 공급업체 설정 업체 추가 버튼 클릭시
	$('#moreBetterForm #btnAddCompany').on('click', function() {
		cfnOpenCompanyListPopup("fnSetPopupComapnyInfo", "M");
	});

	// 브랜드 추가 버튼 클릭시 (복수 브랜드때 수정 필요)
	$('#moreBetterForm #btnAddBrand').on('click', function() {
		cfnOpenBrandListPopup("fnSetPopupBrandInfo", "M");
	});

	// 적용 상품 추가 버튼 클릭시
	$('#moreBetterForm #btnAddApplyGoods').on('click', function() {
		cfnOpenGoodsPopup("fnSetPopupApplyGoodsInfo");
	});
	// 제외 상품 추가 버튼 클릭시
	$('#moreBetterForm #btnAddExceptGoods').on('click', function() {
		cfnOpenGoodsPopup("fnSetPopupExceptGoodsInfo");
	});
	// 업체분담율 추가 버튼 클릭시
	$('#moreBetterForm #btnAddApplyBurden').on('click', function() {
		//cfnOpenApplyBurdenPopup("fnSetPopupApplyBurdenInfo");
		cfnOpenCompanyListPopup("fnSetPopupApplyBurdenInfo", "M");
	});

	// 할인구간 선택삭제 버튼 클릭시
	$('#moreBetterForm #btnDelSectionRow').on('click', function() {
		gridOptionsSectionGbList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsSectionGbList)});
	});
    // 공급업체 설정 선택삭제 버튼 클릭시
    $('#moreBetterForm #btnDeleteCompany').on('click', function() {
        gridOptionsFGCompanyList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsFGCompanyList)});
    });
    // 브랜드 설정 선택삭제 버튼 클릭시
    $('#moreBetterForm #btnDeleteBrand').on('click', function() {
        gridOptionsFGBrandList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsFGBrandList)});
    });
    // 적용상품 선택삭제 버튼 클릭시
    $('#moreBetterForm #btnDeleteApplyGoods').on('click', function() {
        gridOptionsFGApplyGoodsList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsFGApplyGoodsList)});
    });
    // 제외상품 선택삭제 버튼 클릭시
    $('#moreBetterForm #btnDeleteExtGoods').on('click', function() {
        gridOptionsFGExceptGoodsList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsFGExceptGoodsList)});
    });
    // 업체분담율 선택삭제 버튼 클릭시
    $('#moreBetterForm #btnDelApplyBurden').on('click', function() {
        gridOptionsApplyBurdenList.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsApplyBurdenList)});
    });

	//패널영역 줄이기
	$(document).on("click",".panelControl .inner-fa-chevron-up", function() {
		$(this).parent().parent().parent().find(".inner-panelContent").slideUp(100);
		$(this).attr("class","fa inner-fa-chevron-down");
	});
	//패널영역 펼치기
	$(document).on("click",".panelControl .inner-fa-chevron-down", function() {
		$(this).parent().parent().parent().find(".inner-panelContent").slideDown(100);
		$(this).attr("class","fa inner-fa-chevron-up");
	});

	// 창 닫기
	var fnMorebetterFormClose = function(){
		uifnPopupClose('popupMorebetterReg');
	}

	// 구간할인 행추가
	$('#btnAddSectionRow').on('click', function() {
		var tmtbSq = $('#moreBetterForm input[name=disTmtbSq]').val();
		var sectionGbValue = $('input:radio[name="sectionGb"]:checked').val();
		var dcWayValue = $('input:radio[name="dcWay"]:checked').val();

		var optionList = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

		if (optionList.length > 4) {
			mcxDialog.alert('할인 구간은 최대 5개까지 등록 가능합니다.');
			return;
		}

		var data = { tmtbSq: tmtbSq ,sectionGb: sectionGbValue, sectionVal: null, dcWay: dcWayValue, dcVal: null };
		gagaAgGrid.addRowData(gridOptionsSectionGbList, data, "sectionVal");
	});

	// 할인구간 선택 시 기본 조건 변경
	$("#moreBetterForm input[name=sectionGb]").bind('click change', function () {
		var sectionGbValue = $(this).val();
		var dcWayValue = $('input:radio[name="dcWay"]:checked').val();
		var loopRowData = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

		/*if (loopRowData.length == 0) {
			mcxDialog.alert('ROW 데이터가 없습니다.');
			return;
		}*/
		if(loopRowData.length > 0) {
			for (i = 0; i < loopRowData.length; i++) {
				loopRowData[i].sectionGb = sectionGbValue;
				loopRowData[i].sectionVal = "";
				loopRowData[i].dcWay = dcWayValue;
				loopRowData[i].dcVal = "";
			}
			gridOptionsSectionGbList.api.setRowData(loopRowData);
		}
	});

	// 할인구분 선택 시 기본 조건 변경
	$("#moreBetterForm input[name=dcWay]").bind('click change', function () {
		var sectionGbValue = $('input:radio[name="sectionGb"]:checked').val();
		var dcWayValue = $(this).val();
		var loopRowData = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

		/*if (loopRowData.length == 0) {
			mcxDialog.alert('ROW 데이터가 없습니다.');
			return;
		}*/
		if(loopRowData.length > 0) {
			for (i = 0; i < loopRowData.length; i++) {
				loopRowData[i].sectionGb = sectionGbValue;
				loopRowData[i].sectionVal = "";
				loopRowData[i].dcWay = dcWayValue;
				loopRowData[i].dcVal = "";
			}
			gridOptionsSectionGbList.api.setRowData(loopRowData);
		}
	});

	// 수정 버튼 클릭시
	$('#btnMorebetterUpdate').on('click', function() {
		// validation
		if (!gagajf.validation('#moreBetterForm'))
			return false;

		// 기간체크
		if(!checkDateValidation()){
			return false;
		}
		// 행사기간 확인
		/*let fromDate = $('#moreBetterForm input[name=tmtbStdt]').val();
		let toDate = $('#moreBetterForm input[name=tmtbEddt]').val();

		if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
			mcxDialog.alert("행사 기간 시작일자와 종료일자를 입력하세요.");
			$('#moreBetterForm input[name=tmtbStdt]').focus();
			return false;
		}

		if (fromDate > toDate) {
			mcxDialog.alert("시작일자는 종료일자 보다 클 수 없습니다.");
			$('#moreBetterForm input[name=tmtbStdt]').focus();
			return false;
		}*/

		// disabled 값 넘겨주기
		$('#moreBetterForm input[name=tmtbSq]').val($('#moreBetterForm input[name=disTmtbSq]').val());
		$('#moreBetterForm input[name=tmtbStat]').val($('input:radio[name="disTmtbStat"]:checked').val());

		mcxDialog.confirm('수정하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var compAllData = gagaAgGrid.getAllRowData(gridOptionsFGCompanyList);	//selectedRowData
				var brandAllData = gagaAgGrid.getAllRowData(gridOptionsFGBrandList);
				var applyAllData = gagaAgGrid.getAllRowData(gridOptionsFGApplyGoodsList);
				var exceptAllData = gagaAgGrid.getAllRowData(gridOptionsFGExceptGoodsList);
				var burdenAllData = gagaAgGrid.getAllRowData(gridOptionsApplyBurdenList);
				var sectionGbAllData = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

				var jsonSupplyCompData = JSON.stringify(compAllData);
				$('#moreBetterForm input[name=supplyCompList]').val(jsonSupplyCompData);
				var jsonBrandData = JSON.stringify(brandAllData);
				$('#moreBetterForm input[name=brandList]').val(jsonBrandData);
				var jsonApplyData = JSON.stringify(applyAllData);
				$('#moreBetterForm input[name=applyGoodsList]').val(jsonApplyData);
				var jsonExceptData = JSON.stringify(exceptAllData);
				$('#moreBetterForm input[name=exceptGoodsList]').val(jsonExceptData);
				var jsonSectionGbData = JSON.stringify(sectionGbAllData);
				$('#moreBetterForm input[name=sectionGbList]').val(jsonSectionGbData);
				var jsonBurdenData = JSON.stringify(burdenAllData);
				$('#moreBetterForm input[name=burdenList]').val(jsonBurdenData);

				var jsonData = JSON.stringify($('#moreBetterForm').serializeObject());
				gagajf.ajaxJsonSubmit($('#moreBetterForm').prop('action'), jsonData, function() {
					fnMorebetterFormClose();
					$('#btnInit').trigger('click');
					$('#btnSearch').trigger('click');
				});
			}
		});
	});

	// 목록 버튼 클릭
	$("#btnSearchList").on("click", function() {
		uifnPopupClose('popupMorebetterReg');
	});

	// 진행 버튼 클릭
	$("#btnChangeStatIng").on("click", function() {
		// fnCheckData();
		// 각 ag-grid list 수량
		let allSupplyCompData = gagaAgGrid.getAllRowData(gridOptionsFGCompanyList);
		let allBrandData = gagaAgGrid.getAllRowData(gridOptionsFGBrandList);
		let allApplyGoodsData = gagaAgGrid.getAllRowData(gridOptionsFGApplyGoodsList);
		let allExceptGoodsData = gagaAgGrid.getAllRowData(gridOptionsFGExceptGoodsList);
		let allApplyBurdenData = gagaAgGrid.getAllRowData(gridOptionsApplyBurdenList);
		let allSectionGbData = gagaAgGrid.getAllRowData(gridOptionsSectionGbList);

		if(allSectionGbData.length < 1){
			mcxDialog.alert("할인구간을 설정해주세요.");
			return false;
		}

		// 기간체크
		if(!checkDateValidation()){
			return false;
		}

		// 공급업체+브랜드 상품조회
		var multiSupplyCompCd = [];
		$.each(allSupplyCompData, function(idx, item) {
			multiSupplyCompCd.push(item.supplyCompCd);
		});

		var multiBrand = [];
		$.each(allBrandData, function(idx, item) {
			multiBrand.push(item.brandCd);
		});

		var multiApplyGoods = [];
		$.each(allApplyGoodsData, function(idx, item) {
			multiApplyGoods.push(item.goodsCd);
		});

		var multiExceptGoods = [];
		$.each(allExceptGoodsData, function(idx, item) {
			multiExceptGoods.push(item.goodsCd);
		});

		/*var data = {
			mode : $('#moreBetterForm input[name=mode]').val()
			, tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
			, tmtbNm : $('#moreBetterForm input[name=tmtbNm]').val()
			, tmtbStat : "G232_11"				// 진행
			, tmtbStdt : $('#moreBetterForm input[name=tmtbStdt]').val()
			, tmtbEddt : $('#moreBetterForm input[name=tmtbEddt]').val()
			, sectionGb : $('input:radio[name="sectionGb"]:checked').val()
			, applyGb : $('input:radio[name="sectionGb"]:checked').val()
			, dcWay : $('input:radio[name="dcWay"]:checked').val()
			, supplyCompList : allSupplyCompData
			, brandList : allBrandData
			, applyGoodsList : allApplyGoodsData
			, exceptGoodsList : allExceptGoodsData
			, burdenList : allApplyBurdenData
			, sectionGbList : allSectionGbData
			, multiSupplyCompCd : multiSupplyCompCd
			, multiBrand : multiBrand
			, multiApplyGoods : multiApplyGoods
			, multiExceptGoods : multiExceptGoods
		};

		var jsonData = JSON.stringify(data);
		 */

		mcxDialog.confirmC("프로모션을 진행하시겠습니까?<br/>진행 후에는 수정이 제한될 수 있습니다.", {
			btn: confirmBtnText,
			btnClick: function(index) {
				if(index == 1) {
					let data = {
						mode : $('#moreBetterForm input[name=mode]').val()
						, tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
						, tmtbNm : $('#moreBetterForm input[name=tmtbNm]').val()
						, tmtbStat : "G232_11"				// 진행
						, tmtbStdt : $('#moreBetterForm input[name=tmtbStdt]').val()
						, tmtbEddt : $('#moreBetterForm input[name=tmtbEddt]').val()
						, sectionGb : $('input:radio[name="sectionGb"]:checked').val()
						, applyGb : $('input:radio[name="sectionGb"]:checked').val()
						, dcWay : $('input:radio[name="dcWay"]:checked').val()
						, supplyCompList : allSupplyCompData
						, brandList : allBrandData
						, applyGoodsList : allApplyGoodsData
						, gridApplyGoodsList : allApplyGoodsData
						, exceptGoodsList : allExceptGoodsData
						, burdenList : allApplyBurdenData
						, sectionGbList : allSectionGbData
						, multiSupplyCompCd : multiSupplyCompCd
						, multiBrand : multiBrand
						, multiApplyGoods : multiApplyGoods
						, multiExceptGoods : multiExceptGoods
					}
					var jsonData = JSON.stringify(data);
					console.log('jsonData::'+jsonData);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/changeStat', jsonData, fnMorebetterChangeStatCollback);
				}
			}
		});
	});

	var fnMorebetterChangeStatCollback = function(result){
		if(result.duplicateYn == "Y"){
			for(let i=0; i<result.duplicateGoodsList.length; i++){
				gagaAgGrid.addRowData(gridOptionsDuplicateGoodsList, {"goodsCd" : result.duplicateGoodsList[i].goodsCd, "goodsNm" : result.duplicateGoodsList[i].goodsNm});
			}
			mcxDialog.alert("다른 다다익선에서 사용중인 상품이 존재합니다.");
			gagaAgGrid.exportToExcel('다다익선 중복상품 목록', gridOptionsDuplicateGoodsList);
			fnMorebetterFormClose();
			$('#btnInit').trigger('click');
			$('#btnSearch').trigger('click');
		}else{
			fnMorebetterFormClose();
			$('#btnInit').trigger('click');
			$('#btnSearch').trigger('click');
		}
	};

	// 중지 버튼 클릭
	$("#btnMorebetterStop").on("click", function() {
		mcxDialog.confirmC("프로모션을 중지하시겠습니까?<br/>중지 후에는 진행으로 복원하실 수 없습니다.", {
			btn: confirmBtnText,
			btnClick: function(index) {
				if(index == 1) {
					let data = { tmtbStat : "G232_12"			// 중지
						, tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					}
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/changeStat', jsonData, fnMorebetterFormClose);
				}
			}
		});
	});

	// 삭제 버튼 클릭
	$("#btnMorebetterDelete").on("click", function() {
		mcxDialog.confirmC("프로모션을 삭제하시겠습니까?<br/>삭제한 프로모션은 복원하실 수 없습니다.", {
			btn: confirmBtnText,
			btnClick: function(index) {
				if(index == 1) {
					let data = { tmtbStat: "G232_14"			// 삭제
						, tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					}
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/changeStat', jsonData, fnMorebetterFormClose);
				}
			}
		});
	});

/*
	// 공급업체 행삭제
	$('#btnDeleteCompany').on('click', function() {
		var selectedData = gridOptionsFGCompanyList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		var removedData = gagaAgGrid.removeRowData(gridOptionsFGCompanyList, false);
		var arrCompanySq = [];
		$.each(selectedData, function(idx, item) {
			arrCompanySq.push(item.tmtbGoodsSq);
		});
		if (removedData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrCompanySq : arrCompanySq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/supplyCompany/delete', jsonData);
				}
			});
		}
	});

	// 브랜드 행삭제
	$('#btnDeleteBrand').on('click', function() {
		var selectedData = gridOptionsFGBrandList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		var removedData = gagaAgGrid.removeRowData(gridOptionsFGBrandList, false);
		var arrBrandSq = [];
		$.each(selectedData, function(idx, item) {
			arrBrandSq.push(item.tmtbGoodsSq);
		});
		if (removedData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrBrandSq : arrBrandSq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/brand/delete', jsonData);
				}
			});
		}
	});

	// 적용상품 행삭제
	$('#btnDeleteApplyGoods').on('click', function() {
		var selectedData = gridOptionsFGApplyGoodsList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		var removedData = gagaAgGrid.removeRowData(gridOptionsFGApplyGoodsList, false);
		var arrApplyGoodsSq = [];
		$.each(selectedData, function(idx, item) {
			arrApplyGoodsSq.push(item.tmtbGoodsSq);
		});
		if (removedData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrApplyGoodsSq : arrApplyGoodsSq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/applyGoods/delete', jsonData);
				}
			});
		}
	});

	// 제외상품 행삭제
	$('#btnDeleteExtGoods').on('click', function() {
		var selectedData = gridOptionsFGExceptGoodsList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		var removedData = gagaAgGrid.removeRowData(gridOptionsFGExceptGoodsList, false);
		var arrExceptGoodsSq = [];
		$.each(selectedData, function(idx, item) {
			arrExceptGoodsSq.push(item.tmtbGoodsSq);
		});
		if (removedData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrExceptGoodsSq : arrExceptGoodsSq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/exceptGoods/delete', jsonData);
				}
			});
		}
	});

	// 업체분담율 행삭제
	$('#btnDelApplyBurden').on('click', function() {
		var selectedData = gridOptionsApplyBurdenList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		var removedData = gagaAgGrid.removeRowData(gridOptionsApplyBurdenList, false);
		var arrBurdenSq = [];
		$.each(selectedData, function(idx, item) {
			arrBurdenSq.push(item.tmtbBurdenSq);
		});
		if (removedData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrBurdenSq : arrBurdenSq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/burden/delete', jsonData);
				}
			});
		}
	});
*/

	// 구간할인 행삭제
	/*$('#btnDelSectionRow').on('click', function() {
		var selectedData = gridOptionsSectionGbList.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		var removedData = gagaAgGrid.removeRowData(gridOptionsSectionGbList, false);

		var arrSectionSq = [];

		$.each(selectedData, function(idx, item) {
			arrSectionSq.push(item.tmtbSectionSq);
		});

		if (removedData.length > 0) {

			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var data = { arrSectionSq : arrSectionSq
						,tmtbSq : $('#moreBetterForm input[name=disTmtbSq]').val()
					};

					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/marketing/morebetter/sectionVal/delete', jsonData);
				}
			});
		}
	});*/

</script>
</html>
