package com.ruoyi.app.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.PayPush;
import com.ruoyi.app.utils.zaloPay.ZaloPay;
import com.ruoyi.app.utils.zaloPay.ZaloPayConfig;
import com.ruoyi.app.utils.zaloPay.ZaloPayProperties;
import com.ruoyi.app.utils.zaloPay.ZaloPayQueryRefundResponse;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.PoseOrderZalopay;
import com.ruoyi.system.domain.UserBilling;
import com.ruoyi.system.mapper.PosOrderMapper;
import com.ruoyi.system.mapper.UserBillingMapper;
import com.ruoyi.system.service.IPosOrderService;
import com.ruoyi.system.service.IPoseOrderZalopayService;
import com.ruoyi.system.service.IUserBillingService;
import com.ruoyi.system.utils.OrderLogHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;

/**
 * 任务调度
 */
@Component("testTask")
public class TestTask {
    @Autowired
    private IPosOrderService posOrderService;
    @Autowired
    private PosOrderMapper posOrderMapper;
    @Autowired
    private IUserBillingService userBillingService;
    @Autowired
    private UserBillingMapper userBillingMapper;
    @Autowired
    private PosOrderController posorder;
    @Autowired
    private IPoseOrderZalopayService zalopayService;
    @Autowired
    private ZaloPayConfig zaloPayConfig;
    @Autowired
    private ZaloPay zaloPay;
    @Autowired
    private OrderLogHelper orderLogHelper;
    @Autowired
    private OrderService orderService;


    private static Logger logger = LoggerFactory.getLogger(TestTask.class);

    /**
     * 订单未支付，超过一定时间后取消
     * 新逻辑：查 payStatus=0 AND state=0 且超时，设 state=4（已取消）
     * @param minute
     */
    public void testTiming(Integer minute){
        System.out.println("间隔时间："+minute+"分钟");
        List<PosOrder> ordlist = posOrderMapper.getOrderTim(0,minute);
        for(int i=0;i<ordlist.size();i++){
            PosOrder posOrder = new PosOrder();
            posOrder.setId(ordlist.get(i).getId());
            posOrder.setState(4L); // state=4 已取消（替换旧 state=10）
            posOrderService.saveOrUpdate(posOrder);
            orderLogHelper.logSync(String.valueOf(ordlist.get(i).getDdId()), 0, null, "系统", "系统自动取消超时未接单订单");
            try {
                if(ordlist.get(i).getPoints()!=null && ordlist.get(i).getPoints()>0){
                    posorder.returnPoints(ordlist.get(i).getUserId(), Long.valueOf(ordlist.get(i).getDdId()),Long.valueOf(ordlist.get(i).getPoints()));
                }
            }catch (Exception e){
                logger.warn("定时任务取消订单，积分返还失败订单号: {},异常信息:{}", posOrder.getId(),e.getMessage());
            }
        }
        List<UserBilling> ublist = userBillingMapper.getbillingTim(minute);
        for(int i=0;i<ublist.size();i++){
            UserBilling userBilling = new UserBilling();
            userBilling.setId(ublist.get(i).getId());
            userBilling.setState("2");
            userBillingService.saveOrUpdate(userBilling);
        }
    }

