package com.rf.psychological.wxpay.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.rf.psychological.enums.PayType;
import com.rf.psychological.wxpay.model.PaymentInfo;
import com.rf.psychological.wxpay.repository.PaymentInfoRepository;
import com.rf.psychological.wxpay.service.PaymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:支付记录接口
 * @Author: zsf
 * @Date: 2022/6/22
 */
@Service
@Slf4j
public class PaymentInfoServiceImpl implements PaymentInfoService {


    @Autowired
    private PaymentInfoRepository paymentInfoRepository;

    /**
     * 创建支付记录
     * @param plainText 内容
     */
    @Override
    public void createPaymentInfo(String plainText) {
        log.info("记录支付日志");

        Gson gson = new Gson();
        HashMap plainTextMap = gson.fromJson(plainText, HashMap.class);

        //订单号
        String orderNo = (String)plainTextMap.get("out_trade_no");
        //业务编号
        String transactionId = (String)plainTextMap.get("transaction_id");
        //支付类型
        String tradeType = (String)plainTextMap.get("trade_type");
        //交易状态
        String tradeState = (String)plainTextMap.get("trade_state");
        //用户实际支付金额
        Map<String, Object> amount = (Map)plainTextMap.get("amount");
        Integer payerTotal = ((Double) amount.get("payer_total")).intValue();

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);
        paymentInfo.setPayerTotal(payerTotal);
        paymentInfo.setContent(plainText);
        paymentInfo.setCreateTime(DateUtil.now());
        paymentInfoRepository.save(paymentInfo);
    }

}
