/**
 * 통화 로그 관리 - ag-Grid
 */
$(document).ready(function () {
    fn_initGrid();
    fn_init();
    fn_setToday();
    fn_loadCallLogList();
});

/* ============================================
   전역 변수
   ============================================ */
var gridApi = null;

/* ARS 메뉴 번호 → 텍스트 매핑 */
var arsMenuMap = {
    '1': '상담',
    '2': '예약',
    '3': '위치안내'
};

/* ============================================
   ag-Grid 초기화
   ============================================ */
function fn_initGrid() {
    var columnDefs = [
        {
            headerName: 'No',
            valueGetter: function (params) {
                return params.node.rowIndex + 1;
            },
            width: 60,
            maxWidth: 60,
            cellStyle: { textAlign: 'center' },
            suppressSizeToFit: true
        },
        {
            headerName: 'RECORD NO',
            field: 'recordNo',
            width: 100,
            maxWidth: 110,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '구분1',
            field: 'menuText',
            width: 100,
            maxWidth: 120,
            cellStyle: { textAlign: 'center' },
            valueGetter: function (params) {
                var d = params.data;
                if (!d) return '';
                if (d.bound === 'OUT') return 'OUT';
                if (d.callbackCid) return 'Call Back';
                return arsMenuMap[d.ring] || '';
            },
            cellRenderer: function (params) {
                if (!params.data) return '';
                if (params.data.bound === 'OUT') {
                    return '<span style="color:#0000ff;font-weight:600">OUT</span>';
                }
                if (params.data.callbackCid) {
                    return 'Call Back<br><small>' + params.data.callbackCid + '</small>';
                }
                return params.value || '';
            }
        },
        {
            headerName: '구분2',
            field: 'cType1',
            width: 65,
            maxWidth: 80,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '구분3',
            field: 'cType2',
            width: 80,
            maxWidth: 100,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '고객명',
            field: 'memberName',
            width: 90,
            maxWidth: 120,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '전화번호',
            field: 'cid',
            width: 120,
            maxWidth: 140,
            cellStyle: { textAlign: 'center' },
            valueFormatter: function (params) {
                return fn_formatPhone(params.value);
            }
        },
        {
            headerName: '전화 온 시간',
            field: 'regDate',
            width: 145,
            maxWidth: 160,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '통화 시작',
            field: 'linkDate',
            width: 145,
            maxWidth: 160,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '통화 종료',
            valueGetter: function (params) {
                if (!params.data) return '';
                return params.data.linkEndDate || params.data.bendDate || '';
            },
            width: 145,
            maxWidth: 160,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '상담 전화번호',
            field: 'linkCid',
            width: 110,
            maxWidth: 130,
            cellStyle: { textAlign: 'center' }
        },
        {
            headerName: '통화파일',
            field: 'recordNo',
            width: 80,
            maxWidth: 90,
            cellStyle: { textAlign: 'center' },
            cellRenderer: function (params) {
                if (!params.data || !params.data.recordNo || !params.data.linkDate) return '';
                var btn = '<button type="button" class="cl_play_btn" onclick="fn_playRecord(\'' + params.data.recordNo + '\')">▶</button>';
                return btn;
            }
        },
        {
            headerName: 'In Call',
            field: 'incallSel',
            width: 150,
            minWidth: 100,
            cellStyle: { textAlign: 'left' },
            cellRenderer: function (params) {
                var val = params.value;
                if (!val) return '';
                // incallSel은 '|=|값1|=||=|값2|=|' 형식
                var items = val.split('|=|').filter(function (v) { return v.trim() !== ''; });
                if (items.length === 0) return '';
                return items.map(function (item) {
                    return '<span class="cl_incall_badge">' + item + '</span>';
                }).join(' ');
            }
        },
        {
            headerName: '메모',
            field: 'callMsg',
            flex: 1,
            minWidth: 120,
            cellStyle: { textAlign: 'left', cursor: 'pointer' },
            cellRenderer: function (params) {
                var msg = params.value || '';
                // HTML 태그 제거하여 표시
                var plainText = msg.replace(/<[^>]+>/g, '').trim();
                if (plainText.length > 30) {
                    plainText = plainText.substring(0, 30) + '...';
                }
                return plainText || '<span style="color:#B5BDC4">클릭하여 메모 입력</span>';
            }
        }
    ];

    var gridOptions = {
        columnDefs: columnDefs,
        rowData: [],
        rowSelection: 'single',
        animateRows: true,
        headerHeight: 36,
        rowHeight: 40,
        suppressCellFocus: true,
        overlayNoRowsTemplate: '<span style="color:#B5BDC4; font-size:13px;">검색된 통화 내역이 없습니다.</span>',
        onCellClicked: function (event) {
            if (event.colDef.field === 'callMsg') {
                fn_openMemo(event.data);
            }
        },
        defaultColDef: {
            resizable: true,
            sortable: true
        }
    };

    var gridDiv = document.querySelector('#callLogGrid');
    gridApi = new agGrid.Grid(gridDiv, gridOptions);
    gridApi = gridOptions.api;
}

