package com.ruoyi.task.bill;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillStatus;
import com.ruoyi.ss.transactionBill.service.TransactionBillService;
import com.ruoyi.common.pay.wx.service.WxPayService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author wjh
 * 2024/3/14
 */
@Slf4j
@Getter
@Setter
public class BillDelayed implements Delayed {

    private TransactionBillService transactionBillService;

    private WxPayService wxPayService = SpringUtils.getBean(WxPayService.class);


    private String billNo;

    // 超时时间（毫秒）
    private Long timestamp;


    public BillDelayed() {
    }

    BillDelayed(String billNo, Long timestamp) {
        this.billNo = billNo;
        this.timestamp = timestamp;
    }

    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        BillDelayed t = (BillDelayed) other;
        long d = (getDelay(TimeUnit.MILLISECONDS) - t.getDelay(TimeUnit.MILLISECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    // 返回距离你自定义的超时时间还有多少
    public long getDelay(TimeUnit unit) {
        return unit.convert(timestamp - System.currentTimeMillis(), TimeUnit.MILLISECONDS) ;
    }

    /**
     * 执行取消订单任务
     */
    public void run() {
        int updateCount = transactionBillService.cancelRecharge(billNo, TransactionBillStatus.SYS_CANCELED);
        log.debug("订单{}超时取消，影响行数：{}", billNo, updateCount);

    }
}
