package com.elab.spring.intercept;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.elab.core.dao.model.SqlResult;
import com.elab.core.spring.method.SQLPostProcess;
import com.elab.core.sql.config.SqlCommandType;
import com.elab.core.utils.DataUtils;
import com.jay.monitor.data.client.MonitorSendProducer;
import com.jay.monitor.data.core.model.serializable.SQLMonitorDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * SQL 监控回调借口
 * <p>
 * author lkx
 */
public class SQLMonitorPostCallback implements SQLPostProcess {

    @Override
    public void callback(SqlResult sqlResult) {
        SQLMonitorDTO sqlMonitorDTO = new SQLMonitorDTO();

        BeanUtils.copyProperties(sqlResult, sqlMonitorDTO);

        if (SqlCommandType.INSERT.name().equals(sqlMonitorDTO.getCommandType())) {
            sqlMonitorDTO.setDataId(sqlResult.getResult() + "");
            sqlMonitorDTO.setAffectedRows(1);
        } else if (SqlCommandType.UPDATE.name().equals(sqlMonitorDTO.getCommandType())) {
            // 从请求参数中抓取可靠信息
            Object requestParams = sqlResult.getRequestParams();
            try {
                String id = org.apache.commons.beanutils.BeanUtils.getProperty(requestParams, "id");
                sqlMonitorDTO.setDataId(id);
                sqlMonitorDTO.setAffectedRows(DataUtils.getDefaultValue(sqlResult.getResult(), 0));
            } catch (Exception e) {

            }
        }

        sqlMonitorDTO.setJsonContent(JSON.toJSONString(sqlResult.getRequestParams()));
        sqlMonitorDTO.setResult(sqlResult.getResult());
        sqlMonitorDTO.setLogId(Cat.getCurrentMessageId());
        sqlMonitorDTO.setCreateDate(new Date());
        sqlMonitorDTO.setCommandType(sqlResult.getCommandType());
        sqlMonitorDTO.setRequestTime(sqlResult.getTime());
        MonitorSendProducer.sendMsg(sqlMonitorDTO);
    }
}
