package com.style24.batch.biz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.style24.batch.biz.dao.TsbBatchDao;
import com.style24.batch.support.env.TsbConstants;
import com.style24.persistence.domain.BatchLog;

import lombok.extern.slf4j.Slf4j;

/**
 * 배치 Service
 *
 * @author gagamel
 * @since 2020. 12. 2
 */
@Service
@Slf4j
public class TsbBatchService {

	@Autowired
	private TsbBatchDao batchDao;

	/**
	 * 배치정보 조회
	 * @param batchId - 배치ID
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	public BatchLog getBatchInfo(String batchId) {
		return batchDao.getBatchInfo(batchId);
	}

	/**
	 * 배치로그 생성
	 * @param batchId - 배치ID
	 * @return 배치로그일련번호
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	@Transactional("shopTxnManager")
	public Integer createBatchLog(String batchId) {
		BatchLog batchLog = new BatchLog();
		batchLog.setBatchId(batchId);
		batchLog.setRegNo(TsbConstants.REG_NO);

		// 배치로그 생성
		batchDao.createBatchLog(batchLog);

		// 배치상태 진행중으로 처리
		batchLog.setBatchStat("I");
		batchDao.updateBatchStatus(batchLog);

		return batchLog.getBatchLogSq();
	}

	/**
	 * 배치로그 종료 처리
	 * @param batchLogSq - 배치로그일련번호
	 * @param batchId - 배치ID
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	@Transactional("shopTxnManager")
	public void updateBatchLog(Integer batchLogSq, String batchId) {
		BatchLog batchLog = new BatchLog();
		batchLog.setRegNo(TsbConstants.REG_NO);
		batchLog.setBatchLogSq(batchLogSq);
		batchLog.setBatchStat("F");
		batchDao.updateBatchLog(batchLog);

		// 배치상태 완료로 처리
		batchLog.setBatchId(batchId);
		batchLog.setBatchStat("F");
		batchDao.updateBatchStatus(batchLog);
	}

	/**
	 * 배치로그 종료 처리
	 * @param batchLogSq - 배치로그일련번호
	 * @param batchId - 배치ID
	 * @param errorMsg - 에러 메시지
	 * @return
	 * @author gagamel
	 * @since 2021. 8. 26
	 */
	@Transactional("shopTxnManager")
	public void updateBatchLog(Integer batchLogSq, String batchId, String errorMsg) {
		BatchLog batchLog = new BatchLog();
		batchLog.setRegNo(TsbConstants.REG_NO);
		batchLog.setBatchLogSq(batchLogSq);
		batchLog.setBatchStat("E");
		batchLog.setErrorMsg(errorMsg);
		batchDao.updateBatchLog(batchLog);

		// 배치상태 실패로 처리
		batchLog.setBatchId(batchId);
		batchLog.setBatchStat("E");
		batchDao.updateBatchStatus(batchLog);
	}

}
