package org.jeecg.modules.rabbitmq;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.entity.AppOrderProInfo;
import org.jeecg.modules.system.app.service.IAppOrderProInfoService;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
public class DelayedMessageListener {

    private final IAppOrderService appOrderService;
    private final IAppOrderProInfoService appOrderProInfoService;

    /**
     * 监听订单超时未支付延迟队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMQConfig.ORDER_DELAY_QUEUE)
    public void handleMessage(Message message, Channel channel) throws IOException {
        try {
            String msg = new String(message.getBody());
            log.info("收到延迟消息,{}：",msg);

            // 业务逻辑处理
            orderProcessMessage(msg);

            // 手动确认成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 处理失败，拒绝消息并重新入队（或进入死信队列）
            log.error("处理延迟消息失败：{}", e.getMessage());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    private void orderProcessMessage(String orderCode) {
        // 业务处理
        log.info("处理订单消息：{}",orderCode);

        AppOrder appOrder = appOrderService.getOne(Wrappers.<AppOrder>lambdaQuery().eq(AppOrder::getOrderCode, orderCode).last("limit 1"));
        if(ObjectUtil.isNotEmpty(appOrder)){
            if (Objects.equals(appOrder.getOrderStatus(), CommonConstant.ORDER_STATUS_0)) {
                log.info("修改订单：{},支付状态为已取消", orderCode);
                appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_4);
                appOrderService.updateById(appOrder);
                //修改子订单状态
                List<AppOrderProInfo> appOrderProInfoList =
                        appOrderProInfoService.list(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, appOrder.getId()));
                if (CollUtil.isNotEmpty(appOrderProInfoList)){
                    for (AppOrderProInfo appOrderProInfo : appOrderProInfoList) {
                        appOrderProInfo.setOrderStatus(CommonConstant.ORDER_STATUS_4);
                        appOrderProInfoService.updateById(appOrderProInfo);
                    }
                }
            }

        }
    }
}