/****************************************************************************
 * 고객 정보 리스트 조회
 ****************************************************************************/
function fn_selectListUserJson() {

    let formData = new FormData();
    formData.append("userSearchKeywordParam", userSearchKeywordParam);
    formData.append("userSort", userSort);
    formData.append("userStart", userStart);
    formData.append("userLimit", userLimit);
    formData.append("menuClass", menuClass);
    formData.append("userType", search_userType);
    formData.append("userTypeCode", search_userTypeCode);
    formData.append("nationality", search_nationality);
    formData.append("nationalityCode", search_nationalityCode);
    formData.append("membershipYn", search_membershipYn);
    formData.append("appUseYn", search_appUseYn);

    $.ajax({
        url: encodeURI('/webuser/selectListUser.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function (data) {
            if ('0' == data.msgCode) {
                userTotalCount = data.totalCount;
                $(".total").text(userTotalCount+'명');

                userTotalPages = Math.ceil(userTotalCount / userLimit);
                userAgGridData = data.rows.map(item => {
                    if (item.phoneNumber) {
                        item.phoneNumber = fn_setFormatPhone(item.phoneNumber)
                    }
                    if (item.phoneNumber2) {
                        item.phoneNumber2 = fn_setFormatPhone(item.phoneNumber2)
                    }
                    return item;
                });
                userGridOptions.api.setRowData(userAgGridData);

                if (0 < data.rows.length) {

                    //페이징 처리
                    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) {
                    });

                }
            } else {
                modalEvent.danger("조회 오류", data.msgDesc);
            }

        },
        error: function (xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {
            // 로딩열기
            userGridOptions.api.showLoadingOverlay();
        },
        complete: function () {
        },
    });
}
/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_userPagination(param){
    userStart = (parseInt(param)-1)*userLimit;
    fn_selectListUserJson();
}