    /**
     * 退款处理中，查询zalopay退款结果，设置退款状态
     * 新逻辑：查 afterSaleStatus=2（退款中），退款成功后设 afterSaleStatus=6（售后完成）
     * 注意：本次不实现完整退款流程，保留方法结构
     */
   public void refundProcessing() throws URISyntaxException, IOException {
        LambdaQueryWrapper<PosOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PosOrder::getAfterSaleStatus, 2L); // afterSaleStatus=2 退款中
        List<PosOrder> list = posOrderMapper.selectList(queryWrapper);
        System.out.println("定时任务查询退款处理中的数据，数量: "+list.size());
       logger.info("定时任务查询退款处理中的数据，数量: {}", list.size());
        for(int i=0;i<list.size();i++){
            PoseOrderZalopay zaloResopen = zalopayService.getOne(new QueryWrapper<PoseOrderZalopay>().eq("dd_id", list.get(i).getDdId()));
            if(zaloResopen==null){
                System.out.println("定时任务查询退款结果，未查到支付信息订单号: "+list.get(i).getDdId());
                logger.warn("定时任务查询退款结果，未查到支付信息订单号: {}", list.get(i).getDdId());
                break;
            }
            String mRefundId = zaloResopen.getMRefundId();
            ZaloPayProperties.ZaloPayConfig config = zaloPayConfig.getZaloPayConfig(zaloResopen.getPayType());
            ZaloPayQueryRefundResponse response = zaloPay.queryRefundStatus(mRefundId,config);
            if(response.getReturnCode()==1){
                System.out.println("定时任务处理退款结果，订单号: "+list.get(i).getDdId());
                logger.warn("定时任务处理退款结果，订单号: {}", list.get(i).getDdId());
                PosOrder posOrder = new PosOrder();
                posOrder.setId(list.get(i).getId());
                posOrder.setAfterSaleStatus(6L); // afterSaleStatus=6 售后完成（替换旧 state=11）
                posOrderService.saveOrUpdate(posOrder);
                orderLogHelper.logSync(String.valueOf(list.get(i).getDdId()), 0, null, "系统", "系统处理退款完成");
            }
        }

    }

    /**
     * 自动完成兜底：state=2 AND afterSaleStatus=0 且超时，自动设 state=3
     * 外送同时设 deliveryStatus=3，自取/堂食同时设 payStatus=1
     * @param minute
     */
    public void zidwancheng(Integer minute){
        System.out.println("间隔时间："+minute+"分钟");
        LambdaQueryWrapper<PosOrder> query = new LambdaQueryWrapper<>();
        query.eq(PosOrder::getState, 2L)
             .eq(PosOrder::getAfterSaleStatus, 0L)
             .apply("TIMESTAMPDIFF(MINUTE, cretim) > {0}", minute);
        List<PosOrder> ordlist = posOrderService.list(query);
        for(int i=0;i<ordlist.size();i++){
            PosOrder pos = new PosOrder();
            pos.setId(ordlist.get(i).getId());
            pos.setState(3L);
            // 外送订单自动完成 deliveryStatus
            if(ordlist.get(i).getType() != null && ordlist.get(i).getType() == 0L){
                pos.setDeliveryStatus(3L);
            } else {
                // 自取/堂食自动完成 payStatus
                pos.setPayStatus(1L);
            }
            posOrderService.saveOrUpdate(pos);
            orderLogHelper.logSync(String.valueOf(ordlist.get(i).getDdId()), 0, null, "系统", "系统自动完成超时订单");
            PosOrder order = posOrderService.getById(ordlist.get(i).getId());
            orderService.setSanghuBilling(order);
            orderService.setQishouBilling(order);
        }
    }

    /**
     * 检查预约单
     */

    public void checkAppointmentOrder() {
        int minute = DateUtil.getAppoinmentOrderHandleTime();
        System.out.println("检查预约单，预约检查时间：" + minute);
        LambdaQueryWrapper<PosOrder> query = new LambdaQueryWrapper<>();
        query.isNotNull(PosOrder::getDelryTime)
                .in(PosOrder::getType, 0L,1L)
                .ne(PosOrder::getDelryTime, "")
                .isNotNull(PosOrder::getDelryTime)
                .eq(PosOrder::getIsDisplay, false)
                .apply("((collect_payment = '1' AND state = 0) OR (collect_payment <> '1' AND state = 1))");
        List<PosOrder> orders = posOrderMapper.selectList(query);
        for (PosOrder order : orders) {
            boolean isDisplay = DateUtil.isNearOrPastStartTime(order.getDelryTime(), minute);
            if (isDisplay) {
                PosOrder update = new PosOrder();
                update.setId(order.getId());
                update.setDisplayTime(new Date());
                update.setIsDisplay(true);
                posOrderService.saveOrUpdate(update);
            }
        }
    }

}
