package com.czg.task;

import cn.hutool.core.collection.CollUtil;
import com.czg.account.entity.ShopInfo;
import com.czg.account.service.ShopInfoService;
import com.czg.constant.TableValueConstant;
import com.czg.constants.SystemConstants;
import com.czg.exception.CzgException;
import com.czg.market.entity.MkDistributionFlow;
import com.czg.market.service.MkDistributionFlowService;
import com.czg.market.service.MkDistributionUserService;
import com.czg.market.service.OrderInfoService;
import com.czg.order.entity.OrderInfo;
import com.czg.service.market.enums.OrderStatusEnums;
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;
import java.util.List;

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

    @Resource
    private OrderInfoService orderInfoService;
    @DubboReference
    private ShopInfoService shopInfoService;

    List<String> list = List.of(OrderStatusEnums.REFUND.getCode(), OrderStatusEnums.PART_REFUND.getCode());

    /**
     * 分销流水入账
     * AAMarketTasks 统一调用位置
     */
//    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(fixedRate = 30000)
    public void deliver(Long shopId) {
        LocalDateTime now = LocalDateTime.now();
        List<ShopInfo> shopInfos = shopInfoService.list(QueryWrapper.create()
                .eq(ShopInfo::getIsDeleted, SystemConstants.OneZero.ZERO)
                .isNotNull(ShopInfo::getExpireTime)
                .lt(ShopInfo::getExpireTime, now)
                .gt(ShopInfo::getAmount, BigDecimal.ZERO)
                .eq(ShopInfo::getId, shopId)
        );
        if (CollUtil.isEmpty(shopInfos)) {
            log.info("分销延时分账 无符合条件的店铺，无需处理分账");
            return;
        }
        for (ShopInfo shopInfo : shopInfos) {
            boolean breakCurrentShopFlow = false;
            List<MkDistributionFlow> flowList = distributionFlowService.list(new QueryWrapper()
                    .eq(MkDistributionFlow::getShopId, shopInfo.getId())
                    .eq(MkDistributionFlow::getStatus, TableValueConstant.DistributionFlow.Status.PENDING.getCode())
                    .le(MkDistributionFlow::getDeliverTime, now)
                    .orderBy(MkDistributionFlow::getId, true)
            );
            for (MkDistributionFlow item : flowList) {
                if (breakCurrentShopFlow) {
                    break;
                }
                try {
                    log.info("分销延时分账， id: {}, orderNo: {}, 类型: {}", item.getId(), item.getOrderNo(), item.getType());
                    OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper().eq(OrderInfo::getOrderNo, item.getOrderNo()));
                    if (orderInfo == null) {
                        item.setStatus(TableValueConstant.DistributionFlow.Status.FAIL.getCode());
                        distributionFlowService.updateById(item);
                        log.warn("分销延时分账。订单不存在, 订单号: {}", item.getOrderNo());
                        continue;
                    }
                    if (list.contains(orderInfo.getStatus())) {
                        log.warn("分销延时分账。订单已退款, 订单号: {}", item.getOrderNo());
                        distributionUserService.refund(orderInfo.getId(), orderInfo.getOrderNo());
                    } else {
                        item.setStatus(TableValueConstant.DistributionFlow.Status.SUCCESS.getCode());
                        distributionUserService.distributionUserAmount(item, orderInfo);
                    }
                } catch (CzgException e) {
                    log.error("店铺{}:{}分销延时分账异常:{}", shopInfo.getId(), shopInfo.getShopName(), e.getMessage());
                    breakCurrentShopFlow = true;
                } catch (Exception e) {
                    log.error("店铺{}:{}分销延时分账异常", shopInfo.getId(), shopInfo.getShopName(), e);
                    breakCurrentShopFlow = true;
                }
            }
        }
    }
}
