// $(document).ready(function() {
function fn_init(){
    fn_selectAgreementList();
}
document.getElementById('downLoadBtn').addEventListener('click',()=>{
    fn_downloadAgreementExcel();
});
document.getElementById('produceBtn').addEventListener('click',()=>{
    fn_insertAgreementPopup();
});

/****************************************************************************
 * 고객 신체기록 리스트 조회
 ****************************************************************************/
function fn_selectAgreementList(){
    let formData = new FormData();
    formData.append("muUserId",muUserId);
    formData.append("userStart",userStart);
    formData.append("userLimit",userLimit);
    formData.append("menuClass", menuClass);

    $.ajax({
        url: encodeURI('/webuser/selectUserAgreementList.do'),
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                muUserData=data.rows[0];
                userTotalCount  =muUserData.totalCount;
                userTotalPages = Math.ceil(userTotalCount/userLimit);
                document.getElementById("userName").innerHTML = `${muUserData.userName}<span id="latestWriteDate"></span>`;

                if(0<userTotalCount){
                    let latestWriteDate = `(${muUserData.latestWriteDate})`;
                    document.getElementById("latestWriteDate").textContent=latestWriteDate
                }

                if(0<userTotalCount){
                    userAgGridData = data.rows;
                    userGridOptions.api.setRowData(userAgGridData);
                    //페이징 처리
                    window.pagObj = $('#userPagination').twbsPagination({
                        startPage    : ((userStart/userLimit)+1),
                        totalPages   : (userTotalPages==0)?1:userTotalPages,
                        visiblePages : 10,
                        initiateStartPageClick: false,
                        prev         : '<img src="/image/web/page_navigation_arrow.svg" alt="prev">',
                        next         : '<img src="/image/web/page_navigation_arrow.svg" alt="next">',
                        first        : '',
                        last         : '',
                        onPageClick: function (event, page) {
                            fn_userPagination(page);
                        }
                    }).on('page', function (event, page) {
                        //console.info(page + ' (from event listening)');
                    });

                }
            }else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
        },
        beforeSend:function(){
        },
        complete:function(){
        }
    });
}
/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_userPagination(param){
    userStart = (parseInt(param)-1)*userLimit;
    fn_selectAgreementList();
}

/****************************************************************************
 * 컬럼명 클릭(재정렬)
 ****************************************************************************/
function fn_userSearch(param){
    if("A"!=param && "Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_userPaginReset();
    fn_selectAgreementList();
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadAgreementExcel(){
    if("Y"==downloadUseYn){
        // 수정가능
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&userSort="+userSort;
        pagingParam    += "&userDir="+userDir;
        pagingParam    += "&userStart="+userStart;
        pagingParam    += "&userLimit="+userLimit;
        pagingParam    += "&muUserId="+muUserId;

        let url = encodeURI("/webuser/downloadAgreementExcel.do"+pagingParam);
        $("#excelForm").prop("action",url);
        $("#excelForm").submit();
    }
    else{
        modalEvent.warning("", "내려받기 권한이 없습니다.");
        return false;
    }
}

let userColumnDefs = [
    /*{field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},*/
    {field: "rowNum", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
    {field: "type", headerName:"동의서", minWidth:1009, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    {field: "agreeYnName", headerName:"동의여부",minWidth:120, maxWidth:120},
    {field: "renewalCycle", headerName:"갱신주기(개월)",minWidth:150, maxWidth:150},
    {field: "expirationDate", headerName:"만료일",minWidth:120, maxWidth:120},
    {field: "writeDate", headerName:"작성일자",minWidth:120, maxWidth:120}
];

let userGridOptions = {
    suppressRowTransform: true,
    columnDefs: userColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: false,		// 그리드에서 데이터 수정
        cellStyle:{textAlign:'left',fontSize:'14px',padding:'10'},
        //suppressSizeToFit:true,		//자동 맞춤
        //enableRowGroup: true,		// 그룹 묶음
        enablePivot: true,
        enableValue : true
    },

    //suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
    headerHeight : 41, // header 높이
    rowHeight : 41, // row 높이
    rowData : userAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple', // row 다중 선택
    debug : false,
    onCellClicked: function(event){ //셀 클릭 이벤트
        /* alert(event.column.colId); */
		if(event.column.colId=='type'){
			fn_selectAgreementPopup(event.data.muUserAgreementId);
		}
    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        userSelectId = '';

        for(let i=0; i<selectRows.length; i++){
            userSelectId += selectRows[i].muUserId + ",";
        }

        userSelectId = userSelectId.substring(0, userSelectId.lastIndexOf(','));
    },
    onSortChanged: function(event){
        //정렬
        userSort = ''; //기존 정렬 초기화
        let columnArr = event.columnApi.getColumnState();
        if(0<columnArr.length){

            //sort index 순으로 재정렬
            columnArr.sort(function(a,b){
                return a.sortIndex - b.sortIndex;
            });


            let nullCnt = 0;
            for(let i=0; i<columnArr.length; i++){
                let gridSortModel = columnArr[i].colId;
                let gridSort = columnArr[i].sort;

                if(gridSort != null){
                    userStart = 0;

                    userSort += gridSortModel+' '+ gridSort + ',';

                }else{
                    nullCnt++;

                    if(nullCnt == columnArr.length){
                        userSort = '';
                        userDir = '';

                        userStart = 0;
                    }
                }
            }
        }

        userSort = userSort.substring(0,userSort.lastIndexOf( ",")); //맨끝 콤마 지우기

        fn_userSearch();
    }
};

// lookup the container we want the Grid to use
let userGridDiv = document.querySelector('#userGrid');

// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(userGridDiv, userGridOptions);
/****************************************************************************
 * 고객 동의서 리스트 등록팝업
 ****************************************************************************/
function fn_insertAgreementPopup() {
    if("Y"!=insertUseYn){
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    let reqParam =  {'muUserId':muUserId};
    agreementInsertModal.popup(function(obj, reqParam) {
        fn_selectAgreementList();
    }, reqParam);
}

/****************************************************************************
 * 고객 동의서 조회 팝업
 ****************************************************************************/
function fn_selectAgreementPopup(param) {
    if("Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }
    
    if(!fn_emptyCheck(param)){
        modalEvent.warning("", "동의서 정보가 없습니다.");
        return false;
    }

    let reqParam =  {'muUserAgreementId':param};
    agreementSelectModal.popup(function(obj, reqParam) {
        fn_selectAgreementList();
    }, reqParam);
}

fn_init();
