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.diningplates.DiningPlatesDO;
import cn.iocoder.yudao.module.member.dal.dataobject.order.DishOrderDO;
import cn.iocoder.yudao.module.member.service.amount.DeductionService;
import cn.iocoder.yudao.module.member.service.business.BusinessService;
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 cn.iocoder.yudao.module.member.service.user.MemberUserService;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
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;
    @Resource
    private MemberUserService userService;
    @Resource
    private BusinessService businessService;

    @Resource
    private DeductionService deductionService;

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

    /**
     * 30分钟之后自动解绑并扣款
     */
    private static final Integer ABNORMAL_EXPIRATION_TIME = 60;

    @Override
    @TenantIgnore
    @Transactional(rollbackFor = Exception.class)
    public String execute(String param) {
        //查询扣费用户
        Map<String, List<DiningPlatesDO>> map = platesService.getDiningPlatesToCharging(EXPIRATION_TIME, ABNORMAL_EXPIRATION_TIME);
        List<DiningPlatesDO> normal = map.get("normal");
        List<DiningPlatesDO> abnormal = map.get("abnormal");
        int size = 0;

        List<Long> unbindIds = new ArrayList<>();
        List<DishOrderDO> updateList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(normal)) {
            List<Long> ids = normal.stream().map(DiningPlatesDO::getId).collect(Collectors.toList());
            List<Long> orderIds = normal.stream().map(DiningPlatesDO::getOrderId).collect(Collectors.toList());
            //获取正常用户订单
            List<DishOrderDO> toPay = orderService.getToPayByOrder(orderIds);

            toPay.forEach(dishOrderDO -> {
                deductionService.deduction(dishOrderDO);
            });
            size = toPay.size();
            updateList.addAll(toPay);
            unbindIds.addAll(ids);
        }

        if(CollectionUtil.isNotEmpty(abnormal)){
            List<Long> ids = abnormal.stream().map(DiningPlatesDO::getId).collect(Collectors.toList());
            List<Long> orderIds = abnormal.stream().map(DiningPlatesDO::getOrderId).collect(Collectors.toList());
            //获取异常用户订单
            List<DishOrderDO> toPay = orderService.getToPayByOrderAbnormal(orderIds);
            toPay.forEach(dishOrderDO -> {
                deductionService.abnormalOrderHandle(dishOrderDO);
                    });
            updateList.addAll(toPay);
            unbindIds.addAll(ids);
        }
        //餐盘解绑
        if(CollectionUtil.isNotEmpty(unbindIds)){
            platesService.updateBind(unbindIds);
        }
        //更新订单状态和总价
        if(CollectionUtil.isNotEmpty(updateList)){
            orderService.updateBatch(updateList);
        }

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


    public void test() {
        //计算金额
        //if (total.compareTo(wxAmount) <= 0) {
        //    cardDO.setWxAmount(wxAmount.subtract(total).setScale(2, BigDecimal.ROUND_HALF_UP));
        //    dishOrderDO.setWxAmount(total);
        //} else {
        //    cardDO.setWxAmount(BigDecimal.ZERO);
        //    dishOrderDO.setWxAmount(wxAmount);
        //    BigDecimal total1 = total.subtract(wxAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
        //    if (total1.compareTo(cashAmount) <= 0) {
        //        cardDO.setCashAmount(cashAmount.subtract(total1).setScale(2, BigDecimal.ROUND_HALF_UP));
        //        dishOrderDO.setCashAmount(total1);
        //    } else {
        //        cardDO.setCashAmount(BigDecimal.ZERO);
        //        dishOrderDO.setCashAmount(cashAmount);
        //        BigDecimal total2 = total1.subtract(cashAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
        //
        //        cardDO.setGiftAmount(giftAmount.subtract(total2).setScale(2, BigDecimal.ROUND_HALF_UP));
        //        dishOrderDO.setGiftAmount(total2);
        //    }
        //}
        //计算金
    }

}
