/**
 * 문자 상용구 관리 - ag-Grid
 */
$(document).ready(function () {
	fn_initGrid();
	fn_init();
	fn_loadTemplateList();
});

/* ============================================
   전역 변수
   ============================================ */
var gridApi = null;
var currentMode = '';  // 'new' | 'edit'
var currentTemplateId = '';

/* ============================================
   ag-Grid 초기화
   ============================================ */
function fn_initGrid() {
	var columnDefs = [
		{
			headerName: 'No',
			valueGetter: function (params) {
				return params.node.rowIndex + 1;
			},
			width: 55,
			maxWidth: 55,
			cellStyle: { textAlign: 'center' },
			suppressSizeToFit: true
		},
		{
			headerName: '제목',
			field: 'title',
			flex: 2,
			minWidth: 120,
			cellStyle: { textAlign: 'left' }
		},
		{
			headerName: '등록자',
			field: 'regName',
			width: 80,
			maxWidth: 100,
			cellStyle: { textAlign: 'center' }
		},
		{
			headerName: '등록일',
			field: 'regDate',
			width: 100,
			maxWidth: 120,
			cellStyle: { textAlign: 'center' }
		}
	];

	var gridOptions = {
		columnDefs: columnDefs,
		rowData: [],
		rowSelection: 'single',
		animateRows: true,
		headerHeight: 36,
		rowHeight: 38,
		suppressCellFocus: true,
		overlayNoRowsTemplate: '<span style="color:#B5BDC4; font-size:13px;">등록된 상용구가 없습니다.</span>',
		onRowClicked: function (event) {
			var id = event.data.muSmsTemplateId;
			if (id) fn_selectTemplate(id);
		},
		defaultColDef: {
			resizable: true,
			sortable: true
		}
	};

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

/* ============================================
   초기화
   ============================================ */
function fn_init() {
	$('#searchBtn').on('click', function () {
		fn_loadTemplateList();
	});

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

	$('#newTemplateBtn').on('click', function () {
		fn_newTemplate();
	});

	$('#saveBtn').on('click', function () {
		fn_saveTemplate();
	});

	$('#deleteBtn').on('click', function () {
		fn_deleteTemplate();
	});

	$('#cancelBtn').on('click', function () {
		fn_cancelEdit();
	});

	$('#templateContent').on('input', function () {
		fn_updateByteCount();
	});
}

/* ============================================
   목록 조회
   ============================================ */
function fn_loadTemplateList() {
	var param = {
		searchKeyword: $('#searchKeyword').val(),
		menuClass: menuClass
	};

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

			if (rows.length === 0) {
				gridApi.showNoRowsOverlay();
			}
		},
		error: function () {
			alert('목록 조회 중 오류가 발생하였습니다.');
		}
	});
}

/* ============================================
   상세 조회
   ============================================ */
function fn_selectTemplate(templateId) {
	var param = {
		muSmsTemplateId: templateId,
		menuClass: menuClass
	};

	$.ajax({
		url: '/smsTemplate/getSmsTemplate.do',
		type: 'POST',
		data: param,
		dataType: 'json',
		success: function (data) {
			if (data.data) {
				fn_showDetail(data.data);
			} else {
				alert(data.msgDesc || '상세 조회에 실패하였습니다.');
			}
		},
		error: function () {
			alert('상세 조회 중 오류가 발생하였습니다.');
		}
	});
}

function fn_showDetail(detail) {
	currentMode = 'edit';
	currentTemplateId = detail.muSmsTemplateId;

	$('#detailTitle').text('상용구 수정');
	$('#muSmsTemplateId').val(detail.muSmsTemplateId);
	$('#templateTitle').val(detail.title || '');
	$('#templateContent').val(detail.content || '');
	$('#regName').text(detail.regName || '-');
	$('#regDate').text(detail.regDate || '-');
	$('#modDate').text(detail.modDate || '-');

	$('#infoRow').show();
	$('#deleteBtn').show();
	$('#emptyState').hide();
	$('#detailForm').show();

	fn_updateByteCount();
}

/* ============================================
   새 상용구
   ============================================ */
function fn_newTemplate() {
	currentMode = 'new';
	currentTemplateId = '';

	$('#detailTitle').text('상용구 등록');
	$('#muSmsTemplateId').val('');
	$('#templateTitle').val('');
	$('#templateContent').val('');

	$('#infoRow').hide();
	$('#deleteBtn').hide();
	$('#emptyState').hide();
	$('#detailForm').show();

	fn_updateByteCount();

	gridApi.deselectAll();
	$('#templateTitle').focus();
}

/* ============================================
   취소
   ============================================ */
function fn_cancelEdit() {
	currentMode = '';
	currentTemplateId = '';

	$('#detailForm').hide();
	$('#emptyState').show();

	gridApi.deselectAll();
}

/* ============================================
   저장 (등록/수정)
   ============================================ */
function fn_saveTemplate() {
	var title = $.trim($('#templateTitle').val());
	var content = $.trim($('#templateContent').val());

	if (!title) {
		alert('제목을 입력하세요.');
		$('#templateTitle').focus();
		return;
	}

	if (!content) {
		alert('내용을 입력하세요.');
		$('#templateContent').focus();
		return;
	}

	var url = '';
	var param = {
		title: title,
		content: content,
		menuClass: menuClass
	};

	if (currentMode === 'new') {
		url = '/smsTemplate/putSmsTemplate.do';
	} else if (currentMode === 'edit') {
		url = '/smsTemplate/modSmsTemplate.do';
		param.muSmsTemplateId = currentTemplateId;
	}

	if (!url) return;

	$.ajax({
		url: url,
		type: 'POST',
		data: param,
		dataType: 'json',
		success: function (data) {
			alert(data.msgDesc || '처리되었습니다.');
			fn_cancelEdit();
			fn_loadTemplateList();
		},
		error: function () {
			alert('저장 중 오류가 발생하였습니다.');
		}
	});
}

/* ============================================
   삭제
   ============================================ */
function fn_deleteTemplate() {
	if (!currentTemplateId) return;
	if (!confirm('이 상용구를 삭제하시겠습니까?')) return;

	var param = {
		muSmsTemplateId: currentTemplateId,
		menuClass: menuClass
	};

	$.ajax({
		url: '/smsTemplate/delSmsTemplate.do',
		type: 'POST',
		data: param,
		dataType: 'json',
		success: function (data) {
			alert(data.msgDesc || '삭제되었습니다.');
			fn_cancelEdit();
			fn_loadTemplateList();
		},
		error: function () {
			alert('삭제 중 오류가 발생하였습니다.');
		}
	});
}

/* ============================================
   바이트 카운트
   ============================================ */
function fn_updateByteCount() {
	var content = $('#templateContent').val() || '';
	var byteLen = fn_getByteLength(content);

	$('#byteCount').text(byteLen);

	var $badge = $('#typeBadge');
	if (byteLen > 90) {
		$badge.text('LMS').removeClass('sms').addClass('lms');
	} else {
		$badge.text('SMS').removeClass('lms').addClass('sms');
	}
}

function fn_getByteLength(str) {
	var byte = 0;
	for (var i = 0; i < str.length; i++) {
		if (str.charCodeAt(i) <= 0x7F) {
			byte += 1;
		} else {
			byte += 2;
		}
	}
	return byte;
}
