package com.pdaaphm.biz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.pdaaphm.biz.service.IRedisLogService;
import com.pdaaphm.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description RedisLogService
 * @Author WGK
 * @Date 2023/10/18 18:13
 */
@Service
@Slf4j
public class RedisLogService implements IRedisLogService {

    @Autowired
    private RedisCache redisCache;

    @Override
    public String getLogInfo(String taskId) {
        List<String> logs = redisCache.getCacheList(taskId);
        if(CollectionUtils.isEmpty(logs)) {
            return null;
        }
        // 从头删除
        redisCache.leftPopList(taskId);
        return logs.get(0);
    }

    @Override
    public void info(String taskId, String megStr) {
        this.addInfo("INFO", taskId, megStr);
    }

    @Override
    public void error(String taskId, String megStr) {
        this.addInfo("ERROR", taskId, megStr);
    }

    private void addInfo(String level, String taskId, String megStr) {
        List<String> logs = new ArrayList<>();
        try {
            String message = String.format("<p style='color: #58e072'> %s: [%s] -> %s </p>", level, DateUtil.now(), megStr);
            if ("ERROR".equals(level)) {
                message = String.format("<p style='color: #e3270e'> %s: [%s] %s </p>", level, DateUtil.now(), megStr);
            }
            log.info(megStr);
            logs.add(message);
            redisCache.setCacheList(taskId, logs);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
