package com.zhongshu.card.server.core.service.payment;

import com.github.microservice.net.ResultContent;
import com.github.microservice.types.payment.PaymentType;
import com.zhongshu.card.client.type.payment.OrderNoType;
import com.zhongshu.card.server.core.dao.payment.OrderNoInfoDao;
import com.zhongshu.card.server.core.domain.payment.OrderNoInfo;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author TRX
 * @date 2024/11/15
 */
@Slf4j
@Service
public class OrderNoInfoService extends SuperService {

    @Autowired
    private OrderNoInfoDao orderNoInfoDao;

    public ResultContent saveInfo(String paymentNo, OrderNoType orderNoType) {
        return saveInfo(paymentNo, orderNoType, null);
    }

    public ResultContent saveInfo(String paymentNo, OrderNoType orderNoType, PaymentType paymentType) {
        OrderNoInfo orderNoInfo = orderNoInfoDao.findByPaymentNo(paymentNo);
        if (ObjectUtils.isEmpty(orderNoInfo)) {
            orderNoInfo = new OrderNoInfo();
        }
        orderNoInfo.setPaymentNo(paymentNo);
        if (orderNoType == null) {
            orderNoType = OrderNoType.UnKnow;
        }
        orderNoInfo.setOrderNoType(orderNoType);
        orderNoInfo.setPaymentType(paymentType);
        orderNoInfo.setTtl(new Date(System.currentTimeMillis() + 24 * 7 * 60 * 60 * 100L));
        orderNoInfo.setIsSuccess(Boolean.FALSE);
        orderNoInfoDao.save(orderNoInfo);
        return ResultContent.buildSuccess();
    }

    public void markSuccess(String paymentNo) {
        OrderNoInfo orderNoInfo = orderNoInfoDao.findByPaymentNo(paymentNo);
        if (ObjectUtils.isNotEmpty(orderNoInfo)) {
            orderNoInfo.setIsSuccess(Boolean.TRUE);
            orderNoInfoDao.save(orderNoInfo);
        }
    }

    public OrderNoType getOrderNoType(String paymentNo) {
        OrderNoInfo orderNoInfo = orderNoInfoDao.findByPaymentNo(paymentNo);
        if (ObjectUtils.isEmpty(orderNoInfo)) {
            return OrderNoType.UnKnow;
        }
        if (orderNoInfo.getIsSuccess() != null && orderNoInfo.getIsSuccess()) {
            return OrderNoType.UnKnow;
        }
        return orderNoInfo.getOrderNoType();
    }
}
