
/* ##############################################################
	설  명 : [Modal]고객 동의서 입력 팝업
	작성일 : 2024. 03. 14.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 03. 14.	NTsoft 	 최초 생성
*/
let	medicalSelectModal = {
    callback: null,
    reqParam: null,
    dataList: null,
    prtContent: null,
    initBody: null,
    /* 모달 초기화 작업 */
    init: function () {
        $('#medicalSelectModal').remove();
        $('body').append(this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent: function () {
        $('#medicalSelectModal .btnCancle').on("click", function () {
            medicalSelectModal.close();
        });

        $('#medicalSelectModal .btnSave').on("click", function () {
            medicalSelectModal.save();
        });

        $('#medicalSelectModal .btnPrint').on("click", function () {
            medicalSelectModal.print();
        });
    },
    /* 데이터 선택 */
    setSelect: function (selectNumber) {
        let checkedData = dataList[selectNumber];
        if (dataList == null || checkedData == undefined) {
            return;
        }

        if (medicalSelectModal.callback) {
            medicalSelectModal.callback(checkedData);
        }
        medicalSelectModal.close();
    },
    // 출력
    print: function (param) {

        // iframe = Print 사용
        let mywindow = window.open('', 'PRINT', 'height=1200,width=1600');

        // 스타일 적용 방법 1
        mywindow.document.write('<th:block layout:fragment="css"> ');
        mywindow.document.write('<link rel="stylesheet" href="/css/web/modal_customer_sub_sisul_print.css" type="text/css" />');
        mywindow.document.write('</th:block> ');

        mywindow.document.write('<html><head><title>' + document.title + '</title>');
        mywindow.document.write('</head><body>');
        mywindow.document.write('<div id="page">');
        //mywindow.document.write('<h1>' + document.title  + '</h1>');
        mywindow.document.write(document.getElementById('modal-body').innerHTML);
        mywindow.document.write('</div>');
        mywindow.document.write('</body></html>');

        mywindow.document.close(); // necessary for IE >= 10

        // 필요 - style loading is async
        setTimeout(function () {
            // 새 창에서 체크박스 상태를 업데이트하는 스크립트 추가
            let script = mywindow.document.createElement('script');
            let visitType = $('input[name="sortation"]:checked').attr('id');
            script.innerHTML = `
                document.getElementById('${visitType}').checked = true;
            `;
            mywindow.document.body.appendChild(script);

            // 인쇄 시작
            mywindow.print();
        }, 500);
        //mywindow.close();
    },
    // 웹페이지 body 내용을 프린트하고 싶은 내용으로 교체
    beforePrint: function () {
        initBody = document.body.innerHTML;
        document.body.innerHTML = prtContent.innerHTML;
    },
    // 프린트 후, 웹페이지 body 복구
    afterPrint: function () {
        document.body.innerHTML = initBody;
    },
    search: function () {
        let muUserConsultingChartId = medicalSelectModal.reqParam.muUserConsultingChartId;

        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("muUserMedicalChartId", muUserMedicalChartId);
        formData.append("muUserId", muUserId);

        $.ajax({
            url: encodeURI('/webusermedicalchart/selectUserMedicalChart.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function (data) {
                if (data.msgCode === '0') {
                    let userBirthDay = fn_sisulUserBirthAndAge(data.rows[0].birthday,data.rows[0].gender);
                    let treatmentProcedureName = data.rows[0].treatmentName+'-'+data.rows[0].treatmentProcedureName;
                    let firstVisitYn = data.rows[0].visitYn==='N'?'firstVisit':'returnVisit';

                    console.log(firstVisitYn);

                    $("#medicalSelectModal #"+firstVisitYn).prop('checked','true');
                    $("#medicalSelectModal #chartNumber").text(data.rows[0].chartNumber);
                    $("#medicalSelectModal #userName").text(data.rows[0].userName);
                    $("#medicalSelectModal #userBirthday").text(userBirthDay);
                    $("#medicalSelectModal #userNationality").text(data.rows[0].nationality);
                    $("#medicalSelectModal #userPhoneNumber").text(data.rows[0].phoneNumber);
                    $("#medicalSelectModal #userEtc").text(data.rows[0].etc);
                    $("#medicalSelectModal #writeDate").text(data.rows[0].writeDate);
                    $("#medicalSelectModal #writeMemberName").text(data.rows[0].writeMemberName);
                    $("#medicalSelectModal #treatmentProcedureName").text(treatmentProcedureName);
                    $("#medicalSelectModal #reserveMemberName").text(data.rows[0].reserveMemberName);
                    $("#medicalSelectModal #reserveDateTime").text(data.rows[0].reserveDate+', '+data.rows[0].reserveTime);
                    $("#medicalSelectModal #receptionDateTime").text(data.rows[0].receptionDateTime);
                    $("#medicalSelectModal #userMembership").text(data.rows[0].membershipBalance.toLocaleString()+'원');
                    $("#medicalSelectModal #content").text(data.rows[0].content);
                } else {
                    modalEvent.danger("조회 오류", data.msgDesc);
                }

            },
            error: function (xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
            },
            complete: function () {
            }
        });
    },
    //저장
    save: function () {

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

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

        medicalSelectModal.search();
        /*
        // 서명
        let canvas = $('#medicalSelectModal .print_form:nth-child(1) .signPad canvas')[0];
        let sign = new SignaturePad(canvas, {
            minWidth: 1,
            maxWidth: 1,
            penColor: "rgb(0, 0, 0)"
        });
        resizeCanvas(canvas);*/

        setTimeout(function () {
            $('#medicalSelectModal').modal('show')
        }, 200);

    },
    /*
     * 팝업 닫기
     */
    close: function () {
        $('#medicalSelectModal').modal('hide');

		setTimeout(function(){
			$('#medicalSelectModal').remove();
		},500);
    },
    HtmlTemplate :`
        <div class="modal print_modal fade" id="medicalSelectModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body" id="modal-body">
                        <div class="print">
                            <div class="print_top">
                                <p class="first">시술차트</p>
                                <p>
                                    작성일자 :
                                    <span class="first" id="writeDate"></span>
                                    담당자 :
                                    <span id="writeMemberName"></span>
                                </p>
                            </div>
                            <div class="print_btm">
                                <div>
                                    <ul>
                                        <li>
                                            <label>성명</label>
                                            <p id="userName">박고객</p>
                                        </li>
                                        <li>
                                            <label>생년월일</label>
                                            <p id="userBirthday"></p>
                                        </li>
                                        <li>
                                            <label>국적</label>
                                            <p id="userNationality"></p>
                                        </li>
                                        <li>
                                            <label>연락처</label>
                                            <p id="userPhoneNumber"></p>
                                        </li>
                                        <li>
                                            <label>멤버십</label>
                                            <p id="userMembership"></p>
                                        </li>
                                    </ul>
                                    <ul>
                                        <li>
                                            <label>방문 구분</label>
                                            <div class="input_box">
                                                <div>
                                                    <input type="radio" name="sortation" id="firstVisit" readonly/>
                                                    <label for="firstVisit">초진</label>
                                                </div>
                                                <div>
                                                    <input type="radio" name="sortation" id="returnVisit" readonly/>
                                                    <label for="returnVisit">재진</label>
                                                </div>
                                            </div>
                                        </li>
                                        <li>
                                            <label>예약</label>
                                            <p id="reserveDateTime"><!--2024.01.01 13:00--></p>
                                        </li>
                                        <li>
                                            <label>접수</label>
                                            <p id="receptionDateTime"><!--2024.01.01 13:00--></p>
                                        </li>
                                        <li>
                                            <label>예약구분</label>
                                            <p id="treatmentProcedureName"><!--쁘띠-스컬트라--></p>
                                        </li>
                                        <li>
                                            <label>닥터/상담</label>
                                            <p id="reserveMemberName"><!--금쁘띠--></p>
                                        </li>
                                    </ul>
                                    <div class="note">
                                        <label>고객 특이사항</label>
                                        <p id="userEtc"><!--특정 약물 알러지 특정 약물 알러지특정 약물 알러지특정 약물 알러지특정 약물 알러지특정 약물 알러지특정 약물 알러지특정 약물 알러지--></p>
                                    </div>
                                </div>
                                <p>시술내용</p>
                                <div class="last" id="content">
                                    <!--상담내용-->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="btn_box">
                            <button type="button" class="cancel_btn btnCancle">취소</button>
                            <button type="button" class="save_bth btnPrint">인쇄</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>`
};
function fn_sisulUserBirthAndAge(birthday, gender) {
    // 오늘 날짜
    let today = new Date();
    // 생일
    let birthDate = new Date(birthday);

    // 나이 계산
    let age = today.getFullYear() - birthDate.getFullYear();
    let monthDifference = today.getMonth() - birthDate.getMonth();
    let dayDifference = today.getDate() - birthDate.getDate();

    // 만 나이 조정
    if (monthDifference < 0 || (monthDifference === 0 && dayDifference < 0)) {
        age--;
    }

    // 원하는 형식의 문자열 만들기
    let formattedDate = birthday.replace(/-/g, '.');
    return  formattedDate + ' (' + gender + ', ' + age + '세)';

}
