package com.greenorange.promotion.service.course.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greenorange.promotion.constant.CommonConstant;
import com.greenorange.promotion.constant.MqConstant;
import com.greenorange.promotion.model.dto.courseOrder.CourseOrderQueryRequest;
import com.greenorange.promotion.model.entity.CourseOrder;
import com.greenorange.promotion.service.course.CourseOrderService;
import com.greenorange.promotion.mapper.CourseOrderMapper;
import com.greenorange.promotion.utils.MultiDelayMessage;
import com.greenorange.promotion.utils.SqlUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 35880
* @description 针对表【course_order(课程订单表)】的数据库操作Service实现
* @createDate 2025-06-23 18:31:13
*/
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder>
    implements CourseOrderService{


    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 获取查询条件
     */
    @Override
    public QueryWrapper<CourseOrder> getQueryWrapper(CourseOrderQueryRequest courseOrderQueryRequest) {
        String orderNumber = courseOrderQueryRequest.getOrderNumber();
        String orderStatus = courseOrderQueryRequest.getOrderStatus();
        String sortField = courseOrderQueryRequest.getSortField();
        String sortOrder = courseOrderQueryRequest.getSortOrder();
        QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orderNumber), "orderNumber", orderNumber);
        queryWrapper.eq(StringUtils.isNotBlank(orderStatus), "orderStatus", orderStatus);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 向消息队列中发送订单创建的消息
     */
    @Override
    public void sendCreateOrderMessage(Long orderId) {
        // 复制 DELAY_MILLIS 到一个新的 ArrayList
        List<Long> newDelayMillis = new ArrayList<>(MqConstant.DELAY_MILLIS);
        // 延迟检查订单状态信息
        MultiDelayMessage<Long> msg = new MultiDelayMessage<>(orderId, newDelayMillis);
        long delayValue = msg.removeNextDelay();
        rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,
                MqConstant.DELAY_ORDER_ROUTING_KEY, msg, message -> {
                    // 添加延迟消息属性
                    message.getMessageProperties().setDelayLong(delayValue);
                    return message;
                });
    }
}




