<%@ 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-wrapper" data-doctx="${pageName}">
    <!-- Content -->
    <div class="container-xxl flex-grow-1 px-0">
        <div class="card wrapper-list">
            <!-- 상단 버튼 -->
            <div class="container-page-btn">
                <button type="button" class="btn btn-outline-dark w-px-120" name="btnReset" title="초기화">
                    초기화
                </button>
                <span class="container-window-btn-right">
                    <button type="button" class="btn btn-search w-px-120" name="btnSearch" title="검색">
                        검색
                    </button>
                    <button type="button" class="btn btn-excel w-px-120" name="btnExcel" title="엑셀">
                        엑셀
                    </button>
                </span>
            </div>
            <!-- 상단 버튼 -->

            <!-- 검색 조건 영역 -->
            <form name="frmSearch">
                <!-- hidden -->
                <input type="hidden" name="sggCd" />
                <input type="hidden" name="deptCd" />
                <input type="hidden" name="conOrg" />

                <!-- 메인 조건 -->
                <div class="container-search">
                    <div class="row g-1">
                    	<jsp:include page="/WEB-INF/jsp/include/sgg-tasklist.jsp" />
                        <div class="col-6">
                            <label class="form-label form-search-title w-px-120 text-end fw-bold">발송일자</label>
                            <span class="form-search-linebox">
                                <input type="text" class="form-control form-date" name="schExtriRegymdFrom"
                                    data-fmt-type="day" autocomplete="off" title="시작 날짜 선택" />
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                                ~
                                <input type="text" class="form-control form-date" name="schExtriRegymdTo"
                                    data-fmt-type="day" autocomplete="off" title="종료 날짜 선택" />
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                            </span>
                        </div>
                        <!-- 동적검색 -->
                        <div class="col-6">
                            <input type="hidden" name="by" />
                            <input type="text" class="form-control w-px-120 text-end fw-bold" name="byOutput" value="동적 검색" readonly />
                            <input type="hidden" name="mainOption" />
                            <input type="hidden" name="subOption" />
                            <input type="text" class="form-control w-px-400" name="term" autocomplete="off" />
                            <!-- 상세 검색조건 버튼 -->
                            <span class="flr">
                                <button type="button" class="btn btn-open-detail" data-bs-toggle="collapse" data-bs-target="[data-doctx='${pageName}'] [name='searchDetail']">
                                    <i class="bx bx-chevron-down"></i>
                                    상세검색
                                </button>
                            </span>
                        </div> <!-- 동적검색 -->
                    </div>
                </div> <!-- 메인 조건 -->

                <!-- 상세 조건 -->
                 <div name="searchDetail" class="container-search container-search-detail collapse">
                    <div class="row g-1">
                        <div class="col-6">
                            <select class="form-select w-px-120 text-center" name="schRegDateOpt">
                                <option value="regDt">등록일자</option>
                                <option value="mdfcnDt">수정일자</option>
                            </select>
                            <span class="form-search-linebox">
                                <input type="text" class="form-control form-date" name="schRegDateFrom"
                                    data-fmt-type="day" autocomplete="off" title="시작 날짜 선택" />
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                                ~
                                <input type="text" class="form-control form-date" name="schRegDateTo"
                                    data-fmt-type="day" autocomplete="off" title="종료 날짜 선택">
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                            </span>
                        </div>
                        <div class="col-6">
                            <select class="form-select w-px-120 text-center" name="schRgtrOpt">
                                <option value="rgtr">등록자</option>
                                <option value="mdfr">수정자</option>
                            </select>
                            <input type="hidden" name="schRgtrCd" />
                            <input type="text" class="form-control w-px-160" name="schRgtrNm" />
                            <button type="button" class="btn btn-sm btn-outline-dark" name="btnFindUser" title="사용자 검색">검색</button>
                        </div>
                    </div>
                </div> <!-- 상세 조건 -->
            </form>
            <!-- 검색 조건 영역 -->

            <!-- 업무 버튼 및 건수 표시 -->
            <div>
                <span class="container-page-btn" name="gridButtonArea">
                    <!-- 건수, 페이지 표시 -->
                    <div class="d-flex flex-row justify-content-between">
                        <span is="paging-info" class="dataTables_info" name="dataPagingInfo" role="status" aria-live="polite"></span>
                        <ul class="pagination pagination-primary" name="dataPaging">
                        </ul>
                    </div>
                </span>
            </div>
            <!-- 업무 버튼 및 건수 표시 -->

            <!-- DataTables(그리드) -->
            <div class="card-datatable text-nowrap">
                <div class="dataTables_wrapper dt-bootstrap5 no-footer">
                    <div class="table-responsive ox-scroll oy-scroll h-px-400" name="tableRspns">
                        <table class="table-layout-fixed dataTable datatables-ajax table table-bordered no-footer" aria-describedby="DataTables_Table_0_info">
                            <thead class="sticky-thead">
                                <tr name="theadTr" data-search-target="[data-doctx='${pageName}']">
                                    <th class="cmn" style="width: 72px;">No.</th>
                                    <th class="cmn" style="width: 240px;" onclick="FimsSupport.searchFromGridTitle('RELETCDATA', this.innerText, 'match', 'part');">발송자료키</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('JOB_CD', this.innerText, 'match', 'part');">우편물코드</th>
                                    <th class="cmn" style="width: 120px;">우편물종류</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('EXTRI_REGYMD', this.innerText, 'ymd', '');">발송일자</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('RCEPT_YMD', this.innerText, 'ymd', '');">접수일자</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('DIV_KB', this.innerText, 'codeValue', 'EGP002');">취급구분</th>
                                    <th class="cmn" style="width: 100px;" onclick="FimsSupport.searchFromGridTitle('RCEPT_CNT', this.innerText, 'match', 'part');">발송건수</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('RCEPT_AMT', this.innerText, 'match', 'part');">결제금액</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('USEFEE_AMT', this.innerText, 'match', 'part');">제작수수료</th>
                                    <th class="cmn" style="width: 120px;" onclick="FimsSupport.searchFromGridTitle('TOTPOST_PRC', this.innerText, 'match', 'part');">우편요금</th>
                                    <th class="cmn" style="width: 180px;">등록일시</th>
                                    <th class="cmn" style="width: 140px;">등록사용자</th>
                                    <th class="cmn dummy-th"></th>
                                </tr>
                            </thead>
                            <tbody name="tbodyList">
                            </tbody>
                            <template is="curly-brackets" name="tmpltRows">
                                <tr data-index="{data-index}">
                                    <td class="cmn text-center" onclick="{onclick}">{ROW_NUM}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{RELETCDATA}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{JOB_CD}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{JOB_CD3_NM}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{EXTRI_REGYMD}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{RCEPT_YMD}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{DIV_KB_NM}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{RCEPT_CNT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{RCEPT_AMT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{USEFEE_AMT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{TOTPOST_PRC}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{REG_DT}</td>
                                    <td class="cmn text-center" onclick="{onclick}">{RGTR_NM}</td>
                                    <td class="cmn dummy-td"></td>
                                </tr>
                            </template>
                            <template name="tmpltNotFound">
                                <tr class="odd">
                                    <td valign="top" colspan="14" class="dataTables_empty text-center">${prefixName} 정보를 찾지 못했습니다.</td>
                                </tr>
                            </template>
                        </table>
                    </div>
                </div>
            </div>
            <!-- DataTables(그리드) -->

            <p></p>

            <!-- DataTables(그리드) -->
            <div class="card-datatable text-nowrap">
                <div class="dataTables_wrapper dt-bootstrap5 no-footer">
                    <div class="table-responsive ox-scroll oy-scroll h-px-150" name="tableRspnsSumAmt">
                        <table class="table-layout-fixed dataTable datatables-ajax table table-bordered no-footer" aria-describedby="DataTables_Table_0_info">
                            <thead class="sticky-thead">
                                <tr name="theadTrSumAmt" data-search-target="[data-doctx='${pageName}']">
                                    <th class="cmn" style="width: 160px;">취급구분</th>
                                    <th class="cmn" style="width: 200px;">발송건수</th>
                                    <th class="cmn" style="width: 240px;">결제금액</th>
                                    <th class="cmn" style="width: 240px;">제작수수료</th>
                                    <th class="cmn" style="width: 240px;">우편요금</th>
                                    <th class="cmn dummy-th"></th>
                                </tr>
                            </thead>
                            <tbody name="tbodySumAmtList">
                            </tbody>
                            <template is="curly-brackets" name="tmpltSumAmtRows">
                                <tr data-key="{data-index}">
                                    <td class="cmn text-center" onclick="{onclick}">{DIV_KB_NM}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{RCEPT_CNT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{RCEPT_AMT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{USEFEE_AMT}</td>
                                    <td class="cmn text-end"    onclick="{onclick}">{TOTPOST_PRC}</td>
                                    <td class="cmn dummy-td"></td>
                                </tr>
                            </template>
                            <template name="tmpltNotFoundSumAmt">
                                <tr class="odd">
                                    <td valign="top" colspan="6" class="dataTables_empty text-center">${prefixName} 정보를 찾지 못했습니다.</td>
                                </tr>
                            </template>
                        </table>
                    </div>
                </div>
            </div>
            <!-- DataTables(그리드) -->
        </div> <!-- <div class="card wrapper-list"> -->
    </div> <!-- <div class="container-xxl flex-grow-1 px-0"> -->
    <!-- Content -->

    <div class="content-backdrop fade"></div>
</div>
<!-- / inner page html <div class="content-wrapper"> -->

<script>
    LoadScript("epst02050Script", wctx.url("/resources/js/fims/epst/epst02050.js?ver=${ver}"));

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

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

        // URL
        $P.prefixUrl = "${prefixUrl}";
        // datasetControl
        $P.ctrl = newEpst02050Script("${pageName}", "[data-doctx=${pageName}]");

        /**************************************************************************
         * DataTables 이벤트
         **************************************************************************/
        // dataTable 클릭 이벤트
        $P.dataTableClick = (dataIndex) => {
            if (!dataIndex) return;

            $P.$findn("tbodyList").setCurrentRow(dataIndex);

            Apply.toDataset.current($P.ctrl.dataset, dataIndex);
        }

        // DataTables에 스크롤이 맨 밑으로 이동했을 때 이벤트
        $P.scrollDataList = () => {
            $P.ctrl.load($P.ctrl.query.pageNum + 1);
        }

        /**************************************************************************
         * 사용자 함수(function)
         **************************************************************************/
        // 사용자검색 callback
        $P.callbackFindUser = (userId, userNm) => {
            $P.$findn("schRgtrCd").val(userId);                                 // 사용자 ID
            $P.$findn("schRgtrNm").val(userNm);                                 // 사용자 명
        }

        /**************************************************************************
         * 버튼 clickEvent
         **************************************************************************/
        // 업무 구분 변경 이벤트
        $P.fnResetAndChangeBiz = (taskSeCd) => {
            // 업무 구분 코드
            if (!taskSeCd) {
                taskSeCd = $("#layout-navbar input[name='taskSeCd']:checked").val();
            }

            // 초기화
            $P.fnReset(taskSeCd);

            // 업무 구분에 따른 URL 설정
            $P.ctrl.urls.load = wctx.url($P.prefixUrl + "/050/list.do");   // 검색

            // 최고 관리자인지 권한을 확인하여 업무구분을 선택할 수 있도록 하자 -> 수정 필요
            $P.$findn("frmSearch").find("input[name='taskSeCd']").each(function(i) {
                $(this).prop("disabled", "true");
            });

            FimsSupport.renderForTask($P.findn("frmSearch"), taskSeCd.toLowerCase());       // 업무별 검색 조건
            FimsSupport.renderForTask($P.findn("gridbuttonArea"), taskSeCd.toLowerCase());  // 업무별 버튼
        }

        // 사용자검색 버튼 클릭 이벤트
        $P.fnGetFindUser = () => {
            let params = {
                callbackFuncName: "pageObject['${pageName}']['callbackFindUser']"
            }

            ajax.get({
                  url: wctx.url("/user/user02/010/main.do")
                , data: params || {}
                , success: (resp) => {
                    let dialogName = "userDialog";
                    let dialogId = dialogName + "-" + uuid();

                    dialog.open({
                          id: dialogId
                        , title: "사용자 검색"
                        , size: "lg"
                        , content: resp
                        , init: () => {
                            $("#" + dialogId).attr("name", dialogName);
                            $("#" + dialogId).attr("data-ref-doctx", "${pageName}");

                            AppSupport.setDialogZindex();
                        }
                        , onClose: () => { }
                    });
                }
            });
        }

        // 검색 버튼 이벤트
        $P.fnSearchList = () => {
            // validate 확인
            if (!AppSupport.customValidate($P.$findn("frmSearch").find("input,select,textarea"))) return;

            // 검색조건
            $P.ctrl.query = new FimsFormFields($P.selectorn("frmSearch")).get();    // 검색 조건
            $P.ctrl.query.fetchSize = DEFAULT_FETCH_SIZE;                           // 한번에 조회되는 자료 건수
            $P.ctrl.query.relorsectCd = $P.$findn("deptCd").val();                  // 결제부서코드(부서코드)
            $P.ctrl.query.delYn = "N";                                              // 삭제 여부
            $P.ctrl.query.pageNum = 1;                                              // page

            ajax.get({
                  url: $P.ctrl.urls.load
                , data: $P.ctrl.query
                , success: (resp) => {
                    if ($P.ctrl.query.pageNum == 1)
                    	$P.ctrl.setData(resp);
                    else {
                    	$P.ctrl.addData(resp);
                    }
                    $P.ctrl.dsSumAmt.setData(resp.sumAmt);
                }
            });
        }

        // 엑셀 버튼 이벤트
        $P.fnExcel = () => {
            if ($P.ctrl.dataset.empty)
                return dialog.alert("검색된 " + $P.ctrl.prefixName + " 정보가 없습니다.");

            // DataTables(그리드)
            $P.ctrl.query.cellDefs =
                  AppSupport.getCellDefs($P.$findn("theadTr").find("th").not(".dummy-th").not(":eq(0)")
                , $($P.findn("tmpltRows").content).find("td").not(".dummy-td").not(":eq(0)")
                , FimsSupport.getCellDefsForPrivacyCell);

            $P.ctrl.download();
        }

        /**************************************************************************
         * 초기 설정
         **************************************************************************/
        // 이벤트
        $P.setEvent = () => {
            // 기본 버튼 이벤트
            $P.$findn("btnReset").on("click", () => $P.fnResetAndChangeBiz());  // 초기화
            $P.$findn("btnSearch").on("click", () => $P.fnSearchList());        // 검색
            $P.$findn("btnExcel").on("click", () => $P.fnExcel());              // 엑셀
            $P.$findn("btnFindUser").on("click", () => $P.fnGetFindUser());     // 사용자 검색

            // 동적검색에서 엔터(Enter) 키를 누르면 검색한다.
            $P.$findn("term").onEnterPress($P.fnSearchList);

            // DataTables width 변경 조정
            Componentization.fnMakeResizableTable($P.findn("tableRspns"));
            Componentization.fnMakeResizableTable($P.findn("tableRspnsSumAmt"));
            // DataTables 스크롤 이벤트 생성
            Componentization.fnMakeScrollableTable($P.findn("tableRspns"), $P.scrollDataList);
            Componentization.fnMakeScrollableTable($P.findn("tableRspnsSumAmt"), $P.scrollDataList);
        }

        // 화면 초기 설정
        $P.fnReset = (taskSeCd) => {
            // 초기화
            $P.findn("frmSearch").reset();                                      // 화면 초기화
            AppSupport.initDatepicker($P.findn("frmSearch"));                   // 달력 초기화
            AppSupport.initDetailSearchButton($P.findn("frmSearch"));           // 상세검색 버튼 화살표

            // input, select 초기화
            let searchForm = $P.$findn("frmSearch");
            searchForm.find("input[type='radio']").not("[name='taskSeCd']").prop("checked", false);
            searchForm.find("input[type='checkbox']").prop("checked", false);
            searchForm.find("input[type='text']").val("");
            searchForm.find("input[type='hidden']").val("");
            searchForm.find("select").each(function(){ $(this).find("option:eq(0)").prop("selected", true); });

            // 기본 데이터 설정
            $P.$findn("sggCd").val("${sggCd}");                                 // 시군구 코드
            $P.$findn("deptCd").val("${deptCd}");                               // 부서 코드
            $P.$findn("conOrg").val("${conOrg}");                               // E그린 외부기관구분코드
            $P.$findn("frmSearch").find("input[name='taskSeCd'][value='" + taskSeCd + "']").prop("checked", true);  // 업무 구분 코드
            $P.$findn("schExtriRegymdFrom").datepicker("setDate", DateSupport.getAddDay(-7));   // 발송 일자 시작
            $P.$findn("schExtriRegymdTo").datepicker("setDate", TODAY());                       // 발송 일자 종료
            $P.$findn("byOutput").val("동적 검색");                             // 동적 검색
            $P.$findn("schRgtrNm").prop("readonly", true);                      // 사용자 이름

            // dataset 초기화
            $P.ctrl.dataset.clear();
            $P.ctrl.dsSumAmt.clear();
        }

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

        // 2. 초기 설정 및 업무 구분 변경
        $P.fnResetAndChangeBiz($("#layout-navbar input[name='taskSeCd']:checked").val());

        // 3. 보안모드
        fn_securityModeToggle($("#securityMode--top").is(":checked"));
    });

</script>
