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.app.form.RefundOrderForm;
import org.jeecg.modules.app.service.IOrderService;
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.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class OrderExpireDelayedMessageListener {

    private final IOrderService appOrderService;
    private final IAppOrderProInfoService appOrderProInfoService;

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

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

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

    private void orderExpireMessage(String proOrderInfoId) throws ParseException {
        // 业务处理
        log.info("处理订单消息：{}", proOrderInfoId);

        AppOrderProInfo appOrderProInfo = appOrderProInfoService.getById(proOrderInfoId);

        if (appOrderProInfo == null) {
            log.info("子订单不存在：{}", proOrderInfoId);
            return;
        }

        if (ObjectUtil.isNotEmpty(appOrderProInfo)){
            if (Objects.equals(appOrderProInfo.getOrderStatus(), CommonConstant.ORDER_STATUS_1)) {

                try {
                    //过期退款
                    RefundOrderForm refundOrderForm = new RefundOrderForm();
                    refundOrderForm.setOrderCode(appOrderProInfo.getOrderCode());
                    refundOrderForm.setOrderProInfoIds(appOrderProInfo.getId());
                    refundOrderForm.setType(CommonConstant.NUMBER_3);
                    refundOrderForm.setReason("订单已过期,自动退款！");
                    appOrderService.refundOrder(refundOrderForm);
                }catch (Exception e){
                    log.error("修改子订单：{},支付状态为已过期,自动退款失败：{}", appOrderProInfo.getId(),e.getMessage());
                }
                log.info("修改子订单：{},支付状态为已过期", appOrderProInfo.getId());
                appOrderProInfo.setOrderStatus(CommonConstant.ORDER_STATUS_3);
                appOrderProInfoService.updateById(appOrderProInfo);
            }

            //执行业务代码
            AppOrder appOrder = appOrderService.getById(appOrderProInfo.getOrderId());
            List<AppOrderProInfo> appOrderProInfoList = appOrderProInfoService.list(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, appOrderProInfo.getOrderId()));

            if (appOrderProInfoList.stream().filter(orderProInfo -> Objects.equals(orderProInfo.getOrderStatus(),
                    CommonConstant.ORDER_STATUS_3)).count() == appOrderProInfoList.size()) {
                log.info("修改订单：{},支付状态为已过期", appOrder.getOrderCode());
                appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_3);
                appOrderService.updateById(appOrder);
            }
        }

    }
}