package org.jeecg.modules.quartz.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.entity.AppOrderProInfo;
import org.jeecg.modules.system.app.service.IAppOrderProInfoService;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wzq
 * @date 2025/9/8 14:40
 * @description
 */
@Slf4j
@AllArgsConstructor
//@Component
public class RefundJobService {

    private final IAppOrderService appOrderService;

    private final IAppOrderProInfoService appOrderProInfoService;

    /**
     *  @Description 检查已过期未使用的订单进行退款
     */
    @Scheduled(cron = "")
    @Transactional(rollbackFor = Exception.class)
    public void execute(){
        log.info("开始执行检查已过期未使用的订单退款定时任务");
        try {
            List<AppOrder> refundOrderList = new ArrayList<>();
            List<AppOrder> list = appOrderService.list(Wrappers.<AppOrder>lambdaQuery().eq(AppOrder::getPayStatus, 1).eq(AppOrder::getOrderStatus, CommonConstant.ORDER_STATUS_1));
            for (AppOrder appOrder : list) {
                List<AppOrderProInfo> orderProInfoList = appOrderProInfoService.list(Wrappers.lambdaQuery(AppOrderProInfo.class)
                        .eq(AppOrderProInfo::getOrderId, appOrder.getId())
                        .ne(AppOrderProInfo::getType, CommonConstant.ORDER_PRO_INFO_TYPE_6)
                );
                for (AppOrderProInfo appOrderProInfo : orderProInfoList) {
                    if (appOrderProInfo.getOrderStatus() == 1) {
                        // 订单未使用，判断是否已过期
                        LocalDate expireTime = LocalDate.parse((appOrderProInfo.getExpireTime()));
                        if (expireTime.isBefore(LocalDate.now())) {
                            // 订单已过期
                            refundOrderList.add(appOrder);
                            continue;
                        }
                    }
                }
            }
            //批量退款
            for (AppOrder appOrder : refundOrderList) {
                //todo 退款（分账回退）
            }
        }catch (Exception e){
            log.error("检查已过期未使用的订单退款定时任务异常",e);
        }
    }
}
