package cn.axzo.msg.center.message.service.card.log;

import cn.axzo.msg.center.dal.CardDao;
import cn.axzo.msg.center.dal.CardLogDao;
import cn.axzo.msg.center.domain.entity.Card;
import cn.axzo.msg.center.domain.entity.CardLog;
import cn.axzo.msg.center.message.service.card.CardRequestContext;
import com.google.common.base.Throwables;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yanglin
 */
@Component
@RequiredArgsConstructor
public class CardLoggers {

    private final CardDao cardDao;
    private final CardLogDao cardLogDao;

    public CardLogger createLogger(CardRequestContext<?> requestContext, List<Card> cards) {
        return (operationContext, exception) -> {
            ArrayList<CardLog> logs = new ArrayList<>(cards.size());
            for (Card card : cardDao.reloadCards(cards)) {
                CardLog log = new CardLog();
                logs.add(log);
                log.setBizState(card.getBizState());
                log.setCardState(card.getCardState());
                log.setIdentityCode(card.getIdentityCode());
                log.setTemplateCode(card.getTemplateCode());
                log.setBizMessageId(card.getBizMessageId());
                log.setBizCode(card.getBizCode());
                log.setSubBizCode(card.getSubBizCode());
                log.setContext(operationContext);
                log.setBatchNo(requestContext.getBatchNo());
                log.setCardContent(card.getCardContent());
                log.setError(exception == null ? "" : Throwables.getStackTraceAsString(exception));
                log.addLogContent("request", requestContext.getRequest());
            }
            cardLogDao.saveBatch(logs);
        };
    }

}