
/* ##############################################################
	설  명 : [Modal]멤버십 상품등록 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let membershipProcedureModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#membershipProcedureModal').remove();
        $('body').append( this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        $('#membershipProcedureModal .btnCancle').on("click", function(){
            membershipProcedureModal.close();
        });

        $('#membershipProcedureModal .btnSave').on("click", function(){
            membershipProcedureModal.save("I");
        });
        $('#membershipProcedureModal .membership_product_table').on("change",'input[name="price"]', function(){
            let price = $(this).val();
            $(this).parent().siblings('td[name="amount"]').text(Math.round(price/1.1).toLocaleString());
            $(this).parent().siblings('td[name="vat"]').text((price-Math.round(price/1.1)).toLocaleString());
        });
        $('#membershipProcedureModal .membership_product_table').on("change",'input[name="addPrice"]', function(){
            let price = parseInt($(this).parent().parent().find('.input_box input').eq(1).val(),0);
            if(!price){
                modalEvent.warning('오류','멤버십 상품금액을 입력해주세요.');
                return;
            }
            let addPrice=parseInt($(this).val(),0);
            if(price){
                $(this).parent().siblings('td[name="totalAmount"]').text((price+addPrice).toLocaleString());
            }else{
                $(this).parent().siblings('td[name="totalAmount"]').text(addPrice.toLocaleString());
            }
        });

        $('#membershipProcedureModal [name=price]').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });

        $('#membershipProcedureModal [name=addPrice]').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });
    },
    /* 데이터 선택 */
    setSelect:function(selectNumber) {
        let checkedData = dataList[selectNumber];
        if(dataList==null||checkedData==undefined){
            return ;
        }

        if( membershipProcedureModal.callback )  {
            membershipProcedureModal.callback(checkedData);
        }
        membershipProcedureModal.close();
    },
    //저장
    save:function(state) {
        /*공급가 = 총금액/1.1
        vat= 총금액 -공급가
        *소수점 반올림(공통)
        비급여항목은 부가세 X*/
        let membershipProductRow   = {'data':[]};
        let productTr = $('#membershipProcedureModal .membership_product_table tbody').children('tr');
        let productTempArray = new Array();
        for(let i=0 ; i < productTr.length; i++){
            let insuranceType  = 'N';
            let amount = productTr.eq(i).find('input[name="price"]').val()

            let orderNumber       = productTr.eq(i).find('td[name="modalMembershipProcedureOrderNumber"]').text();
            let productName 	  = productTr.eq(i).find('input[name="membershipName"]').val();
            let price    = Math.round(amount/1.1)
            let vat      = amount-price
            let additionalAmount  = productTr.eq(i).find('input[name="addPrice"]').val();


            if(true != fn_emptyCheck(productName)){
                modalEvent.warning("등록", "멤버십 상품명이 없습니다.");
                return;
            }
            if(true != fn_emptyCheck(amount)){
                modalEvent.warning("등록", "멤버십 상품 금액이 없습니다.");
                return;
            }
            let arr_sub = {}
            arr_sub.productName       = productName;
            arr_sub.price 	          = price;
            arr_sub.vat 	          = vat;
            arr_sub.additionalAmount  = additionalAmount;
            productTempArray.push(arr_sub);

            membershipProductRow.data = productTempArray;
            console.log(arr_sub);

        }

        modalEvent.info("등록", "멤버십상품을 등록하시겠습니까?", function(){
            let formData = new FormData();
            formData.append("menuClass", menuClass);
            formData.append("membershipProductRow",JSON.stringify(membershipProductRow));

            $.ajax({
                url: encodeURI('/webmembership/insertMembershipProcedure.do'),
                data: formData,
                dataType: "json",
                processData: false,
                contentType: false,
                type: 'POST',
                async: true,
                success: function(data){
                    if('0'==data.msgCode){
                        modalEvent.success("등록 성공", data.msgDesc, function(){
                            if( membershipProcedureModal.callback )  {
                                membershipProcedureModal.callback();
                            }
                            membershipProcedureModal.close();
                        });
                    }
                    else{
                        modalEvent.danger("등록 오류", data.msgDesc);
                    }
                },
                error : function(xhr, status, error) {
                    modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
                },
                beforeSend:function(){

                },
                complete:function(){

                }
            });
        });
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        // 초기화 후 열기
        membershipProcedureModal.init();

        //콜백함수 지정.
        membershipProcedureModal.callback = callback;
        membershipProcedureModal.reqParam = reqParam;
        membershipProcedureModal.dataList = null;

        fn_insertModal_membershipProcedureAddRow();
        setTimeout(function(){
            $('#membershipProcedureModal').modal('show')
        }, 200);
    },
    /*
     * 팝업 닫기
     */
    close:function() {
        $('#membershipProcedureModal').modal('hide');

		setTimeout(function(){
			$('#membershipProcedureModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal membership_registration_modal fade" id="membershipProcedureModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<p class="title">멤버십 상품등록</p>
					</div>
		
					<div class="modal-body">
						<div class="table_box">
							<table class="membership_product_table">
								<thead>
									<tr>
										<th>번호</th>
										<th>멤버십 상품명</th>
										<th>멤버십 상품금액</th>
										<th>공급가</th>
										<th>VAT</th>
										<th>멤버십 추가지급액</th>
										<th>멤버십 총지급액</th>
										<th></th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>
					<div class="modal-footer">
						<div class="btn_box">
							<button type="button" class="cancel_btn btnCancle">취소</button>
							<button type="button" class="registration_bth btnSave">등록</button>
						</div>
					</div>
				</div>
			</div>
		</div>
    `
};
/****************************************************************************
 * row 추가 이벤트
 ****************************************************************************/
function fn_insertModal_membershipProcedureAddRow(type){
    let addBtnType = type === 'a'?'none':'block'
    let subtractBtnType=type !== 'a'?'none':'block'
    let parentTable = $('#membershipProcedureModal .membership_product_table tbody');

    let liNum = parentTable.find('tr').length;

    let addRowHtml = '';
    addRowHtml += '<tr>';
    addRowHtml += '	    <td name="modalMembershipProcedureOrderNumber">'+(liNum+1)+'</td>';
    addRowHtml += '	    <td class="input_box">';
    addRowHtml += '         <input type="text" name="membershipName" placeholder="멤버십 상품명 입력"/>';
    addRowHtml += '	    </td>';
    addRowHtml += '     <td class="input_box">';
    addRowHtml += '         <input type="text" name="price" placeholder="상품 금액 입력"/>';
    addRowHtml += '	    </td>';
    addRowHtml += '	    <td name="amount">-</td>';
    addRowHtml += '	    <td name="vat">-</td>';
    addRowHtml += '     <td class="input_box">';
    addRowHtml += '         <input type="text" name="addPrice" placeholder="멤버십 추가금액 입력"/>';
    addRowHtml += '	    </td>';
    addRowHtml += '	    <td name="totalAmount">-</td>';
    addRowHtml += '	    <td class="button_box">';
    addRowHtml += '			    <button style="display:'+addBtnType+'" onclick="javascript:fn_insertModal_membershipProcedureAddRow(\'a\');"><img src="/image/web/add.svg" alt="추가"></button>';
    addRowHtml += '			    <button style="display:'+subtractBtnType+'" onclick="javascript:fn_insertModal_membershipProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
    addRowHtml += '     </td>';
    addRowHtml += ' </tr>';

    parentTable.append(addRowHtml).trigger("create");

    $('#membershipProcedureModal [name=price]').on('input', function() {
        // 입력된 키가 숫자가 아닌 경우 입력을 막음
        this.value = this.value.replace(/\D/g, '');
    });

    $('#membershipProcedureModal [name=addPrice]').on('input', function() {
        // 입력된 키가 숫자가 아닌 경우 입력을 막음
        this.value = this.value.replace(/\D/g, '');
    });

    fn_insertModal_membershipProcedureRefreshOrderNumber(parentTable);
}


/****************************************************************************
 * row 삭제 이벤트
 ****************************************************************************/
function fn_insertModal_membershipProcedureRemoveRow(param){
    let parentTable = $(param).closest('table').find("tbody");
    let liLength = parentTable.children('tr').length;

    if(1<liLength){
        let liNum = $(param).closest('tr').prevAll().length;
        parentTable.children('tr').eq(liNum).remove();

        fn_insertModal_membershipProcedureRefreshOrderNumber(parentTable);
    }
    else{
        modalEvent.warning("입력 오류", "더 이상 삭제할 수 없습니다.");
    }
}


/****************************************************************************
 * 전체 row 정렬순번 변경
 ****************************************************************************/
function fn_insertModal_membershipProcedureRefreshOrderNumber(param){
    $(param).find("tr").each(function(index){
        $(this).find('td').eq(0).text(index+1);
    });

    // row 추가/삭제 버튼 처리
    // $(param).find(".add_box").hide();
    // $(param).find('.subtract_box').show();
    // $(param).find("tr:first").find("td:last").prev().find(".subtract_box").hide();
    // $(param).find("tr:first").find("td:last").prev().find(".add_box").show();
}
