package com.jsowell.pile.service.impl;

import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.AdapayCallbackRecord;
import com.jsowell.pile.mapper.AdapayCallbackRecordMapper;
import com.jsowell.pile.service.AdapayCallbackRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AdapayCallbackRecordServiceImpl implements AdapayCallbackRecordService {

    @Autowired
    private AdapayCallbackRecordMapper adapayCallbackRecordMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void saveAdapayCallbackRecord(AdapayCallbackRecord callbackRecord) {
        adapayCallbackRecordMapper.insert(callbackRecord);
    }

    /**
     * 根据订单号查询支付回调信息
     *
     * @param orderCode
     * @return
     */
    @Override
    public AdapayCallbackRecord selectByOrderCode(String orderCode) {
        if (StringUtils.isBlank(orderCode)) {
            return null;
        }
        String redisKey = CacheConstants.QUERY_ORDER_ADAPAY_CALLBACK + orderCode;
        AdapayCallbackRecord record = redisCache.getCacheObject(redisKey);
        if (record != null) {
            return record;
        }
        // AdapayCallbackRecord record = null;
        try {
            record = adapayCallbackRecordMapper.selectByOrderCode(orderCode);
            if (record != null) {
                redisCache.setCacheObject(redisKey, record, CacheConstants.cache_expire_time_1d);
            }
        } catch (Exception e) {
            log.error("查询汇付支付回调记录失败", e);
        }
        // log.info("查询汇付支付回调记录 orderCode:{}, result:{}", orderCode, JSON.toJSONString(record));
        return record;
    }

    @Override
    public AdapayCallbackRecord selectByPaymentId(String paymentId) {
        if (StringUtils.isBlank(paymentId)) {
            return null;
        }
        // 加缓存缓存一周 由于回调结果不会变动，所以不用写清缓存的逻辑了
        String redisKey = CacheConstants.QUERY_ADAPAY_CALLBACK_RECORD_BY_PAYMENT_ID + paymentId;
        AdapayCallbackRecord record = redisCache.getCacheObject(redisKey);
        if (record != null) {
            return record;
        }
        try {
            record = adapayCallbackRecordMapper.selectByPaymentId(paymentId);
            if (record != null) {
                redisCache.setCacheObject(redisKey, record, CacheConstants.cache_expire_time_1d);
            }
        } catch (Exception e) {
            log.error("查询汇付支付回调记录失败", e);
        }
        return record;
    }
}
