package com.elab.spring.monitor;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.jay.monitor.data.client.MonitorSendProducer;
import com.jay.monitor.data.core.model.serializable.ServiceDataDTO;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 业务数据收集器
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/26 - 14:41
 */
public class JayMonitorServiceCollect implements ServiceMonitorDataCollect {

    @Override
    public Object send(String[] author, String methodName, String groupName, String key, String dataId, Object request,
        MonitorSupplier supplier) throws Exception {
        ServiceDataDTO dataDTO = new ServiceDataDTO();
        dataDTO.setDataId(dataId);
        dataDTO.setGroupName(groupName);
        dataDTO.setGroupKeyName(key);
        Map<String, Object> extMap = new HashMap<>();
        extMap.put("request", request);
        dataDTO.setCreateDate(new Date());
        dataDTO.setMethodName(methodName);
        // 回填请求参数
        dataDTO.setJsonContent(JSON.toJSONString(request));
        dataDTO.setAuthor(author);
        dataDTO.setLogId(Cat.getCurrentMessageId());
        Object response = null;
        Long start = System.currentTimeMillis();
        try {
            response = supplier.get();
            extMap.put("response", response);
            dataDTO.setStatus(1);
        } catch (Throwable e) {
            dataDTO.setStatus(-1);
            dataDTO.setErrorMessage(e.getMessage());
            StringWriter writer = new StringWriter(1024);
            e.printStackTrace(new PrintWriter(writer));
            dataDTO.setErrorStackTrace(writer.toString());
            throw e;
        } finally {
            dataDTO.setExtMap(extMap);
            Long requestTime = System.currentTimeMillis() - start;
            dataDTO.setRequestTime(requestTime);
            MonitorSendProducer.sendMsg(dataDTO);
        }
        return response;
    }
}
