package com.bonus.canteen.core.order.mq.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bonus.canteen.core.common.constant.LeMqConstant;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.JacksonUtil;
import com.bonus.canteen.core.common.utils.LogUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.data.dataset.Executors;
import com.bonus.canteen.core.order.common.business.OrderPlaceBusiness;
import com.bonus.canteen.core.order.common.business.OrderResultBusiness;
import com.bonus.canteen.core.order.common.constants.DishesStateEnum;
import com.bonus.canteen.core.order.common.constants.OrderCacheConstants;
import com.bonus.canteen.core.order.common.constants.OrderErrorTypeEnum;
import com.bonus.canteen.core.order.common.model.OrderInfo;
import com.bonus.canteen.core.order.common.service.OrderErrorLogService;
import com.bonus.canteen.core.order.common.service.OrderInfoService;
import com.bonus.canteen.core.order.mq.MqPayload;
import com.bonus.canteen.core.order.mq.MqUtil;
import com.bonus.canteen.core.order.mq.po.*;
import com.bonus.canteen.core.pay.common.constants.PayStateEnum;
import com.bonus.canteen.core.pay.common.constants.TradeTypeEnum;
import com.bonus.canteen.core.pay.common.po.PayResultPO;
import com.bonus.canteen.core.pay.common.po.RefundResultPO;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.BiConsumer;

@Service
public class OrderMqHandler {
   private static final Logger log = LoggerFactory.getLogger(OrderMqHandler.class);
   @Lazy
   @Autowired
   private OrderPlaceBusiness orderPlaceBusiness;
   @Lazy
   @Autowired
   private OrderResultBusiness orderResultBusiness;
   @Lazy
   @Autowired
   protected OrderInfoService orderInfoService;
//   @Lazy
//   @Autowired
//   protected OrderPhotoService orderPhotoService;
   @Lazy
   @Autowired
   protected OrderErrorLogService orderErrorLogService;
//   @Lazy
//   @Autowired
//   protected OrderDeviceApi orderDeviceApi;
//   @Lazy
//   @Autowired
//   protected MacWeighBindService macWeighBindService;
//   @Lazy
//   @Autowired
//   private OrderWeightBusiness orderWeightBusiness;
//   @Lazy
//   @Autowired
//   private OrderPayApi orderPayApi;

