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

import com.github.microservice.net.ResultContent;
import com.github.microservice.pay.client.model.ledger.TransactionLogModel;
import com.wechat.pay.java.service.refund.model.Refund;
import com.zhongshu.card.client.type.RefundState;
import com.zhongshu.card.server.core.dao.payment.RefundRecordDao;
import com.zhongshu.card.server.core.domain.payment.RefundRecord;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 退款记录管理
 *
 * @author TRX
 * @date 2024/11/19
 */
@Slf4j
@Service
public class RefundRecordService extends SuperService {

    @Autowired
    private RefundRecordDao refundRecordDao;

    public ResultContent saveEntity(RefundRecord entity) {
        if (ObjectUtils.isNotEmpty(entity)) {
            refundRecordDao.save(entity);
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 保存更新 退款记录状态
     *
     * @param refundNo
     * @param refundState
     * @return
     */
    public ResultContent markState(String refundNo, RefundState refundState) {
        return markState(refundNo, refundState, null);
    }

    public ResultContent markState(String refundNo, RefundState refundState, List<TransactionLogModel> transactionLogModelList) {
        if (StringUtils.isNotEmpty(refundNo) && refundState != null) {
            RefundRecord refundRecord = refundRecordDao.findTopByRefundNo(refundNo);
            if (ObjectUtils.isNotEmpty(refundRecord)) {
                refundRecord.setRefundState(refundState);
                refundRecord.setExamineTime(System.currentTimeMillis());
                refundRecord.setRefuseRemark(refundRecord.getRefundRemark());
                refundRecord.setRefundTransactionIds(refundRecord.getRefundTransactionIds());
                refundRecordDao.save(refundRecord);
            }
        }
        return ResultContent.buildSuccess();
    }

    /**
     * 得到最近10条退款中的数据
     *
     * @return
     */
    public List<RefundRecord> getTop10RefundingRecord() {
        return refundRecordDao.findTop10ByRefundStateOrderByCreateTimeDesc(RefundState.Refunding);
    }

}
