package com.izouma.nineth.task;

import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.enums.AuthorityName;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AirDropRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.security.Authority;
import com.izouma.nineth.service.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class OrderServiceTask {

    private RocketMQTemplate rocketMQTemplate;

    private OrderService orderService;

    private GeneralProperties generalProperties;

    private UserRepo userRepo;

    private AirDropRepo airDropRepo;


    /**
     * 批量取消订单,使用延迟处理，而不是固定速度
     */
    @Scheduled(fixedDelay = 30000)
    public void batchCancel() {
//        if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
//            return;
//        }

        List<Long> orderIds = orderService.findWaitingCancelList();
        log.debug("定时取消订单开始执行,数量：{}", orderIds.size());
        orderIds.forEach(orderId -> {
            try {
                orderService.cancel(orderId);
            } catch(BusinessException err){
                log.error("取消订单失败：" + orderId +",原因："+ err.getMessage());
            }catch (Exception err) {
                log.error("取消订单失败:" + orderId,err);
            }
        });


    }


    /**
     * 统计用户销量，使用延迟处理，而不是固定速度
     *
     */
    @Scheduled(fixedDelay = 120000)
    public void setSales() {
        log.debug("定时统计销量开始执行");
        List<User> minters = userRepo.findByAuthoritiesContains(Authority.get(AuthorityName.ROLE_MINTER));
        for (User minter : minters) {
            //临时处理,不统计特殊用户
            if(minter.getId() == 2317857L){
                continue;
            }

            //销售数量
            Integer saleCount =  orderService.countSales(minter.getId());
            //空投数量
            Integer dropCount =   airDropRepo.countDropCount(minter.getId());
            if(dropCount != null){
                saleCount += dropCount;
            }

            userRepo.setSales(minter.getId(), saleCount );
        }
    }

}