   public <T> void handleMessage(MqPayload<String> payload, Class<T> clz, BiConsumer<OrderMqHandler, T> handleFunc) {
      try {
         log.info("[订单消息]收到消息 {}", payload);
         T payloadData = JacksonUtil.readValue((String)payload.getData(), clz);
         if (payloadData != null) {
            Executors.doInTenant(payload.getTenantId(), (s) -> {
               handleFunc.accept(this, payloadData);
            });
         } else {
            log.error("[订单消息]解析失败");
         }
      } catch (Exception var5) {
         log.error("[订单消息]处理异常", var5);
      }

   }

//   public void orderAsyncSave(OrderSavePO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      RLock lock = RedisUtil.getLock(OrderCacheConstants.orderCacheSaveLockKey(payload.getMacOrderId()));
//      lock.lock();
//
//      try {
//         log.info("[订单异步保存]MQ消费：开始");
//         if (CollUtil.isNotEmpty(payload.getOrderInfoList()) && this.orderInfoService.existOrderId(((OrderInfo)payload.getOrderInfoList().get(0)).getOrderId(), ((OrderInfo)payload.getOrderInfoList().get(0)).getOrderDate())) {
//            log.warn("[订单异步保存]MQ消费：订单已存在，不再保存：{}", payload.getMacOrderId());
//         } else {
//            this.orderResultBusiness.asyncSaveHandler(payload);
//         }
//
//         log.info("[订单异步保存]MQ消费：消息消费完成");
//      } catch (Exception var12) {
//         log.info("[订单异步保存]MQ消费：处理异常", var12);
//         this.orderErrorLogService.saveError(payload.getPayVO().getTradeId(), payload.getTraceId(), OrderErrorTypeEnum.MQ_MAC_ASYNC_SAVE, var12.getMessage(), JacksonUtil.writeValueAsString(payload));
//      } finally {
//         if (CharSequenceUtil.isNotBlank(payload.getMacOrderId())) {
//            this.orderPlaceBusiness.orderHandlerUnLock(payload.getMacOrderId());
//         }
//
//         try {
//            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
//               lock.unlock();
//            }
//         } catch (Exception var11) {
//            log.error("解锁异常", var11);
//         }
//
//      }
//
//   }
//
//   public void orderAsyncSaveWeight(OrderSaveWeightPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      RLock lock = RedisUtil.getLock(OrderCacheConstants.orderCacheSaveLockKey(payload.getMacOrderId()));
//      lock.lock();
//
//      try {
//         log.info("[订单异步保存自助餐]MQ消费：开始");
//         String cacheStr = (String)Executors.readInTenant(payload.getTenantId(), () -> {
//            return RedisUtil.getString(OrderCacheConstants.orderCacheKey(payload.getMacOrderId()));
//         });
//         if (CharSequenceUtil.isEmpty(cacheStr)) {
//            throw new LeException("未查询到缓存 " + payload.getMacOrderId());
//         }
//
//         OrderSavePO orderSavePO = (OrderSavePO)JacksonUtil.readValue(cacheStr, OrderSavePO.class);
//         if (orderSavePO == null) {
//            throw new LeException("[订单异步保存自助餐]缓存解析错误： " + cacheStr);
//         }
//
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.asyncSaveHandler(orderSavePO);
//         });
//         log.info("[订单异步保存自助餐]MQ消费：消息消费完成");
//      } catch (Exception var13) {
//         log.error("[订单异步保存自助餐]MQ消费：处理异常", var13);
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderErrorLogService.saveError((Long)null, payload.getTraceId(), OrderErrorTypeEnum.MQ_MAC_ASYNC_SAVE, var13.getMessage(), JacksonUtil.writeValueAsString(payload));
//         });
//      } finally {
//         try {
//            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
//               lock.unlock();
//            }
//         } catch (Exception var12) {
//            log.error("解锁异常", var12);
//         }
//
//      }
//
//   }

   public void orderAsyncPayResult(PayResultPO payload) {
      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
         LogUtil.putLogTraceId(payload.getTraceId());
      } else {
         LogUtil.generateNewLogTraceId();
      }

      if (!TradeTypeEnum.isConsumeType(payload.getTradeType())) {
         log.info("[订单异步支付结果]MQ消费：非消费类型交易，不处理");
      } else {
         RLock lock = RedisUtil.getLock(OrderCacheConstants.orderAsyncPayResultLockKey(payload.getTradeId().toString()));
         lock.lock();
         String macOrderId = null;

         try {
            log.info("[订单异步支付结果]MQ消费：开始");
            macOrderId = (String)Executors.readInTenant(payload.getMerchantId(), () -> {
               return this.orderResultBusiness.asyncPayResultHandler(payload);
            });
            log.info("[订单异步支付结果]MQ消费：消息消费完成");
         } catch (Exception var13) {
            log.error("[订单异步支付结果]MQ消费：处理异常", var13);
            Executors.doInTenant(payload.getMerchantId(), (s) -> {
               this.orderErrorLogService.saveError(payload.getTradeId(), payload.getTraceId(), OrderErrorTypeEnum.MQ_ORDER_PAY_RESULT, var13.getMessage(), JacksonUtil.writeValueAsString(payload));
            });
         } finally {
            if (CharSequenceUtil.isNotEmpty(macOrderId) && PayStateEnum.isFinishedState(payload.getTradeState())) {
               this.orderPlaceBusiness.orderHandlerUnLock(macOrderId);
            }

            try {
               if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                  lock.unlock();
               }
            } catch (Exception var12) {
               log.error("解锁异常", var12);
            }

         }

      }
   }
