package com.zhongshu.card.server.core.service.keyExpire.impl;

import com.github.microservice.net.ResultContent;
import com.zhongshu.card.server.core.dataConfig.OrderConfig;
import com.zhongshu.card.server.core.service.base.RedisService;
import com.zhongshu.card.server.core.service.keyExpire.KeyExpire;
import com.zhongshu.card.server.core.service.payment.ExpenseFlowServiceImpl;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author TRX
 * @date 2025/3/28
 */
@Slf4j
@Component
public class OrderKeyExpire implements KeyExpire {

    @Autowired
    private ExpenseFlowServiceImpl expenseFlowService;

    @Autowired
    private RedisService redisService;

    private String keyStart() {
        return "order_";
    }

    private String buildKey(String orderNo) {
        return String.format("%s%s", keyStart(), orderNo);
    }

    public void saveKey(String orderNo, Long time) {
        if (CommonUtil.longIsEmpty(time)) {
            time = OrderConfig.orderExpirationTime;
        }
        redisService.setValue(buildKey(orderNo), orderNo, time);
    }

    public void deleteKey(String orderNo) {
        redisService.removeValue(buildKey(orderNo));
    }

    @Override
    public boolean isAccessKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        return key.startsWith(keyStart());
    }

    @Override
    public ResultContent<Object> handle(String key) {
        if (StringUtils.isEmpty(key)) {
            return ResultContent.buildFail("key is empty");
        }
        String orderNo = key.replaceAll(keyStart(), "");
        log.info("orderNo:{}", orderNo);
        expenseFlowService.handleDelayedTask(orderNo);
        return ResultContent.buildSuccess();
    }
}
