package com.xunwang.payment.service.impl;

import com.google.gson.Gson;
import com.xunwang.payment.entity.PaymentInfo;
import com.xunwang.payment.enums.PayType;
import com.xunwang.payment.mapper.PaymentInfoMapper;
import com.xunwang.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志 服务实现类
 * </p>
 *
 * @author Long
 * @since 2023-02-26
 */
@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    /**
     * 记录支付日志
     * @param plainText
     */
    @Override
    public void createPaymentInfo(String plainText) {

        log.info("记录支付日志");

        Gson gson = new Gson();
        Map<String, Object> 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");
        BigDecimal payerTotal = new BigDecimal(amount.get("payer_total").toString());

        PaymentInfo paymentInfo = new PaymentInfo();

        // 支付者openid
        if (plainTextMap.get("payer") != null && plainTextMap.get("payer") != "") {
            Map<String, Object> payer =  (Map)plainTextMap.get("payer");
            String openId = (String)payer.get("openid");
            paymentInfo.setOpenId(openId);
        }

        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);
        paymentInfo.setPayerTotal(payerTotal);
        paymentInfo.setContent(plainText);

        baseMapper.insert(paymentInfo);
    }
}
