package org.jeecg.modules.quartz.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
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.app.form.RefundOrderForm;
import org.jeecg.modules.app.service.IOrderService;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.entity.AppOrderProInfo;
import org.jeecg.modules.system.app.entity.AppSitePlace;
import org.jeecg.modules.system.app.service.IAppOrderProInfoService;
import org.jeecg.modules.system.app.service.IAppSitePlaceService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author wzq
 * @date 2025/9/8 14:40
 * @description  无固定场已过期未使用的订单进行退款
 */
@Slf4j
@AllArgsConstructor
//@Component
public class RefundJobService {

    private final IOrderService appOrderService;

    private final IAppSitePlaceService appSitePlaceService;

    private final IAppOrderProInfoService appOrderProInfoService;

    /**
     *  @Description 检查无固定场已过期未使用的订单进行退款
     */
    @Scheduled(cron = "0 0 3 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void execute(){
        log.info("开始执行检查已过期未使用的订单退款定时任务");
        try {
            List<AppOrder> list = appOrderService.list(Wrappers.<AppOrder>lambdaQuery()
                    .eq(AppOrder::getPayStatus, CommonConstant.NUMBER_1)
                    .eq(AppOrder::getOrderStatus, CommonConstant.ORDER_STATUS_1)
                    .eq(AppOrder::getOrderType, CommonConstant.ORDER_TYPE_2)
            );
            for (AppOrder appOrder : list) {
                //判断订单是否支持过期自动退款
                String orgCode = appOrder.getOrgCode();
                AppSitePlace sitePlace = appSitePlaceService.getOne(Wrappers.lambdaQuery(AppSitePlace.class).eq(AppSitePlace::getOrgCode, orgCode));
                if (ObjectUtil.isNotEmpty(sitePlace)){
                    if (sitePlace.getRefundType() != null && sitePlace.getRefundType() == 0){
                        List<AppOrderProInfo> orderProInfoList = appOrderProInfoService.list(Wrappers.lambdaQuery(AppOrderProInfo.class)
                                .eq(AppOrderProInfo::getOrderId, appOrder.getId())
                                .eq(AppOrderProInfo::getType, CommonConstant.ORDER_PRO_INFO_TYPE_2)
                        );
                        List<AppOrderProInfo> refundOrderList = new ArrayList<>();
                        for (AppOrderProInfo appOrderProInfo : orderProInfoList) {

                            if (appOrderProInfo.getOrderStatus() == 1) {
                                // 订单未使用，判断是否已过期
                                LocalDateTime expireTime = LocalDateTime.parse(appOrderProInfo.getExpireTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                                if (expireTime.isBefore(LocalDateTime.now())) {
                                    // 订单已过期
                                    refundOrderList.add(appOrderProInfo);
                                }
                            }
                        }
                        //批量退款
                        if (CollUtil.isNotEmpty(refundOrderList)){
                            RefundOrderForm refundOrderForm = new RefundOrderForm();
                            refundOrderForm.setOrderCode(appOrder.getOrderCode());

                            StringJoiner sj = new StringJoiner(",");
                            refundOrderList.forEach(appOrderProInfo -> sj.add(appOrderProInfo.getId()));

                            refundOrderForm.setOrderProInfoIds(sj.toString());
                            refundOrderForm.setReason("过期自动退款");

                            appOrderService.refundOrder(refundOrderForm);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("检查已过期未使用的订单退款定时任务异常",e);
        }
    }
}