/* ============================================
   초기화 (이벤트 바인딩)
   ============================================ */
function fn_init() {
    $('#searchBtn').on('click', function () {
        fn_loadCallLogList();
    });

    $('#mCid').on('keypress', function (e) {
        if (e.which === 13) fn_loadCallLogList();
    });

    $('#sDate, #eDate').on('change', function () {
        // 날짜 변경 시 자동 검색하지 않음 (사용자가 조회 버튼 클릭)
    });
}

/* ============================================
   오늘 날짜 설정
   ============================================ */
function fn_setToday() {
    var today = fn_getDateStr(new Date());
    $('#sDate').val(today);
    $('#eDate').val(today);
}

/* ============================================
   날짜 단축 버튼
   ============================================ */
function fn_dayChk(type) {
    var now = new Date();
    var sDate, eDate;

    switch (type) {
        case 't': // 오늘
            sDate = new Date();
            eDate = new Date();
            break;
        case 'p': // 어제
            sDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
            eDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
            break;
        case 'w': // 이번주 (월요일~오늘)
            var dayOfWeek = now.getDay();
            var diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
            sDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff);
            eDate = new Date();
            break;
        case 'pw': // 지난주 (월요일~일요일)
            var dayOfWeek = now.getDay();
            var diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
            var thisMonday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff);
            sDate = new Date(thisMonday.getFullYear(), thisMonday.getMonth(), thisMonday.getDate() - 7);
            eDate = new Date(thisMonday.getFullYear(), thisMonday.getMonth(), thisMonday.getDate() - 1);
            break;
        case 'm': // 이번달
            sDate = new Date(now.getFullYear(), now.getMonth(), 1);
            eDate = new Date();
            break;
        case 'pm': // 지난달
            sDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
            eDate = new Date(now.getFullYear(), now.getMonth(), 0);
            break;
        default:
            return;
    }

    $('#sDate').val(fn_getDateStr(sDate));
    $('#eDate').val(fn_getDateStr(eDate));
    fn_loadCallLogList();
}

/* ============================================
   목록 조회
   ============================================ */
function fn_loadCallLogList() {
    var param = {
        sDate: $('#sDate').val(),
        eDate: $('#eDate').val(),
        callType: $('#callType').val(),
        callType1: $('#callType1').val(),
        callType2: $('#callType2').val(),
        mCid: $('#mCid').val().replace(/[^0-9]/g, ''),
        fulldnis: '',  // TODO: 매장별 수신번호 설정 필요
        menuClass: menuClass
    };

    $.ajax({
        url: '/callLog/getCallLogList.do',
        type: 'POST',
        data: param,
        dataType: 'json',
        success: function (data) {
            var rows = data.rows || [];
            gridApi.setRowData(rows);

            if (rows.length === 0) {
                gridApi.showNoRowsOverlay();
            }

            // 통계 업데이트
            fn_updateStats(data.stats);
        },
        error: function () {
            alert('목록 조회 중 오류가 발생하였습니다.');
        }
    });
}

