package cn.superdesk.uniorder.mq.consumer.superdeskapp.credit;


import cn.superdesk.uniorder.dao.entity.sys.SysOderUser;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysOderUserDubboConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class ReceiveServiceCreditConsumerHandler {

	@Autowired
	private SysOderUserDubboConsumerService sysOderUserDubboConsumerService;

	/**
	 * 基金 这个有测过吗?
	 *
	 * @param record
	 */
	@KafkaListener(topics = "${custom.fund.topic}")
	public void listenCreditdev(ConsumerRecord<?, ?> record) {

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

		log.info("-------------recieve message from {} topic-------------", topic);
		log.info("data.String:{}", record);
		log.info("key:{}", String.valueOf(record.key()));//消费的topic的分区
		log.info("partition:{}", String.valueOf(record.partition()));//消费的topic的分区
		log.info("offset:{}", String.valueOf(record.offset()));//消费者的位置
		log.info("get message from {} topic : {}", topic, record.value());//接收到的消息

		Optional<?>         kafkaMessage = Optional.ofNullable(record.value());
		String              messageStr   = (String) kafkaMessage.get();
		Map<String, Object> jsonMap      = com.alibaba.fastjson.JSONObject.parseObject(messageStr);

		try {
			SysOderUser orderUser = new SysOderUser();

			orderUser.setUserId(Long.decode(String.valueOf((Integer) jsonMap.get("id"))));
			BigDecimal fundBalance = new BigDecimal((String) jsonMap.get("credit"));

			orderUser.setFundBalance(fundBalance);

			if (fundBalance == null) {
				orderUser.setFundBalance(new BigDecimal("0"));
			}

			List<SysOderUser> listSysUser = sysOderUserDubboConsumerService.findByUserId(orderUser.getUserId());

			// 存在 update
			if (listSysUser.size() >= 1) {
				orderUser.setId(listSysUser.get(0).getId());
				sysOderUserDubboConsumerService.update(orderUser);
			}

		} catch (Exception e) {

			log.error("listenCreditdev error===>" + e.getMessage());
			log.error(e.getMessage(), e);

			e.printStackTrace();
		}
	}
}
