package cn.superdesk.uniorder.interceptor.logger;


import cn.superdesk.uniorder.dto.dubbo.kafka.KafkaConsumerRecordParams;
import cn.superdesk.uniorder.dubbo.consumer.kafka.KafkaConsumerRecordDubboConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Optional;


/**
 * @Description: 切面-日志
 * @Author: linjinyu
 * @CreateDate: 5/13/20 10:16 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 5/13/20 10:16 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Aspect
@Component
public class KafkaLoggerAspect {


	@Value("${spring.kafka.consumer.group-id}")
	private static String KAFKA_GROUP;

	@Autowired
	private KafkaConsumerRecordDubboConsumerService kafkaConsumerRecordDubboConsumerService;


	/**
	 * 切点定义 包路径 ..* 类 .* 方法 listen* 参数
	 */
	@Pointcut(value = "execution(* cn.superdesk.uniorder.mq.consumer..*.*.listen*(org.apache.kafka.clients.consumer.ConsumerRecord))")
	public void cutOffPoint() {

		log.info("KafkaLogAspect->cutOffPoint@Pointcut");

	}

	@Before("cutOffPoint() && args(record)")
	public void doBefore(ConsumerRecord<?, ?> record) {

		log.info("KafkaLogAspect->doBefore@Before");
		info(record);
	}

//	@After("cutOffPoint()")
//	public void doAfter() {
//		log.info("KafkaLogAspect->doAfter@After");
//	}

	ThreadLocal<Long> startTime = new ThreadLocal<>();

//	@Around("cutOffPoint()")
//	public Object doAround(ProceedingJoinPoint pjp) {
//
//		startTime.set(System.currentTimeMillis());
//
//		log.info("KafkaLogAspect->doAround@Around");
//
//		Object obj;
//
//		try {
//			obj = pjp.proceed();
//			log.info("执行返回值 : " + obj);
//			log.info(pjp.getSignature().getName() + "方法执行耗时: " + (System.currentTimeMillis()-startTime.get()));
//		} catch (Throwable throwable) {
//			obj = throwable.toString();
//		}
//
//		return obj;
//	}

	/**
	 * 执行完请求可以做的
	 *
	 * @param result
	 * @throws Throwable
	 */
//	@AfterReturning(returning = "result", pointcut = "cutOffPoint()")
//	public void doAfterReturning(Object result) throws Throwable {
//
//		log.info("KafkaLogAspect->doAfterReturning@AfterReturning {}", result.toString());
//	}

	/**
	 * 只接收 ConsumerRecord<String, String>
	 *
	 * @param record
	 */
	public void info(ConsumerRecord<?, ?> record) {

		// 消费的topic
		String topic = record.topic();

		log.info("\n\n\n\n------------- KafkaLogUtils info start -------------" +
						"\nrecord.String:{}" +
						"\ntopic:        {}" +
						"\ngroup_id:     {}" +
						"\npartition:    {}" +
						"\noffset:       {}" +
						"\nmessage_key:  {}" +
						"\nmessage_body: {}",
				record,
				topic,
				KAFKA_GROUP,
				String.valueOf(record.partition()),
				String.valueOf(record.offset()),
				String.valueOf(record.key()),
				record.value()
		);


		Optional<?> kafkaMessage = Optional.ofNullable(record.value());
		if (kafkaMessage.isPresent()) {


//			log.info("kafka-{}-{}", "Aspect", JsonUtils.toJson(kafkaMessage));

			Object message = kafkaMessage.get();
//			System.out.println("----msg\n" + record);
//			System.out.println("----key\n" + record.key());
//			System.out.println("----body\n" + message);


			KafkaConsumerRecordParams params = new KafkaConsumerRecordParams();

			params.setTopic(topic);
			params.setGroupId("");
			params.setPartitions(Integer.valueOf(record.partition()));
			params.setOffset(Long.valueOf(record.offset()));
			params.setCreateTime(System.currentTimeMillis());
			params.setSerializedKeySize(Long.valueOf(record.serializedKeySize()));
			params.setSerializedValueSize(Long.valueOf(record.serializedValueSize()));
			params.setMessageKey(String.valueOf(record.key()));
			params.setMessageBody(String.valueOf(message));


			kafkaConsumerRecordDubboConsumerService.addObj(params);
		}

		log.info("\n------------- KafkaLogUtils info  end  -------------\n\n\n");

	}
}
