package com.ghy.callback;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.adapay.model.Event;
import com.ghy.common.adapay.model.PaymentDTO;
import com.ghy.common.utils.MoneyUtil;
import com.ghy.payment.domain.PaymentConfirm;
import com.ghy.payment.mapper.PaymentConfirmMapper;
import com.ghy.payment.mapper.PaymentMapper;
import com.ghy.payment.service.CallBackService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service("paymentConfirmCallbackService")
public class PaymentConfirmCallbackService implements CallBackService {

    @Resource
    private PaymentMapper paymentMapper;
    @Resource
    private PaymentConfirmMapper paymentConfirmMapper;

    @Override
    public void onCallback(Event event) {
        // 支付确认没有callback
    }

    @Override
    public void onResponse(JSONObject response) {
        if (AdapayStatusEnum.succeeded.code.equals(response.getString("status")) ||
                AdapayStatusEnum.pending.code.equals(response.getString("status"))) {
            // 支付确认 操作成功
            PaymentConfirm paymentConfirm = response.toJavaObject(PaymentConfirm.class);
            // 保存支付确认记录
            paymentConfirmMapper.insert(paymentConfirm);
            // 更新支付单信息
            updatePayment(paymentConfirm);
        }
    }

    private synchronized void updatePayment(PaymentConfirm paymentConfirm) {
        String paymentId = paymentConfirm.getPaymentId();
        PaymentDTO payment = paymentMapper.selectById(paymentId);
        // 支付金额
        BigDecimal payAmt = new BigDecimal(payment.getPayAmt());
        // 已确认金额
        BigDecimal confirmedAmt = new BigDecimal(paymentConfirm.getConfirmedAmt());
        // 已退款金额
        BigDecimal refundedAmt = new BigDecimal(paymentConfirm.getRefundedAmt());
        // 已撤销金额
        BigDecimal reservedAmt = new BigDecimal(paymentConfirm.getReservedAmt());
        // 可支配金额 = 支付金额 - 已确认金额 - 已退款金额 - 已撤销金额
        BigDecimal availableAmt = payAmt.subtract(confirmedAmt).subtract(refundedAmt).subtract(reservedAmt);

        // 更新支付单信息
        PaymentDTO payment2up = new PaymentDTO();
        payment2up.setId(paymentId);
        payment2up.setConfirmedAmt(paymentConfirm.getConfirmedAmt());
        payment2up.setRefundedAmt(paymentConfirm.getRefundedAmt());
        payment2up.setReservedAmt(paymentConfirm.getReservedAmt());
        payment2up.setAvailableAmt(MoneyUtil.toS(availableAmt));
        paymentMapper.updatePayment(payment2up);
    }
}
