<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>

<c:set var="prefixName" scope="request">의견제출 상세 정보</c:set>

<!-- inner page html -->
<div class="content-pop" data-doctx="${pageName}">
    <!-- Content -->
    <div class="container flex-grow-1 px-0">
        <div class="card">
            <!-- 입력 영역 -->
            <form name="frmEdit">
                <!-- hidden -->
                <input type="hidden" name="sggCd" data-map="SGG_CD" />
                <input type="hidden" name="taskSeCd" data-map="TASK_SE_CD" />
                <input type="hidden" name="crdnId" data-map="CRDN_ID" />
                <input type="hidden" name="opnnId" data-map="OPNN_ID" />

                <div class="row g-1">
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="crdnYmdTm">단속일시</label>
                        <input is="id-input" type="text" class="form-control w-50" name="crdnYmdTm" data-map="CRDN_YMD_TM" data-fmt-type="dt" readonly />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="vhrno">차량번호</label>
                        <input is="id-input" type="text" class="form-control w-45" name="vhrno" data-map="VHRNO" readonly />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="rtpyrNm">납부자</label>
                        <input is="id-input" type="text" class="form-control w-55" name="rtpyrNm" data-map="RTPYR_NM" readonly />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="rcptNo">접수번호</label>
                        <input is="id-input" type="text" class="form-control w-40" name="rcptNo" data-map="RCPT_NO" />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end required" for="rcptYmd">접수일자</label>
                        <input is="id-input" type="text" class="form-control form-date" name="rcptYmd" data-map="RCPT_YMD"
                            data-fmt-type="day" title="날짜 선택" maxlength="10" required />
                        <button type="button" class="bx bx-lg bx-calendar bg-white" id="btnRcptYmd--${pageName}"></button>
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end required" for="rcptSeCd">접수구분</label>
                        <select is="id-select" class="form-select" name="rcptSeCd" data-map="RCPT_SE_CD" required>
                            <option value="">선택하세요</option>
                            <c:forEach items="${FIM029List}" var="item">
                                <option value="${item.code}">${item.value}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end required" for="sttrNm">성명</label>
                        <input is="id-input" type="text" class="form-control w-35" name="sttrNm" data-map="STTR_NM" required />
                        <button type="button" class="btn btn-sm btn-outline-dark" name="btnSearchPayer" title="납부자 정보 적용">
                            납부자
                        </button>
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="sttrBrdt">생년월일</label>
                        <input is="id-input" type="text" class="form-control w-30" name="sttrBrdt" data-map="STTR_BRDT" placeholder="YYMMDD" />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end required" for="ownrRelCd">소유주관계</label>
                        <select is="id-select" class="form-select" name="ownrRelCd" data-map="OWNR_REL_CD" required>
                            <option value="">선택하세요</option>
                            <c:forEach items="${FIM032List}" var="item">
                                <option value="${item.code}">${item.value}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="sttrAddr">주소</label>
                        <input is="id-input" type="text" class="form-control w-70" name="sttrAddr" data-map="STTR_ADDR" />
                        <input is="id-input" type="text" class="form-control w-px-75" name="sttrZip" data-map="STTR_ZIP" />
                        <button type="button" class="btn btn-sm btn-outline-dark" name="btnSearchAddr" title="주소 검색">
                            검색
                        </button>
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="sttrDaddr">상세주소</label>
                        <input is="id-input" type="text" class="form-control w-85" name="sttrDaddr" data-map="STTR_DADDR" />
                    </div>
                    <div class="col-md-4">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="sttrCttpc">연락처</label>
                        <input is="id-input" type="text" class="form-control w-45" name="sttrCttpc" data-map="STTR_CTTPC" />
                    </div>
                    <div class="col-md-8">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="sttrEml">이메일</label>
                        <input is="id-input" type="text" class="form-control w-40" name="sttrEml" data-map="STTR_EML" />
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end align-top" for="opnnSbmsnCn">의견제출내용</label>
                        <textarea is="id-textarea" type="text" class="form-control w-85" name="opnnSbmsnCn" data-map="OPNN_SBMSN_CN" rows="5" data-maxlengthb="4000"></textarea>
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end required" for="opnnSbmsnSeCd">의견제출구분</label>
                        <select is="id-select" class="form-select" name="opnnSbmsnSeCd" data-map="OPNN_SBMSN_SE_CD" required>
                            <option value="">선택하세요</option>
                            <c:forEach items="${FIM033List}" var="item">
                                <option value="${item.code}">${item.value}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end" for="opnnSbmsnGist">의견제출요지</label>
                        <input is="id-input" type="text" class="form-control w-85" name="opnnSbmsnGist" data-map="OPNN_SBMSN_GIST" data-maxlengthb="300" />
                    </div>
                    <div class="col-md-12">
                        <label is="name-label" class="col-form-label bg-lighter pe-2 w-px-120 text-sm-end align-top" for="picRvwOpnn">검토의견</label>
                        <textarea is="id-textarea" class="form-control w-85" name="picRvwOpnn" data-map="PIC_RVW_OPNN" rows="2" data-maxlengthb="1000"></textarea>
                    </div>
                </div>
            </form>
            <!-- 입력 영역 -->

            <!-- 첨부 파일 -->
            <div class="card">
                <form name="frmFile" method="post" enctype="multipart/form-data" >
                    <input type="file" name="uploadFiles" multiple="multiple" onchange="pageObject['${pageName}'].fnAddFiles(this);" hidden />
                </form>
                <div class="row g-1">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-blue w-px-120" name="btnAddFile" title="첨부파일 추가">파일추가</button>
                    </div>
                </div>
                <!-- 첨부 파일 테이블 -->
                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-striped" name="fileList">
                        <thead>
                            <th class="text-center" style="width: 24px">No.</th>
                            <th class="text-center" style="width: 200px">파일번호</th>
                            <th class="text-center">파일이름</th>
                            <th class="text-center" style="width: 200px">파일크기</th>
                            <th class="text-center" style="width: 120px">다운로드</th>
                            <th class="text-center" style="width: 120px">삭제</th>
                        </thead>
                        <tbody name="tbodyFileList">
                        </tbody>
                    </table>
                </div> <!-- 첨부 파일 테이블 <div class="table-responsive"> -->
            </div>  <!-- <div class="card"> -->
            <!-- 첨부 파일 -->

            <!-- 업무 버튼 및 건수 표시 -->
            <div>
                <span class="container-page-btn">
                    <!-- 업무 버튼 -->
                    <span class="container-window-btn-right">
                        <button type="button" class="btn btn-primary w-px-120" name="btnSave" title="저장">
                            저장
                        </button>
                    </span>
                </span>
            </div>
            <!-- 업무 버튼 및 건수 표시 -->
        </div> <!-- <div class="card"> -->
    </div> <!-- <div class="container flex-grow-1 px-0"> -->
    <!-- Content -->
