package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.log;

import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.mes.bean.MesServiceBusiScanLog;
import cn.estsh.i3plus.pojo.mes.repository.MesServiceBusiScanLogRepository;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@Data
public class MesServiceBusiScanLogService {
    private Logger LOGGER = null;

    private MesServiceBusiScanLogRepository mesServiceBusiScanLogRepository;
    private String orderNo = "";
    private String sn = "";
    private String organizeCode = "";
    private String userName = "";
    private String callClass = "";
    private String callFun = "";

    private static final String INFO = "INFO";
    private static final String ERROR = "ERROR";

    private List<MesServiceBusiScanLog> mesServiceBusiScanLogs = new ArrayList<>();

    public MesServiceBusiScanLogService() {
        mesServiceBusiScanLogs.clear();
    }

    public MesServiceBusiScanLogService(Class<?> clazz) {
        this();
        LOGGER = LoggerFactory.getLogger(clazz);
        this.callClass = clazz.getSimpleName();
    }

    //正常信息
    public void info(String msg) {
        saveToDb(msg, 0, INFO);
        LOGGER.info(msg);
    }

    public void info(String msg, long duration) {
        saveToDb(msg, Integer.parseInt(duration + ""), INFO);
        LOGGER.info(msg);
    }

    //错误日志
    public void error(String msg) {
        saveToDb(msg, 0, ERROR);
        LOGGER.error(msg);
    }

    /**
     * @param msg
     */
    public void saveToDb(String msg, Integer duration, String logType) {
        MesServiceBusiScanLog serviceLog = new MesServiceBusiScanLog();
        serviceLog.setOrderNo(this.orderNo);
        serviceLog.setSn(this.sn);
        serviceLog.setDuration(duration);
        serviceLog.setOrganizeCode(this.organizeCode);
        serviceLog.setCallClass(this.callClass);
        serviceLog.setCallFun(this.callFun);
        serviceLog.setMessage(msg);
        serviceLog.setLogType(logType);
        ConvertBean.serviceModelInitialize(serviceLog, this.userName);

        mesServiceBusiScanLogs.add(serviceLog);
    }

    /**
     * 保存所有日志到数据库
     */
    public void flush() {
        if (mesServiceBusiScanLogs != null && mesServiceBusiScanLogs.size() > 0) {
            if (mesServiceBusiScanLogRepository != null) {
                mesServiceBusiScanLogRepository.saveAll(mesServiceBusiScanLogs);
                mesServiceBusiScanLogs.clear();
            }
        }
    }
}