/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_userSearch(param) {
    if("A"!=param && "Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_userPaginReset();

    search_userType         = ($("#userType .option_list_item.selected").attr('id') || '').split('_')[1] || '';
    search_userTypeCode     = $("#userType .option_list_item.selected").data('code') || '';
    search_nationality      = ($("#nationality .option_list_item.selected").attr('id') || '').split('_')[1] || '';
    search_nationalityCode  = $("#nationality .option_list_item.selected").data('code') || '';
    search_membershipYn     = $("#membershipYn .option_list_item.selected").attr('value') || '';
    search_appUseYn         = $("#appUseYn .option_list_item.selected").attr('value') || '';
    userSearchKeywordParam  = $("#txt_userSearchKeyword").val() || '';


    fn_selectListUserJson();
}
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_userEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            fn_userSearch();
        }
    }else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            fn_userSearch();
        }
    }
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadUserExcel() {
    if ("Y" == downloadUseYn) {
        // 수정가능
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&userSearchKeywordParam=" + userSearchKeywordParam;
        pagingParam += "&userSort=" + userSort;
        pagingParam += "&userDir="+userDir;
        pagingParam += "&userStart=" + userStart;
        pagingParam += "&userLimit=" + userLimit;
        pagingParam += "&userTypeCode=" + (search_userTypeCode ?? "");
        pagingParam += "&userType=" + (search_userType ?? "");
        pagingParam += "&nationalityCode=" + (search_nationalityCode ?? "");
        pagingParam += "&nationality=" + (search_nationality ?? "");
        pagingParam += "&membershipYn=" + (search_membershipYn ?? "");
        pagingParam += "&appUseYn=" + (search_appUseYn ?? "");

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

/****************************************************************************
 * 고객등록
 ****************************************************************************/
function fn_insertUserPopup() {
    if ("Y" != insertUseYn) {
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    let reqParam = {};
    userInsertModal.popup(function (obj, reqParam) {
    }, reqParam);
}
/****************************************************************************
 * 추천인 팝업
 ****************************************************************************/
function listOpen(){
    let reqParam = {};
    userIntroSelectModal.popup(function (obj, reqParam) {
        document.getElementById('recommendId').dataset.userId=obj.muUserId;
        document.getElementById('recommendId').value = obj.userName;
    }, reqParam);
}

/****************************************************************************
 * 수정 화면으로 이동.
 ****************************************************************************/
function fn_updateUserIntro(param) {
    if ("Y" == updateUseYn || "Y" == selectUseYn) {
        // 수정가능
        let pagingParam = "?muUserId=" + param;
        pagingParam    += "&userSearchKeywordParam="+userSearchKeywordParam;
        pagingParam    += "&userSort="+userSort;
        pagingParam    += "&userDir="+userDir;
        pagingParam    += "&userStart="+userStart;
        pagingParam    += "&userLimit="+userLimit;
        pagingParam    += "&nationality="+search_nationality??'';
        pagingParam    += "&userType="+search_userType??'';
        pagingParam    += "&membershipYn="+search_membershipYn??'';

        fn_leftFormAction2('0201010101', "/webuser/updateUserIntro.do" + pagingParam);
    } else {
        modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
        return false;
    }
}

function userTypeCellRenderer(params) {
    if(!params.value)
        return
        if('T'===params.value)
            return '간편예약고객';
        if('Y'===params.value||''===params.value)
            return '-';
        else
            return `<img src="${params.value.replace("C:", "")}" alt="고객구분">`;
}

let userColumnDefs = [
        {
            field: "checkbox",
            headerName: "",
            minWidth: 55,
            maxWidth: 55,
            headerCheckboxSelection: true,
            checkboxSelection: true
        },
        {field: "rowNum", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
        {field: "userName", headerName: "고객명", minWidth: 130,maxWidth:200, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
        {field: "nationality", headerName: "국적", minWidth: 90, maxWidth: 90},
        {field: "birthday", headerName: "생년월일", minWidth: 100, maxWidth: 100},
        {field: "age", headerName: "나이", minWidth: 70, maxWidth: 70},
        {field: "gender", headerName: "성별", minWidth: 70,maxWidth: 70},
        {field: "userType", headerName: "고객구분", minWidth: 65, maxWidth: 90, cellRenderer: userTypeCellRenderer},
        {field: "phoneNumber", headerName: "연락처", minWidth: 140, maxWidth: 150},
        {field: "membershipYn", headerName: "멤버십", minWidth: 100, maxWidth: 100},
        {field: "etc", headerName: "특이사항", minWidth: 227},
        {field: "memo", headerName: "고객메모", minWidth: 230},
        {field: "lastVisitDate", headerName: "최근내원", minWidth: 100, maxWidth: 100},
        {field: "appUseYn", headerName: "앱 가입상태", minWidth: 100, maxWidth: 100}
];

// let the grid know which columns and what data to use
let userGridOptions = {
    suppressRowTransform: true,
    columnDefs: userColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: true,		// 그리드에서 데이터 수정
        cellStyle: {textAlign: 'left', fontSize: '14px', padding: '0'},
        //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 == 'userName') {
            fn_updateUserIntro(event.data.muUserId);
        }
    },
    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();
    }
};

let userGridDiv = document.querySelector('#userGrid');

new agGrid.Grid(userGridDiv, userGridOptions);

function fn_setSelectBox(num){
    let category=fn_selectCategoryList();
    for(let i = 0; i < num; i++){
        let categoryCode     = category[i].categoryCode;
        // if(num>2){
        //     fn_selectModalOtherOption(categoryCode)
        // }else{
        //     fn_selectListOtherOption(categoryCode);
        // }
        fn_selectModalOtherOption2(categoryCode)
    }
}
document.addEventListener("DOMContentLoaded", function() {
    fn_isForeignerEvent();
    fn_setSelectBox(2);
    fn_clickEvent();
    $(`#userType .option_list_item[id="${search_userType}"]`).click();
    $(`#nationality .option_list_item[id="${search_nationality}"]`).click();
    $(`#membershipYn .option_list_item[value="${search_membershipYn}"]`).click();
    $("#txt_userSearchKeyword").val(decodeURIComponent(userSearchKeywordParam));
    fn_userSearch();

});
document.getElementById("downLoadBtn").addEventListener('click',()=>{
    fn_downloadUserExcel();
});
document.getElementById("userBtn").addEventListener('click',()=>{
    fn_insertUserPopup();
});
document.getElementById("searchBtn").addEventListener('click',()=>{
    fn_userSearch();
});
document.getElementById("txt_userSearchKeyword").addEventListener('keypress',(e)=>{
    fn_userEnter(e);
});