//
//   public void orderTimeout(OrderCancelPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单异步超时]MQ消费：开始");
//         Executors.doInTenant(payload.getMerchantId(), (s) -> {
//            this.orderResultBusiness.asyncTradeTimeoutHandler(payload);
//         });
//         log.info("[订单异步超时]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单异步超时]MQ消费：处理异常", var3);
//         Executors.doInTenant(payload.getMerchantId(), (s) -> {
//            this.orderErrorLogService.saveError(payload.getTradeId(), payload.getTraceId(), OrderErrorTypeEnum.MQ_ORDER_CANCEL, var3.getMessage(), JacksonUtil.writeValueAsString(payload));
//         });
//      }
//
//   }
//
//   public void updateOrderImage(OrderImagePO payload) {
//      LogUtil.generateNewLogTraceId();
//
//      try {
//         log.info("[订单图片MQ]-数据：{}", payload);
//         TenantContextHolder.setTenantId(payload.getMerchantId());
//         Executors.doInTenant(payload.getMerchantId(), (transactionStatus) -> {
//            this.orderPhotoService.saveOrUpdatePhoto(payload.getSaveList());
//         });
//      } catch (Exception var3) {
//         log.error("[订单图片MQ]MQ消费：处理异常", var3);
//      }
//
//   }

