package com.bonus.core.customer.mq;

import com.bonus.core.common.redis.RedisUtil;
import com.bonus.core.common.utils.TenantContextHolder;
import com.bonus.core.customer.constants.CustCacheKey;
import com.bonus.core.data.dataset.Executors;
import com.bonus.core.device.android.constant.DeviceMqMessage;
import com.bonus.core.device.mq.MacMessage;
import com.bonus.core.order.mq.MqPayload;
import com.bonus.mq.MQListener;
import com.bonus.mq.MQMessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

@Component
@MQMessageListener(
   group = "customer-data-change-delay",
   topic = "customer",
   tag = "customer-data-change-delay"
)
public class DelayedMessageListener implements MQListener<MqPayload<CustomerMessageDTO>> {
   private static final Logger log = LoggerFactory.getLogger(DelayedMessageListener.class);
   private static final String formatter = "yyyy-MM-dd HH:mm:ss.SSS";
   private static final long repeatTimes = 2000L;

   @Override
   public void onMessage(MqPayload<CustomerMessageDTO> mqPayload) {
      Long tenantId = mqPayload.getTenantId();
      CustomerMessageDTO messageDTO = (CustomerMessageDTO)mqPayload.getData();

      try {
         Executors.doInTenant(tenantId, (status) -> {
            String updateKey = CustCacheKey.getTenantKey(messageDTO.getMessageType().name());
            String time = RedisUtil.getString(updateKey);
            if (time != null) {
               LocalDateTime redisTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
               LocalDateTime mqTime = LocalDateTime.parse(messageDTO.getDelayTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
               long secondsDifference = ChronoUnit.MILLIS.between(redisTime, mqTime);
               log.debug("[用户模块]商户:{},[{}]收到延迟消息时间差:{}毫秒", new Object[]{tenantId, messageDTO.getMessageType().getDesc(), secondsDifference});
               if (secondsDifference < 0L) {
                  Integer incr = RedisUtil.incr(updateKey + ":incr", 7200L);
                  log.info("[用户模块]商户:{},[{}]累计次数:{}", new Object[]{tenantId, messageDTO.getMessageType().getDesc(), incr});
                  if ((long)incr > 2000L) {
                     this.handleMessage(messageDTO.getMessageType());
                     RedisUtil.delete(updateKey + ":incr");
                  }

               } else {
                  this.handleMessage(messageDTO.getMessageType());
               }
            }
         });
      } catch (Exception var5) {
         log.error("消费失败:{}", var5.getMessage(), var5);
      }

   }

   public void handleMessage(DelayedMessageTypeEnum messageTypeEnum) {
      if (messageTypeEnum.equals(DelayedMessageTypeEnum.PERSON)) {
         MacMessage.updateDevicePersonalInfoTeantV2();
         DeviceMqMessage.deviceUpdatePersonalConfigV4();
      } else if (messageTypeEnum.equals(DelayedMessageTypeEnum.PHOTO)) {
         MacMessage.updateDevicePersonalInfoFeatureTeantV2();
         DeviceMqMessage.deviceUpdatePersonalFeatureConfigV4();
         DeviceMqMessage.deviceUpdatePersonalValidityConfigV4();
      } else if (messageTypeEnum.equals(DelayedMessageTypeEnum.CARD)) {
         DeviceMqMessage.deviceUpdateCardStatusConfigV4();
      } else if (messageTypeEnum.equals(DelayedMessageTypeEnum.EXPIRED)) {
         DeviceMqMessage.deviceUpdatePersonalValidityConfigV4();
      }

      log.info("[用户模块]商户:{},[{}]通知设备消息已发送", TenantContextHolder.getTenantId(), messageTypeEnum.getDesc());
   }
}