/* ============================================
   통계 업데이트
   ============================================ */
function fn_updateStats(stats) {
    if (!stats) {
        $('#statTotal, #statIn, #statOut, #statType1, #statType2, #statType11, #statType12, #statType13').text('0');
        return;
    }

    $('#statTotal').text(fn_numberFormat(stats.totalCnt || 0));
    $('#statIn').text(fn_numberFormat(stats.inCnt || 0));
    $('#statOut').text(fn_numberFormat(stats.outCnt || 0));
    $('#statType1').text(fn_numberFormat(stats.type1Cnt || 0));
    $('#statType2').text(fn_numberFormat(stats.type2Cnt || 0));
    $('#statType11').text(fn_numberFormat(stats.type11Cnt || 0));
    $('#statType12').text(fn_numberFormat(stats.type12Cnt || 0));
    $('#statType13').text(fn_numberFormat(stats.type13Cnt || 0));
}

/* ============================================
   메모 팝업
   ============================================ */
function fn_openMemo(data) {
    if (!data || !data.recordNo) return;

    $('#memoRecordNoVal').val(data.recordNo);
    $('#memoRecordNo').text('RECORD NO: ' + data.recordNo);
    $('#memoContent').val(data.callMsg || '');
    $('#memoOverlay').fadeIn(200);
    $('#memoContent').focus();
}

function fn_closeMemo() {
    $('#memoOverlay').fadeOut(200);
}

function fn_saveMemo() {
    var recordNo = $('#memoRecordNoVal').val();
    var callMsg = $.trim($('#memoContent').val());

    if (!recordNo) return;

    var param = {
        recordNo: recordNo,
        callMsg: callMsg,
        menuClass: menuClass
    };

    $.ajax({
        url: '/callLog/saveCallMemo.do',
        type: 'POST',
        data: param,
        dataType: 'json',
        success: function (data) {
            alert(data.msgDesc || '저장되었습니다.');
            fn_closeMemo();
            fn_loadCallLogList();
        },
        error: function () {
            alert('메모 저장 중 오류가 발생하였습니다.');
        }
    });
}

/* ============================================
   유틸리티 함수
   ============================================ */
function fn_getDateStr(date) {
    var y = date.getFullYear();
    var m = ('0' + (date.getMonth() + 1)).slice(-2);
    var d = ('0' + date.getDate()).slice(-2);
    return y + '-' + m + '-' + d;
}

function fn_numberFormat(num) {
    if (!num && num !== 0) return '0';
    return Number(num).toLocaleString();
}

function fn_formatPhone(phone) {
    if (!phone) return '';
    phone = phone.replace(/[^0-9]/g, '');
    if (phone.length === 11) {
        return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
    } else if (phone.length === 10) {
        return phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    } else if (phone.length === 9) {
        return phone.replace(/(\d{2})(\d{3})(\d{4})/, '$1-$2-$3');
    }
    return phone;
}

/* ============================================
   녹음 파일 재생
   ============================================ */
function fn_playRecord(recordNo) {
    if (!recordNo) return;

    $.ajax({
        url: '/callLog/getRecordFileUrl.do',
        type: 'POST',
        data: { recordNo: recordNo },
        dataType: 'json',
        success: function (data) {
            if (data.success && data.recordUrl) {
                window.open(data.recordUrl, '_blank', 'width=400,height=200');
            } else {
                alert('녹음 파일을 불러올 수 없습니다.');
            }
        },
        error: function () {
            alert('녹음 파일 조회 중 오류가 발생하였습니다.');
        }
    });
}

