package com.fzm.mall.server.admin.task.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.fzm.mall.server.admin.mq.MsgProducer;
import com.fzm.mall.server.admin.mq.enums.QueueTypeEnum;
import com.fzm.mall.server.admin.order.entity.dto.MemberUpDTO;
import com.fzm.mall.server.admin.order.mapper.OrderMapper;
import com.fzm.mall.server.admin.order.model.Order;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单支付完成
 *
 * @author wulixian
 * @since 2021/9/14
 */
@Component
@EnableScheduling
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderMemberUpTask {

    private final OrderMapper orderMapper;
    private final MsgProducer msgProducer;

    /**
     * 7天
     */
    private static final Long DATA_IN_SEVEN = 604800000L;

    /**
     * 8天
     */
    private static final Long DATA_IN_EIGHT = 691200000L;

    @Scheduled(cron = "${order.member-up-task}")
    private void configureTasks() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_state", Order.ORDER_STATE_SUCCESS)
                .eq("is_delete", false);
        List<Order> orderList = orderMapper.selectList(queryWrapper);
        /**
         * 筛选出更新时间为当前时间7-8天内得订单
         */
        Long currentTime = SystemClock.now();

        List<Order> resultList = orderList.stream().filter(order -> (currentTime - order.getUpdateTime()) >= DATA_IN_SEVEN &&
                (currentTime - order.getUpdateTime()) < DATA_IN_EIGHT).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(resultList)){
            resultList.forEach(order -> {
                MemberUpDTO memberUpDTO = new MemberUpDTO();
                memberUpDTO.setUid(order.getUid());
                memberUpDTO.setAmount(order.getAmount());
                msgProducer.send(JSONObject.toJSONString(memberUpDTO), QueueTypeEnum.USER_MEMBER_UP);
            });
        }
    }
}