//   public void orderPlaced(OrderPlacedPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单已下单]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderPlacedHandler(payload);
//         });
//         log.info("[订单已下单]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单已下单]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void orderCanceled(OrderCanceledPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单已取消]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderCanceledHandler(payload);
//         });
//         log.info("[订单已取消]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单已取消]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void orderRefunded(OrderRefundPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单已退款]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderRefundedHandler(payload);
//         });
//         log.info("[订单已退款]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单已退款]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void orderStateUpdated(OrderDishesStateUpdatePO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单更新制作配送状态]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderDishesStateUpdateHandler(payload);
//         });
//         log.info("[订单更新制作配送状态]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单更新制作配送状态]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void orderDishesAdd(OrderDishesEditPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单加菜]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderAddDishesHandler(payload);
//         });
//         log.info("[订单加菜]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单加菜]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void orderDishesRemove(OrderDishesEditPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      try {
//         log.info("[订单减菜]MQ消费：开始");
//         Executors.doInTenant(payload.getTenantId(), (s) -> {
//            this.orderResultBusiness.orderRemoveDishesHandler(payload);
//         });
//         log.info("[订单减菜]MQ消费：消息消费完成");
//      } catch (Exception var3) {
//         log.error("[订单减菜]MQ消费：处理异常", var3);
//      }
//
//   }
//
//   public void DcPushUser(JSONObject content) {
//      try {
//         log.info(content.toJSONString());
//         Long ordId = content.getLong("ordId");
//         OrderChangePO orderChangePO = this.orderDeviceApi.getOrderInfoById(ordId);
//         OrderInfo orderInfo = orderChangePO.getOrderInfo();
//         if (DishesStateEnum.WAIT_TAKE.getKey().equals(orderInfo.getDishesState())) {
//            Integer cleanType = content.getInteger("clean");
//            if (cleanType == 2) {
//               String sendTimeStr = content.getString("sendTime");
//               if (sendTimeStr != null) {
//                  LocalDateTime sendTime = LocalDateTime.parse(sendTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
//                  orderChangePO.setTimeoutClean(sendTime);
//               }
//            }
//
//            orderChangePO.setCleanType(cleanType);
//            MqUtil.send(JSON.toJSONString(orderChangePO), LeMqConstant.Topic.ORDER_CHANGE);
//         }
//      } catch (Exception var8) {
//         log.error("[取餐柜超时]MQ消费：处理异常", var8);
//      }
//
//   }
//
//   public void buffetPay(BuffetBindPayDto payload) {
//      LogUtil.generateNewLogTraceId();
//
//      try {
//         log.info("[计量主机支付]MQ入参:{}", payload);
//         Executors.doInTenant(payload.getMerchantId(), (s) -> {
//            String version = RedisUtil.getString(String.format("yunshitang:%s:payversion:%s", payload.getMerchantId(), payload.getMacOrdId()));
//            if ((!ObjectUtil.isEmpty(payload.getPayversion()) || !ObjectUtil.isNotEmpty(version)) && (!ObjectUtil.isNotEmpty(payload.getPayversion()) || payload.getPayversion().equals(version))) {
//               OrderWeightPayDTO orderWeightPayDTO = new OrderWeightPayDTO();
//               orderWeightPayDTO.setMacOrderId(payload.getMacOrdId());
//               orderWeightPayDTO.setWeightBindType(payload.getBindType());
//               orderWeightPayDTO.setOpenid(payload.getOpenId());
//               AliMacWeightBindVO bindVO = this.orderPayApi.getAliMacWeightBindByMacOrdId(payload.getMacOrdId());
//               if (bindVO != null) {
//                  orderWeightPayDTO.setAliSign(bindVO.getAliSign());
//                  orderWeightPayDTO.setAlifToken(bindVO.getAlifToken());
//               }
//
//               OrderWeightPayVO orderWeightPayVO = this.orderWeightBusiness.pay(orderWeightPayDTO);
//               if (!orderWeightPayVO.weightPaySuccess() && (ObjectUtil.isEmpty(payload.getPayNum()) ? 2 : payload.getPayNum()) < 4) {
//                  payload.setPayNum(ObjectUtil.isEmpty(payload.getPayNum()) ? 2 : payload.getPayNum() + 1);
//                  BuffetBindSend.bindPaySend(payload);
//               }
//
//               if (ObjectUtil.isEmpty(payload.getPayNum()) || payload.getPayNum() < 2) {
//                  this.macWeighBindService.cleanAfterOrderPaid(payload.getMacOrdId(), payload.getPlateSerialNum());
//               }
//
//            }
//         });
//      } catch (Exception var3) {
//         log.error("[计量主机支付]：处理异常", var3);
//      }
//
//   }
//
//   public void orderAsyncRefundResult(RefundResultPO payload) {
//      if (CharSequenceUtil.isNotEmpty(payload.getTraceId())) {
//         LogUtil.putLogTraceId(payload.getTraceId());
//      } else {
//         LogUtil.generateNewLogTraceId();
//      }
//
//      if (!TradeTypeEnum.isConsumeRefundType(payload.getTradeType())) {
//         log.info("[订单异步支付结果]MQ消费：非消费退款类型交易，不处理");
//      } else {
//         RLock lock = RedisUtil.getLock(OrderCacheConstants.orderAsyncPayResultLockKey(payload.getRefundTradeId().toString()));
//         lock.lock();
//
//         try {
//            log.info("[订单异步退款结果]MQ消费：开始");
//            Executors.doInTenant(payload.getMerchantId(), (s) -> {
//               this.orderResultBusiness.asyncRefundResultHandler(payload);
//            });
//            log.info("[订单异步退款结果]MQ消费：消息消费完成");
//         } catch (Exception var12) {
//            log.error("[订单异步退款结果]MQ消费：处理异常", var12);
//            Executors.doInTenant(payload.getMerchantId(), (s) -> {
//               this.orderErrorLogService.saveError(payload.getRefundTradeId(), payload.getTraceId(), OrderErrorTypeEnum.MQ_ORDER_REFUND_RESULT, var12.getMessage(), JacksonUtil.writeValueAsString(payload));
//            });
//         } finally {
//            try {
//               if (lock.isHeldByCurrentThread() && lock.isLocked()) {
//                  lock.unlock();
//               }
//            } catch (Exception var11) {
//               log.error("解锁异常", var11);
//            }
//
//         }
//
//      }
//   }
}
