<!-- 배송지변경 팝업 -->
<div class="modal-header">
	<h5 class="modal-title" id="exchangeLabel">교환상품 옵션 변경</h5>
</div>
<div class="modal-body">
	<div class="pop_cont">
		<form class="form_wrap">
			<div class="select_option_area">
				<h6>옵션 변경 상품 선택</h6>
				<div class="form_field">
					<div th:if="${exchangeOptionInfo}" th:each="oneData, status : ${exchangeOptionInfo}">
						<input th:id="|chk_exchange_item_${oneData.ordDtlItemSq}|" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}" type="checkbox" onclick="fnSelectOptionChange(this);"><label th:for="|chk_exchange_item_${oneData.ordDtlItemSq}|"><span th:text="|${oneData.itemNm} / ${oneData.colorNm} / ${oneData.optCd2}|"></span></label>
					</div>
				</div>
			</div>
			<div class="modify_option_area" id="modifyOptionArea" style="display:none">
				<th:block th:if="${exchangeOptionInfo}" th:each="oneData, status : ${exchangeOptionInfo}">
					<th:block th:if="${chgQty > 0}" th:each="num, index  : ${#numbers.sequence(1,chgQty)}">
						<div class="modify_box" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, num=${num}" style="display:none">
							<div class="name_blk" th:text="|${oneData.itemNm} / ${oneData.colorNm}|"></div>
							<div class="select_blk">
								<!-- 옵션교환 라디오 형태 -->
								<div class="sel_radio" th:if="${oneData.selfGoodsYn == 'Y'}">
									<input type="hidden" name="chgOptCd2" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, itemNm=${oneData.itemNm}, colorNm=${oneData.colorNm}, orgOptCd2=${oneData.optCd2}, goodsType=${oneData.goodsType}, num=${num}">
									<div th:class="|form_field ${oneData.ordDtlItemSq}|">
										<div th:if="${oneData.optCd2Arr.length > 0}" th:each="option, idx : ${oneData.optCd2Arr}">
											<input type="radio" th:name="|${oneData.ordDtlItemSq}_${num}|" th:id="|${oneData.ordDtlItemSq}_${option}_${num}|" th:value="${option}" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, num=${num}" th:disabled="${#numbers.formatInteger(oneData.currStockQtyArr[idx.index], 0)} <= 0 or ${oneData.soldoutYnArr[idx.index] == 'Y'}" onclick="fnRadioOption(this);">
											<label th:for="|${oneData.ordDtlItemSq}_${option}_${num}|"><span th:text="${option}"></span></label>
										</div>
									</div>
								</div>
								<!-- //옵션교환 라디오 형태 -->
								<!-- 옵션교환 셀렉트박스 형태 -->
								<div class="sel_select" th:unless="${oneData.selfGoodsYn == 'Y'}">
									<div class="form_field">
										<div class="select_custom exchange_option">
											<div class="combo">
												<input type="hidden" name="chgOptCd2" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, itemNm=${oneData.itemNm}, colorNm=${oneData.colorNm}, orgOptCd2=${oneData.optCd2}, goodsType=${oneData.goodsType}, num=${num}">
												<div class="select">옵션 선택</div>
												<ul class="list">
													<!-- 선택처리 class="selected" / 선택불가 aria-disabled="true" / 품절표기 data-soldout="true" 추가  -->
													<li class="selected" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, num=${num}, optCd2=''" onclick="fnSelectOption(this);">옵션 선택</li>
													<th:block th:each="option, idx : ${oneData.optCd2Arr}">
														<li th:if="${oneData.optCd2Arr.length} > 0 and (${#numbers.formatInteger(oneData.currStockQtyArr[idx.index],0)} <= 0 or ${oneData.soldoutYnArr[idx.index]} == 'Y')" th:text="${option}" aria-disabled="true" data-soldout="true" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, num=${num}, optCd2=''" onclick="fnSelectOption(this);"></li>
														<li th:if="${oneData.optCd2Arr.length} > 0 and ${#numbers.formatInteger(oneData.currStockQtyArr[idx.index],0)} > 0 and ${oneData.soldoutYnArr[idx.index]} == 'N'" th:text="${option}" th:attr="ordDtlItemSq=${oneData.ordDtlItemSq}, num=${num}, optCd2=${option}" onclick="fnSelectOption(this);"></li>
													</th:block>
												</ul>
											</div>
										</div>
									</div>
								</div>
								<!-- //옵션교환 셀렉트박스 형태 -->
							</div>
							<div class="allcheck_blk" th:if="${num} == 1">
								<div class="form_field">
									<div>
										<input th:id="|${oneData.ordDtlItemSq}_checkAll|" name="chk_exchange_all1" type="checkbox" checked="" onclick="fnSelectOptionChange();"><label th:for="|${oneData.ordDtlItemSq}_checkAll|"><span>선택 옵션으로 전체 교환</span></label>
									</div>
								</div>
							</div>
						</div>
					</th:block>
				</th:block>
			</div>
		</form>
	</div>
</div>
<div class="modal-footer">
	<button type="button" id="" class="btn btn_dark" onclick="fnSaveOption();"><span>옵션 저장</span></button>
</div>
<script th:inline="javascript">
	let exchangeOptionInfo = [[${exchangeOptionInfo}]];
	let oneData = [[${oneData}]];
	let chgQty = [[${chgQty}]];
	let checkedOrdDtlItemSqArr = [];

	$(document).ready( function() {
		// 셀렉트박스 활성화
		$('#exchangePop .select_custom.exchange_option').each(function() {
			new sCombo($(this));
		});
	});

	// 구성상품 선택 및 전체 적용 클릭 이벤트
	var fnSelectOptionChange = function() {
		checkedOrdDtlItemSqArr = [];
		let cnt = 0;
		
		// 체크 수량 조회
		$.each($('.select_option_area .form_field input:checkbox'), function(idx, item) {
			if ($(item).is(':checked')) {
				checkedOrdDtlItemSqArr.push($(item).attr('ordDtlItemSq'));
				cnt++;
			}
		});

		// 옵션변경영역 처리
		if (cnt > 0) {
			$('#modifyOptionArea').css('display', '');
		} else {
			$('#modifyOptionArea').css('display', 'none');
		}

		$.each($('.modify_box'), function(idx, item) {
			let ordDtlItemSq = $(item).attr('ordDtlItemSq');
			let num = $(item).attr('num');
			let id = '#' + ordDtlItemSq + '_checkAll';

			if (checkedOrdDtlItemSqArr.includes(ordDtlItemSq)) {
				if (num == 1) {
					$(item).css('display', '');

					if (oneData.selfGoodsYn == 'Y') {
						$.each($(item).find('input:radio'), function (index, radio) {
							if ($(radio).is(':checked')) {
								$(radio).click();
							}
						});
					} else {
						$.each($(item).find('li'), function (index, radio) {
							if ($(radio).hasClass('selected')) {
								$(radio).click();
							}
						});
					}
				} else if ($(id).is(':checked')) {
					$(item).css('display', 'none');
				} else {
					$(item).css('display', '');
				}
			} else {
				$(item).css('display', 'none');
			}
		});

		fnChangeCss();
	}

	// 라디오 클릭 이벤트
	var fnRadioOption = function(param) {
		let ordDtlItemSq = $(param).attr('ordDtlItemSq');
		let num = $(param).attr('num');
		let optCd2 = $(param).val();
		let checkAllId = '#' + ordDtlItemSq + '_checkAll';
		let radioId = '.' + ordDtlItemSq + ' input:radio';

		$(param).parent().parent().parent().find('input[name=chgOptCd2]').val(optCd2);

		if (num == 1 && $(checkAllId).is(':checked')) {
			$.each($(radioId), function(idx, item) {
				if ($(item).attr('num') != 1 && optCd2 == $(item).val()) {
					$(item).click();
				}
			});
		}
	}

	// 셀렉트박스 클릭 이벤트
	var fnSelectOption = function(param) {
		let ordDtlItemSq = $(param).attr('ordDtlItemSq');
		let num = $(param).attr('num');
		let optCd2 = $(param).attr('optCd2');
		let checkAllId = '#' + ordDtlItemSq + '_checkAll';

		$(param).parent().parent().find('input[name=chgOptCd2]').val(optCd2);

		if (num == 1 && $(checkAllId).is(':checked')) {
			$.each($('.exchange_option li'), function(idx, item) {
				if ($(item).attr('num') != 1 && optCd2 == $(item).attr('optCd2')) {
					$(item).click();
				}
			});
		}
	}
	
	// 옵션 저장 버튼 클릭 이벤트
	var fnSaveOption = function() {
		// 옵션 선택 여부 확인
		if (checkedOrdDtlItemSqArr.length <= 0) {
			mcxDialog.alert('교환 옵션을 선택해주세요.');
			return false;
		}

		// 변경 옵션 처리
		let dataArr = [];
		let ordDtlItemSq = 0;
		let colorNm = '';
		let itemNm = '';
		let goodsType = '';
		let chgOptCd2Arr = [];
		let selectOptionCheck = true;

		$.each($('input[name=chgOptCd2]'), function(idx, item) {
			let chgOrdDtlItemSq = $(item).attr('ordDtlItemSq');
			colorNm = $(item).attr('colorNm');
			itemNm = $(item).attr('itemNm');
			goodsType = $(item).attr('goodsType');
			let changeYn = checkedOrdDtlItemSqArr.includes(chgOrdDtlItemSq)
			let chgOptCd2 = changeYn ? $(item).val() : $(item).attr('orgOptCd2');
			let chgOptCd2Obj = {};
			chgOptCd2Obj.chgOptCd2 = chgOptCd2;
			chgOptCd2Obj.qty = 1;

			if (ordDtlItemSq != Number(chgOrdDtlItemSq)) {
				if (idx > 0) {
					let data = {};
					data.ordDtlNo = oneData.ordDtlNo;
					data.ordDtlItemSq = ordDtlItemSq;
					data.chgQty = chgQty;
					data.colorNm = colorNm;
					data.itemNm = itemNm;
					data.goodsType = goodsType;
					data.chgOptCd2Arr = fnOptionCount(chgOptCd2Arr);
					dataArr.push(data);
				}

				ordDtlItemSq = chgOrdDtlItemSq;
				chgOptCd2Arr = [];
			}

			chgOptCd2Arr.push(chgOptCd2Obj);

			

			// 옵션 선택 여부 설정
			if (changeYn && gagajf.isNull($(item).val())) {
				selectOptionCheck = false;
			}
		});

		// 옵션 선택 여부 체크
		if (!selectOptionCheck) {
			mcxDialog.alert('교환 옵션을 선택해주세요.');
			return false;
		}

		let data = {};
		data.ordDtlNo = oneData.ordDtlNo;
		data.ordDtlItemSq = ordDtlItemSq;
		data.chgQty = chgQty;
		data.colorNm = colorNm;
		data.itemNm = itemNm;
		data.goodsType = goodsType;
		data.chgOptCd2Arr = fnOptionCount(chgOptCd2Arr);
		dataArr.push(data);

		fnChangeOptionCallback(dataArr)

		$('.close-modal').trigger('click');
	}

	// 변경 옵션별 수량 처리
	var fnOptionCount = function(param) {
		var result = [];
		param.reduce(function(res, value) {
			if (!res[value.chgOptCd2]) {
				res[value.chgOptCd2] = { chgOptCd2: value.chgOptCd2, qty: 0 };
				result.push(res[value.chgOptCd2])
			}
			res[value.chgOptCd2].qty += value.qty;
			return res;
		}, {});
		
		return result;
	}

	// 옵션 선택 영역 CSS 수정
	var fnChangeCss = function() {
		let index = 0;
		$.each($('.modify_box'), function(idx, item) {
			if ($(item).css('display') == 'block') {
				index++;
				if (index == 1) {
					$(item).css('margin-top', '0');
					$(item).css('padding-top', '0');
					$(item).css('border-top', 'none');
				} else {
					$(item).css('margin-top', '30px');
					$(item).css('padding-top', '30px');
					$(item).css('border-top', '1px dashed #ddd');
				}
			}
		});
	}
</script>
