package com.czg.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.czg.account.entity.ShopUser;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserService;
import com.czg.constant.TableValueConstant;
import com.czg.market.entity.MkDistributionFlow;
import com.czg.market.service.MkDistributionFlowService;
import com.czg.market.service.MkDistributionUserService;
import com.czg.order.entity.OrderInfo;
import com.czg.order.service.OrderInfoService;
import com.czg.service.market.enums.OrderStatusEnums;
import com.czg.utils.FunUtils;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 分销定时任务
 *
 * @author ww
 */
@Slf4j
@Component
public class DistributionTask {
    @Resource
    private MkDistributionUserService distributionUserService;
    @Resource
    private MkDistributionFlowService distributionFlowService;

    @DubboReference
    private OrderInfoService orderInfoService;
    @DubboReference
    private ShopInfoService shopInfoService;
    @DubboReference
    private ShopUserService shopUserService;

    /**
     * 分销流水入账
     * AAMarketTasks 统一调用位置
     */
//    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(fixedRate = 30000)
    public void deliver() {
        //  1. 订单完成支付时（判断是否分销）产生流水记录。
        //  2. 判断入账时间。
        //  3. 如果是 0 天，再去判断商户余额是否足够。够则入账，不足则不管。
        //  4. 流水增加应该入账的时间（订单产生时带入）
        //  5. 定时任务 应该是一天执行一次。查询待入账状态和应入账时间小于当前时间的记录，循环处理：并且判断商户余额是否足够，余额不足忽略处理；余额足够变为已入账并扣除商户余额。
        //  6. 订单产生退款时，去流水表查询该订单的流水记录，如果未入账改为已入账，并插入一条退款扣钱的流水。
        LocalDateTime localDateTime = DateUtil.date().toLocalDateTime();
        distributionFlowService.list(new QueryWrapper()
                .eq(MkDistributionFlow::getStatus, TableValueConstant.DistributionFlow.Status.PENDING.getCode()).le(MkDistributionFlow::getDeliverTime, localDateTime)).forEach(item -> {
            FunUtils.safeRunVoid(() -> {
                log.info("开始处理延时分账， id: {}, orderNo: {}, 类型: {}", item.getId(), item.getOrderNo(), item.getType());

                OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper().eq(OrderInfo::getOrderNo, item.getOrderNo()));
                if (orderInfo == null) {
                    log.warn("订单不存在, 订单号: {}", item.getOrderNo());
                    return;
                }
                if (CollUtil.newArrayList(OrderStatusEnums.REFUND.getCode(), OrderStatusEnums.REFUNDING.getCode(), OrderStatusEnums.PART_REFUND.getCode()).contains(orderInfo.getStatus())) {
                    log.warn("订单已退款, 订单号: {}", item.getOrderNo());
                    distributionUserService.refund(orderInfo.getId(), orderInfo.getOrderNo());
                } else {
                    item.setStatus(TableValueConstant.DistributionFlow.Status.SUCCESS.getCode());
                    ShopUser shopUser = shopUserService.getById(item.getDistributionUserId());
                    distributionUserService.updateShopInfoAmount(orderInfo.getShopId(), item.getRewardAmount().negate(), orderInfo.getId(), TableValueConstant.DistributionAmountFlow.Type.SUB, "分销扣减");
                    distributionUserService.updateIncome(item.getRewardAmount().negate(), item.getRewardAmount(), BigDecimal.ZERO,
                            item.getDistributionUserId(), shopUser.getUserId(), item.getShopUserId(), item.getShopId(), item.getLevel());
                    distributionFlowService.updateById(item);
                }
            });
        });
    }


}
