<!DOCTYPE html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org">
<!--
 *************************************************************************
 * @source  : RandomCouponList.html
 * @desc    : 쿠폰난수관리 Page
 *------------------------------------------------------------------------
 * TSIT
 * Copyright(c) 2020 TSIT, All rights reserved.
 *------------------------------------------------------------------------
 * VER  DATE        AUTHOR      DESCRIPTION
 * ---  ----------- ----------  -----------------------------------------
 * 1.0  2021.01.22  xodud1202   쿠폰난수관리
 *************************************************************************
-->
<div id="main">
    <!-- 메인타이틀 영역 -->
    <div class="main-title"></div>

    <!-- 메뉴 설명 -->
    <div class="infoBox menu-desc"></div>
    
    <form id="searchForm" name="searchForm" th:action="@{'/marketing/coupon/random/list/paging'}" th:onsubmit="fnSearch(); return false;" >

        <!-- 패널 영역1 -->
        <div class="boxStyle">
			<span class="boxControl">
				<i class="fa fa-chevron-up" data-view="show"></i>
                <!-- <i class="fa fa-times" data-view="show"></i> -->
			</span>
            <!-- 검색조건 영역 -->
            <div class="boxTitle">검색조건</div>
            <ul class="boxContent">
                <li class="boxContentTop">
                    <table class="frmStyle">
                        <col width="8%">
                        <col width="12%">
                        <col width="8%">
                        <col width="12%">
                        <col width="8%">
                        <col width="12%">
                        <col width="8%">
                        <col width="12%">
                        <col width="8%">
                        <col width="12%">
                        <tr>
                            <th>쿠폰명</th>
                            <td>
                                <input type="text" name="cpnNm" maxlength="40" class="type-text" style="width: 100%;"/>
                            </td>
                            <th>등록가능기간</th>
                            <td colspan="10" id="terms" class="availTerm">
                            </td>
                        </tr>
                    </table>
                    <div class="panelBtnB">
                        <input type="button" value="조회" class="btn btn-base btn-lg btn-info" id="btnSearch" onclick="fnSearch();"/>
                        <input type="button" value="초기화" class="btn btn-dark btn-lg " onclick="$('#searchForm')[0].reset(); fnInitCalendar();" />
                    </div>
                </li>
            </ul>
            <!-- //검색조건 영역 -->
        </div>
        <!-- 패널 영역1 -->
        <div class="panelStyle2">
            <!-- 검색결과 영역 -->
            <!-- 상단버튼 영역  -->
            <ul class="lrStyle">
                <li class="aR">
                    검색결과 : <strong><span id="gridRowTotalCount">0</span> 건</strong>&nbsp;
                    쪽번호 <span id="pgNo">0</span>/ <strong id="endPgNo">0</strong>&nbsp;&nbsp;
                    <select id="pageSize" name="pageSize">
                        <option value="50" selected="selected">50개씩 보기</option>
                        <option value="100">100개씩 보기</option>
                        <option value="500">500개씩 보기</option>
                        <option value="1000">1000개씩 보기</option>
                    </select>
                    <input type="hidden" name="pageNo" id="pageNo" value ="1"/>
                </li>
            </ul>

            <!-- //상단버튼 영역  -->
            <div class="panelContent">
                <div id="gridList" style="width: 100%;height: 400px;" class="ag-theme-balham"></div>
            </div>
            <div class="panelBtnB">
                <!-- Paging -->
                <div class="tablePaging" id="couponPagination"></div>
                <!-- //Paging -->
            </div>
            <!-- 검색결과 영역 -->
        </div>
    </form>
    <!-- //패널 영역2 -->
    <!-- 등록/수정 -->
    <div class="panelStyle2">
        <ul class="lrStyle">
            <li>
                <span class="infoTxt cBlue"><i class="fa fa-info-circle" aria-hidden="true"></i>쿠폰시작문자(단일)의 경우에는 중복된 코드를 삽입할 수 없습니다.</span>
            </li>
        </ul>
        <form id="detailForm" name="detailForm" action="#" th:action="@{'/marketing/coupon/random/save'}">
            <input type="hidden" name="rdCpnSq"/>
            <table class="frmStyle">
                <colgroup>
                    <col style="width:10%;"/>
                    <col style="width:23.3%;"/>
                    <col style="width:10%;"/>
                    <col style="width:23.3%;"/>
                    <col style="width:10%;"/>
                    <col/>
                </colgroup>
                <tr>
                    <th>쿠폰명<i class="star"></i></th>
                    <td>
                        <input type="text" class="w200" name="rdCpnNm" maxlength="50" data-valid-name="랜덤쿠폰명"/>
                    </td>
                    <th>쿠폰생성수량<i class="star"></i></th>
                    <td>
                        <input type="text" class="w200" name="rdCpnIdQty" maxlength="8" data-valid-name="랜덤쿠폰생성수량" data-valid-type="numeric"/>
                    </td>
                    <th>쿠폰시작문자<i class="star"></i></th>
                    <td>
                        <select name="rdCpnPrefixGb" data-valid-name="쿠폰시작문자구분" onchange="onChangePrefixGb(this.value);">
                            <option value="R">랜덤</option>
                            <option value="S">단일</option>
                        </select>
                        <input type="text" class="w200" name="rdCpnPrefix" maxlength="4" required="required" data-valid-name="쿠폰시작문자" data-valid-type="alphaNumeric" style="text-transform: uppercase;"/>
                    </td>
                </tr>
                <tr>
                    <th>지급구분(<font color="RED">*</font>)
                    </th>
                    <td>
                        <label class="rdoBox" th:if="${rdcpnGbList}" th:each="oneData, status : ${rdcpnGbList}" >
                            <input type="radio" name="rdcpnGb" class="type-radio" th:value="${oneData.cd}" th:text="${oneData.cdNm}" onchange="onChangePdGb(this.value);"/>
                        </label>
                    </td>
                    <th class="rdcpnGbCpn">적용쿠폰ID<i class="star"></i></th>
                    <td class="rdcpnGbCpn">
                        <input name="cpnName" type="text" class="w150" onkeypress="if (window.event.keyCode == 13) { fnOpenCouponRetrievePopup('input[name=cpnId]', 'input[name=cpnName]'); }"/>
                        <button type="button" class="btn icn" th:onclick="fnOpenCouponRetrievePopup('input[name=cpnId]', 'input[name=cpnName]')"><i class="fa fa-search cpn" aria-hidden="true"></i></button>
                        <input name="cpnId" type="text" class="w100" maxlength="20" readonly/>
                    </td>
                    <th class="rdcpnGbCpn">쿠폰발급수량<i class="star"></i></th>
                    <td class="rdcpnGbCpn">
                        <input type="text" class="w200" name="cpnCnt" maxlength="20" data-valid-name="쿠폰발급수량" data-valid-type="numeric"/>
                    </td>
                    <th class="rdcpnGbPnt">적용포인트<i class="star"></i></th>
                    <td class="rdcpnGbPnt">
                        <input type="text" class="w200" name="pointAmt" maxlength="20" data-valid-name="적용포인트금액" data-valid-type="numeric"/>
                    </td>
                    <th class="rdcpnGbPnt">포인트만료일시<i class="star"></i></th>
                    <td  class="rdcpnGbPnt">
                        <input name="pointExpireDt" type="text" class="w80 schDate" maxlength="10" data-valid-name="포인트만료일시" />
                    </td>
                </tr>
                <tr>
                    <th>등록기간<i class="star"></i></th>
                    <td class="dashR">
                        <input name="regPossibleStdt" type="text" class="w80 schDate" maxlength="10" required data-valid-name="등록가능시작일자" />
                        ~
                        <input name="regPossibleEddt" type="text" class="w80 schDate" maxlength="10" required data-valid-name="등록가능종료일자" />
                    </td>
                    <th>중복사용가능여부<i class="star"></i></th>
                    <td>
                        <select name="dupUsableYn" required data-valid-name="중복사용가능여부">
                            <option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
                        </select>
                    </td>
                    <th>사용여부<i class="star"></i></th>
                    <td>
                        <select name="useYn" required data-valid-name="사이트">
                            <option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:text="|${oneData.cdNm}|"></option>
                        </select>
                    </td>
                </tr>
            </table>

            <div class="panelBtnB">
                <button type="button" class="btn btn-info btn-lg" id="btnNew">신규</button>
                <button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
    /*<![CDATA[*/

    var columnDefs = [
        {width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false, editable: false,pinned: 'left'}
        ,{field: "rdCpnSq"       ,headerName:"랜덤쿠폰일련번호"     		,width:150   ,cellClass:"text-center",hide:true}
        ,{field: "rdCpnNm"		,headerName:"쿠폰명"					,width:200	,cellClass:"text-center"
            ,cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
        }
        ,{field: "rdCpnIdQty"         ,headerName:"생성수량"     		,width:90   ,cellClass:"text-center"
            ,cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
        }
        ,{field: "rdCpnPrefix"        ,headerName:"랜덤쿠폰시작문자"          		,width:120   ,cellClass:"text-center",hide:true}
        ,{field: "rdCpnPrefixGb"        ,headerName:"랜덤쿠폰시작문자구분"          		,width:120   ,cellClass:"text-center",hide:true}
        ,{field: "regPossibleStdt"    ,headerName:"등록가능시작일시"    		,width:150   ,cellClass:"text-center"
            ,cellRenderer: function(params) {T
                return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
            }
        }
        ,{field: "regPossibleEddt"    ,headerName:"등록가능종료일시"           	,width:150   ,cellClass:"text-center"
            ,cellRenderer: function(params) {
                return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
            }
        }
        ,{field: "dupUsableYn"        ,headerName:"중복사용가능여부"          		,width:120   ,cellClass:"text-center"}
        ,{field: "rdcpnGb"            ,headerName:"구분"            	,width:80   ,cellClass:"text-center",hide:true}
        ,{field: "rdcpnGbNm"            ,headerName:"구분"            	,width:100   ,cellClass:"text-center"}
        ,{field: "cpnId"              ,headerName:"적용쿠폰ID"          		,width:100   ,cellClass:"text-center"}
        ,{field: "cpnCnt"             ,headerName:"쿠폰발급수량"            ,width:100   ,cellClass:"text-center"
            , cellRenderer: function(params) {
                return params.value.addComma();
            }
        }
        ,{field: "pointAmt"             ,headerName:"적용포인트금액"        ,width:120   ,cellClass:"text-center"
            , cellRenderer: function(params) {
                return params.value.addComma();
            }
        }
        ,{field: "pointExpireDt"           ,headerName:"포인트만료일시"          	,width:150   ,cellClass:"text-center"
            ,cellRenderer: function(params) {
                return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
            }
        }
        ,{field: "useYn"             ,headerName:"사용여부"        	,width:80   ,cellClass:"text-center"}
        ,{field: "regId"              ,headerName:"등록자"           		,width:100   ,cellClass:"text-center"}
        ,{field: "regDt"              ,headerName:"등록일시"            	,width:150   ,cellClass:"text-center"
            ,cellRenderer: function(params) {
                return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
            }
        }
        ,{field: "updId"              ,headerName:"수정자ID"           		,width:100   ,cellClass:"text-center",hide:true}
        ,{field: "updDt"              ,headerName:"수정일시"            	,width:150   ,cellClass:"text-center",hide:true
            ,cellRenderer: function(params) {
                return !gagajf.isNull(params.value) ? gagaAgGrid.toDateTimeFormat(params.value) : '';
            }
        }
    ];

    var cpnListOpt = gagaAgGrid.getGridOptions(columnDefs);
    cpnListOpt.rowSelection = 'multiple';
    cpnListOpt.suppressRowClickSelection = true;

    // 셀 클릭 이벤트
    cpnListOpt.onCellClicked = function(event) {
        var field = event.colDef.field;
        if (event.colDef.field == "rdCpnIdQty"){
            var rdCpnSq = event.data.rdCpnSq;
            var actionUrl = "/marketing/coupon/random/cpnUseDetail/popup/form?rdCpnSq="+rdCpnSq;
            cfnOpenModalPopup(actionUrl,'RandomCpnDetailPopup');
        }

        if (event.colDef.field == "rdCpnNm"){
            var formId = '#detailForm';

            // 기본정보 입력
            $(formId + ' input[name=rdCpnSq]').val(event.data.rdCpnSq);
            $(formId + ' input[name=rdCpnNm]').val(event.data.rdCpnNm);
            $(formId + ' input[name=rdCpnIdQty]').val(event.data.rdCpnIdQty.addComma());
            $(formId + ' select[name=dupUsableYn]').val(event.data.dupUsableYn);
            $(formId + ' input[name=cpnId]').val(event.data.cpnId);
            $(formId + ' input[name=cpnCnt]').val(event.data.cpnCnt.addComma());
            $(formId + ' input[name=pointAmt]').val(event.data.pointAmt.addComma());
            $(formId + ' select[name=useYn]').val(event.data.useYn);
            $(formId + ' input[name=rdCpnPrefix]').val(event.data.rdCpnPrefix);
            $(formId + ' select[name=rdCpnPrefixGb]').val(event.data.rdCpnPrefixGb);

            $("input[name=rdcpnGb][value="+event.data.rdcpnGb+"]").prop('checked', true);
            onChangePdGb(event.data.rdcpnGb);

            // 등록 기간 설정
            var stDate = event.data.regPossibleStdt.split(" ")[0];
            var edDate = event.data.regPossibleEddt.split(" ")[0];
            var exDate = '';
            if(!gagajf.isNull(event.data.pointExpireDt)) {
                exDate = event.data.pointExpireDt.split(" ")[0];
            }

            $(formId + ' input[name=regPossibleStdt]').val(stDate);
            $(formId + ' input[name=regPossibleEddt]').val(edDate);
            $(formId + ' input[name=pointExpireDt]').val(exDate);

            //setComma("detailForm", true);

        }
    }

    $(document).ready(function() {
        var hideList = [];
        cfnCreateCalendar('#terms', 'availStdt', 'availEddt', true, '지급일', '');
        //$('.btnToday').trigger('click');

        //대상구분 초기화
        $("input[name=rdcpnGb][value=C]").prop('checked', true);
        onChangePdGb("C");

        $("select[name=dupUsableYn]").val("N");
        $("select[name=rdCpnPrefixGb]").val("R");

        setComma("detailForm", true);

        // Create a agGrid
        gagaAgGrid.createGrid('gridList', cpnListOpt);

        uifnFitGrid('auto');

        // fnSearch();
    });

    var fnInitCalendar = function() {
        //$(".btnToday").trigger('click');
    }

    /**
     * 목록 조회
     */

    function fnSearch() {
        gagaPaging.init('searchForm', fnSearchCallBack, 'couponPagination', $('#searchForm').find('#pageSize').val());
        gagaPaging.load(1);
    }

    var fnSearchCallBack = function(result) {
        $('#searchForm').find('#gridRowTotalCount').html(result.paging.totalCount.addComma());
        $('#searchForm').find('#pageNo').val(result.paging.pageNo.addComma());
        $('#searchForm').find('#pgNo').html(result.paging.pageNo.addComma());
        $('#searchForm').find('#endPgNo').html(result.paging.totalPage.addComma());
        cpnListOpt.api.setRowData(result.CouponList);
        gagaPaging.createPagination(result.paging);
    }

    //페이징
    $('#searchForm select[name=pageSize]').on('change', function() {
        $("#searchForm input[name=pageNo]").val('1');
        $('#btnSearch').click();
    });

    $("#btnNew").on("click", function(){
        $("#detailForm")[0].reset();
        setComma("detailForm", false);
        $("input[name=rdcpnGb][value=C]").prop('checked', true);
        onChangePdGb("C");
        $("select[name=dupUsableYn]").val("N");
        $("select[name=rdCpnPrefixGb]").val("R");
        setComma("detailForm", true);
    });

    $("#btnSave").on("click", function(){
        var formId = '#detailForm';
        var formJson = $(formId).serializeObject();

        if(gagajf.isNull(formJson.rdCpnNm)){
            mcxDialog.alert("쿠폰명을 입력해주세요");
            return;
        }

        if(gagajf.isNull(formJson.rdCpnIdQty) || formJson.rdCpnIdQty < 1){
            mcxDialog.alert("쿠폰생성수량을 입력해주세요");
            return;
        }

        if(formJson.rdcpnGb == "C"){
            if(gagajf.isNull(formJson.cpnId)){
                mcxDialog.alert("적용할 쿠폰ID를 입력해주세요");
                return;
            }
            if(gagajf.isNull(formJson.cpnCnt) || formJson.cpnCnt < 1){
                mcxDialog.alert("쿠폰발급수량을 입력해주세요");
                return;
            }
        }else if(formJson.rdcpnGb == "P"){
            if(gagajf.isNull(formJson.pointAmt)){
                mcxDialog.alert("적용할 포인트를 입력해주세요");
                return;
            }
            if(gagajf.isNull(formJson.pointExpireDt)){
                mcxDialog.alert("포인트만료일자를 입력해주세요");
                return;
            }
        }

        /*
                if(formJson.rdCpnPrefixGb == "S" && formJson.rdCpnIdQty > 1){
                    mcxDialog.alert("단일문자일 경우 쿠폰생성수량은 1개만 가능합니다.");
                    return;
                }
        */

        // 날짜 유효성 체크
        var st = formJson.regPossibleStdt.replaceAll("-", "");
        var ed = formJson.regPossibleEddt.replaceAll("-", "");

        if (Number(st) > Number(ed)) {
            mcxDialog.alert('등록시작일은 등록종료일보다 클 수 없습니다.');
            return;
        }

        setComma("detailForm", false); // 숫자타입 콤마 제거

        if(!gagajf.isNull(formJson.cpnId)){
            $("input[name=cpnId]").val($("input[name=cpnId]").val().toUpperCase());
        }
        if(!gagajf.isNull(formJson.rdCpnPrefix)){
            $("input[name=rdCpnPrefix]").val($("input[name=rdCpnPrefix]").val().toUpperCase());
        }

        mcxDialog.confirm('저장하시겠습니까?', {
            cancelBtnText: "취소",
            sureBtnText: "확인",
            sureBtnClick: function(){
                gagajf.ajaxFormSubmit($(formId).prop('action'), formId, fnSaveCallback);
            }
        });
    });

    function setComma(formId, pBoolean){
        //숫자타입 콤마 찍어주기
        $("#"+formId+" [data-valid-type=numeric]").each(function(){
            $(this).change(function(){
                if(pBoolean){
                    $(this).val($(this).val().addComma());
                }else{
                    $(this).val($(this).val().removeComma());
                }
            });
            if(pBoolean){
                $(this).val($(this).val().addComma());
            }else{
                $(this).val($(this).val().removeComma());
            }
        });
    }

    function fnSaveCallback(){
        $("#btnNew").trigger('click');
        //setComma("detailForm", true);
        fnSearch();
    }

    function fnCouponCreate(){
        cfnCouponCreatePopup();
    }

    function fnCouponCopy(){
        var selectedData = cpnListOpt.api.getSelectedRows();

        if (selectedData.length == 0) {
            mcxDialog.alert('선택된 행이 없습니다.');
            return;
        }
        if (selectedData.length > 1) {
            mcxDialog.alert('하나의 쿠폰만 선택하세요.');
            return;
        }
        var cpnId = selectedData[0].cpnId;
        var mode = "copy"
        var actionUrl = "/marketing/coupon/popup/form?cpnId="+cpnId;
        actionUrl += "&mode="+mode;
        cfnOpenModalPopup(actionUrl,'CouponCreatePopup');
    }

    function fnCouponDetail(cpnId){
        var actionUrl = "/marketing/coupon/popup/form?cpnId="+cpnId;
        cfnOpenModalPopup(actionUrl,'CouponCreatePopup');
    }

    function fnCpnUseDetail(cpnId){
        var actionUrl = "/marketing/coupon/cpnUseDetail/popup/form?cpnId="+cpnId;
        cfnOpenModalPopup(actionUrl,'CpnUseDetailPopup');
    }

    // 쿠폰조회 팝업
    var fnOpenCouponRetrievePopup = function(strReturnCode, strReturnName) {
        var oParam = new Object();
        oParam.returnCode = strReturnCode;
        oParam.returnName = strReturnName;
        cfnOpenCouponRetrievePopup($(strReturnName).val(), oParam);
    }

    /*유효기간구분온체인지이벤트*/
    function onChangePdGb(val){
        if(val == "C"){
            $(".rdcpnGbCpn").show();
            $(".rdcpnGbPnt").hide();
        }else{
            $(".rdcpnGbCpn").hide();
            $(".rdcpnGbPnt").show();
        }

    }

    function onChangePrefixGb(val){
        $("input[name=rdCpnPrefix]").val('');
        if(val == "S"){
            $("input[name=rdCpnPrefix]").attr("maxlength", 10);
            $("input[name=rdCpnPrefix]").attr("data-valid-type", "");
        }else{
            $("input[name=rdCpnPrefix]").attr("maxlength", 4);
        }

    }

    var fnCouponExcelDownLoad = function(){
        var selectedData = cpnListOpt.api.getSelectedRows();

        if (selectedData.length == 0) {
            mcxDialog.alert('선택된 행이 없습니다.');
            return;
        }

        gagaAgGrid.exportToExcel('쿠폰목록', cpnListOpt, true);
    }

    /*]]>*/
</script>

</html>