package cn.iocoder.yudao.module.member.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.member.dal.dataobject.card.CardDO;
import cn.iocoder.yudao.module.member.dal.dataobject.diningplates.DiningPlatesDO;
import cn.iocoder.yudao.module.member.dal.dataobject.order.DishOrderDO;
import cn.iocoder.yudao.module.member.enums.TimePeriodEnum;
import cn.iocoder.yudao.module.member.service.card.CardService;
import cn.iocoder.yudao.module.member.service.diningplates.DiningPlatesService;
import cn.iocoder.yudao.module.member.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自动扣款 Job
 *
 * @author j-sentinel
 */
@Slf4j
@Component
public class BalanceDeductionJob implements JobHandler {

    @Resource
    private DiningPlatesService platesService;
    @Resource
    private OrderService orderService;
    @Resource
    private CardService cardService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 20分钟之后自动解绑并扣款
     */
    private static final Integer EXPIRATION_TIME = 20;


    @Override
    @TenantIgnore
    @Transactional(rollbackFor = Exception.class)
    public String execute(String param) {
        //查询扣费用户
        List<DiningPlatesDO> diningPlatesToCharging = platesService.getDiningPlatesToCharging(EXPIRATION_TIME);
        int size = 0;

        if(CollectionUtil.isNotEmpty(diningPlatesToCharging)){
            List<Long> ids = diningPlatesToCharging.stream().map(DiningPlatesDO::getId).collect(Collectors.toList());
            List<Long> users = diningPlatesToCharging.stream().map(DiningPlatesDO::getUserId).collect(Collectors.toList());
            //先更改状态防止重复消费
            //platesService.updatePayFlag(ids,DiningPlatesDO.PAY);
            //获取用户订单
            List<DishOrderDO> toPay = orderService.getToPay(users);
            //扣除余额
            List<CardDO> list = new ArrayList<>();
            toPay.forEach(dishOrderDO -> {
                //新的总价
                BigDecimal total = new BigDecimal(stringRedisTemplate.opsForValue().get(dishOrderDO.getDiningPlatesNum()));
//                BigDecimal total = new BigDecimal(0.01);
                Long userId = dishOrderDO.getUserId();
                CardDO cardDO = new CardDO();
                cardDO.setType(TimePeriodEnum.getTimePeriod(LocalDateTime.now()));
                BigDecimal oldMoney = cardService.getMoneyByUserId(userId);
                cardDO.setMoney(oldMoney.subtract(total).setScale(2, BigDecimal.ROUND_HALF_UP));
                cardDO.setUserId(userId);
                cardDO.setChangeMoney(total);
                cardDO.setFlag(CardDO.MINUS);
                list.add(cardDO);
                dishOrderDO.setTotalMoney(total);
                dishOrderDO.setOrderStatus(DishOrderDO.COMPLETE);
                stringRedisTemplate.delete(dishOrderDO.getDiningPlatesNum());
            });
            cardService.insertBatch(list);
            size = list.size();
            //餐盘解绑
            platesService.updateBind(ids);
            //更新订单状态和总价
            orderService.updateBatch(toPay);
        }

        log.info("[execute][扣款定时任务扣款数量 ({}) 个]", size);
        return String.format("扣款定时任务扣款数量 %s 个", size);
    }

}