</div>
<!-- / inner page html <div class="content-pop"> -->

<script>
    LoadScript("excl02020Script", wctx.url("/resources/js/fims/excl/excl02020.js?ver=${ver}"));

    /**************************************************************************
     * Global Variable
     **************************************************************************/
    pageObject["${pageName}"] = newDoctxFinder("${pageName}");

    /**************************************************************************
     * script 진입
     **************************************************************************/
    $(document).ready(function() {
        // pageObject
        let $P = pageObject["${pageName}"];

        // URL
        $P.prefixUrl = "${prefixUrl}";
        // infoDialog 호출 용도(view 조회(편집불가), create 등록, update 수정)
        $P.callPurpose = "${callPurpose}";
        // datasetControl
        $P.ctrl = newExcl02020Control("${pageName}", "[data-doctx=${pageName}]");
        // 파일 리스트
        $P.fileListArr = new Array();

        /**************************************************************************
         * 사용자 함수(function)
         **************************************************************************/
        // 주소 검색 결과 callback
        $P.callbackSearchAddr = (obj) => {
            $P.$findn("sttrAddr").val(obj.ADDR);                                // 주소
            $P.$findn("sttrZip").val(obj.ZIP);                                  // 우편번호
            $P.$findn("sttrDaddr").val(obj.DTL_ADDR);                           // 상세 주소
        }

        /**************************************************************************
         * 버튼 clickEvent
         **************************************************************************/
        // 납부자 정보를 진술자 정보로 입력한다.
        $P.fnSearchPayer = (btnTitle) => {
            $P.$findn("frmEdit").find("[name='ownrRelCd'] option:contains('본인')").prop("selected", true);
            $P.$findn("sttrNm").val($P.ctrl.getValue("RTPYR_NM"));
            $P.$findn("sttrBrdt").val($P.ctrl.getValue("RTPYR_BRDT"));
            $P.$findn("sttrAddr").val($P.ctrl.getValue("ADDR"));
            $P.$findn("sttrZip").val($P.ctrl.getValue("ZIP"));
            $P.$findn("sttrDaddr").val($P.ctrl.getValue("DTL_ADDR"));

            if ($P.ctrl.getValue("RTPYR_MBL_TELNO") != "")
                $P.$findn("sttrCttpc").val($P.ctrl.getValue("RTPYR_MBL_TELNO"));
            else
                $P.$findn("sttrCttpc").val($P.ctrl.getValue("RTPYR_TELNO"));

            $P.$findn("sttrEml").val($P.ctrl.getValue("RTPYR_EML"));
        }

        // 주소 검색
        $P.fnSearchAddr = async(btnTitle) => {
            let resp = await fetch(wctx.url("/resources/html/searchAddr.html"));
            let template = await resp.text();

            dialog.open({
                  id: "searchAddrDialog"
                , title: btnTitle
                , size: "lg"
                , content: template
                , init: () => {
                    $("#searchAddrCallback").val("pageObject['${pageName}'].callbackSearchAddr");

                    AppSupport.setDialogZindex();
                }
            });
        }

        // 첨부파일 조회
        $P.fnSearchFileList = (opnnId) => {
            let tableFileList = $P.findn("fileList");                            // table element 찾기
            let fileLength = tableFileList.rows.length;

            // 기존 table에 자료가 존재하면 tableRow 삭제
            for (let iLoop = 1; iLoop < fileLength; iLoop++) {
                tableFileList.deleteRow(1);                                     // table 행(Row) 삭제
            }

            // 의견제출 등록일 경우에는 첨부파일을 조회하지 안는다..
            if (!opnnId) return;

            // 첨부파일 리스트
            ajax.get({
                  url: "file/list.do"
                , data: {
                      infoType: "110"
                    , infoKeys: opnnId
                    , fetchSize: 0
                }
                , success: (resp) => {
                    let fileNo = 0;
                    let fileList = resp.fileList;

                    fileList.forEach(function (item, index, array) {
                        fileNo = index + 1;

                        let innerHtml = "";
                        innerHtml += "<tr>";
                        innerHtml += "<td class='text-center'>" + fileNo + "</td>";
                        innerHtml += "<td class='text-center'>" + item.FILE_ID + "</td>";
                        innerHtml += "<td class='text-center'>" + item.FILE_NM + "</td>";
                        innerHtml += "<td class='text-center'>" + item.FILE_SIZE + " byte</td>";
                        innerHtml += "<td class='text-center'>" + "<button type='button' class='btn' onclick=";
                        innerHtml += "pageObject['${pageName}'].fnFileDownload(" + item.FILE_ID + ");" + "><i class='bx bx-download me-1'></i></button>" + "</td>";
                        innerHtml += "<td class='text-center'>" + "<button type='button' class='btn' onclick=";
                        innerHtml += "pageObject['${pageName}'].fnFileRemove(this);" + "><i class='bx bx-trash me-1'></i></button>" + "</td>";
                        innerHtml += "</tr>";

                        $P.$findn("tbodyFileList").append(innerHtml);
                    });
                }
            });
        }

        // 첨부파일 등록
        $P.fnAddFiles = (obj) => {
            let tableFileList = $P.findn("fileList");                            // table element 찾기
            let fileNo = tableFileList.rows.length - 1;                         // table에 있는 파일 갯수 (첫번째 title은 제외하기 위해서 -1 처리)
            let maxFileCnt = 3;                                                   // 의견제출에 등록 할 수 있는 첨부 파일 최대 개수
            let attFileCnt = obj.files.length;                                    // 선택한 파일의 개수
            let fileArr = new Array();                                            // 파일 배열

            fileArr = $P.fileListArr;

            // 등록할 파일 개수 확인
            if (attFileCnt + fileNo > maxFileCnt)
                return dialog.alert("첨부파일은 최대 " + maxFileCnt + "개 까지 첨부 가능합니다.");

            // 첨부파일을 table에 추가.
            for (let iLoop = 0; iLoop < attFileCnt; iLoop++) {
                let selectedFile = obj.files[iLoop];
                let innerHtml = "";

                fileNo += 1;

                innerHtml += "<tr>";
                innerHtml += "<td class='text-center'>" + fileNo + "</td>";
                innerHtml += "<td class='text-center'>" + "</td>";
                innerHtml += "<td class='text-center'>" + selectedFile.name + "</td>";
                innerHtml += "<td class='text-center'>" + selectedFile.size + " byte</td>";
                innerHtml += "<td class='text-center'>" + "</td>";
                innerHtml += "<td class='text-center'>" + "<button type='button' class='btn' onclick=";
                innerHtml += "pageObject['${pageName}'].fnFileRemove(this);" + "><i class='bx bx-trash me-1'></i></button>" + "</td>";
                innerHtml += "</tr>";

                $P.$findn("tbodyFileList").append(innerHtml);

                fileArr.push(obj.files[iLoop]);
            }
        }

        // 첨부파일 삭제 아이콘 클릭 이벤트
        $P.fnFileRemove = (obj) => {
            dialog.alert({
                  content: "선택한 파일을 삭제하시겠습니까?"
                , onOK: () => {
                    let tr = $(obj).parent().parent();                            // 클릭한 버튼이 속한 tr 요소
                    let td = tr.children();
                    let fileId = td.eq(1).text();                               // 삭제할 파일번호
                    let fileName = td.eq(2).text();                             // 삭제할 파일이름

                    if (fileId != null && fileId != "") {
                        ajax.post({
                              url: "file/remove.do"
                            , data: { fileIDs: fileId }
                            , success: (resp) => { }
                        });
                    } else {
                        let filtered = $P.fileListArr.filter((value, index, arr) => {
                            return (value.name != fileName);
                        });

                        $P.fileListArr = filtered;
                    }

                    $(obj).closest("tr").remove();                                // table 에서 제거
                }
            });
        }

        // 첨부파일 다운로드 아이콘 클릭 이벤트
        $P.fnFileDownload = (fileID) => {
            top.location.href = "/file/download.do?fileID=" + fileID;
        }

        // 저장
        $P.fnSave = () => {
            // validate 확인
            if (!AppSupport.customValidate($P.$findn("frmEdit").find("input,select,textarea"))) return;

            // formFields
            let params = new FimsFormFields($P.selectorn("frmEdit")).get();

            dialog.alert({
                  content: "현재 " + $P.ctrl.prefixName + " 정보를 저장하시겠습니까?"
                , init: () => { AppSupport.setDialogZindex(); }
                , onOK: () => { $P.ctrl.save(params); }                         // formFields
            });
        }

        /**************************************************************************
         * 초기 셋팅
         **************************************************************************/
        // 이벤트 설정
        $P.setEvent = () => {
            // 버튼 이벤트
            $P.$findn("btnSearchPayer").on("click", function() {
                $P.fnSearchPayer($(this).attr("title"));                        // 납부자 정보 조회 버튼 이벤트
            });
            $P.$findn("btnSearchAddr").on("click", function() {
                $P.fnSearchAddr($(this).attr("title"));                         // 주소 검색 버튼 이벤트
            });
            $P.$findn("btnAddFile").on("click", function() {
                $P.$findn("uploadFiles").trigger("click");                      // 파일 등록 버튼 이벤트
            });

            $P.$findn("btnSave").on("click", () => $P.fnSave());                // 저장
        }

        // 초기 화면 설정
        $P.fnReset = () => {
            // 초기화
            $P.findn("frmEdit").reset();                                        // 화면 초기화
            AppSupport.initDatepicker($P.findn("frmEdit"));                     // 달력 초기화

            // 기본 데이터 설정
            $P.$findn("rcptYmd").datepicker("setDate", TODAY());                // 접수 일자

            // View로 호출되었을때 disabled 셋팅
            if ($P.callPurpose == "view") {
                // input 요소들을 disabled
                $P.$findn("frmEdit").find("input,textarea,select").prop("disabled", true);

                // button 요소들을 disabled
                $P.$findn("btnRcptYmd").prop("disabled", true);                  // 접수 일자 달력 버튼
                $P.$findn("btnSearchPayer").prop("disabled", true);              // 납부자 버튼
                $P.$findn("btnSearchAddr").prop("disabled", true);               // 우편번호 버튼
                $P.$findn("btnAddFile").prop("disabled", true);                  // 파일 추가 버튼
                $P.$findn("btnSave").prop("disabled", true);                     // 저장 버튼
            } else if ($P.callPurpose == "create") {
                $P.$findn("rcptNo").prop("readonly", true);                      // 접수 번호
            }
        }

        /**************************************************************************
         * 최초 실행 함수
         **************************************************************************/
        // 1. 이벤트 설정
        $P.setEvent();

        // 2. 초기 화면 설정
        $P.fnReset();

        // 3. Dataset 설정
        $P.ctrl.setData([${Info}]);
    });

</script>
