package com.ghy.payment.service.impl;

import com.alibaba.fastjson.JSON;
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.PayReverseCallback;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.CallBackService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

/**
 * 撤销支付回调
 *
 * @author HH 2022/5/31
 */
@Service("payReverseCallbackService")
public class PayReverseCallbackService implements CallBackService {

    private static final Logger logger = LoggerFactory.getLogger(PayReverseCallbackService.class);

    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private FinancialDetailService financialDetailService;

    @Override
    public void onCallback(Event event) {
        logger.debug("撤销支付 callback: {}", event);
        PayReverseCallback callback = JSON.parseObject(event.getData(), PayReverseCallback.class);
        if (AdapayStatusEnum.succeeded.code.equals(callback.getStatus())) {
            // 将子财务单支付状态设置为3 表示退款成功
            financialDetailService.payReverseSucceeded(callback.getId());
        }
    }

    @Override
    public void onResponse(JSONObject response) {
        logger.debug("撤销支付 Response: {}", response.toString());
        if (AdapayStatusEnum.pending.code.equals(response.getString("status"))) {
            String reverseId = response.getString("id");
            String paymentId = response.getString("payment_id");
            String reverseAmt = response.getString("reverse_amt");
            FinancialMaster fm = financialMasterService.selectByPaymentId(paymentId);
            // 创建并保存一条子财务单(type=撤销支付)
            FinancialDetail fd = new FinancialDetail(fm.getDeptId(), financialDetailService.createCode(), fm.getId(),
                    fm.getCode(), new BigDecimal(reverseAmt), 4, null);
            // 子财务单关联撤销支付ID
            fd.setReverseId(reverseId);
            financialDetailService.insertFinancialDetail(fd);
        } else {
            logger.warn("撤销失败: {}", response.toJSONString());
        }
    }
}
