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.PayCallback;
import com.ghy.common.adapay.model.PaymentDTO;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.service.CallBackService;
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.time.LocalDateTime;

/**
 * 支付回调
 *
 * @author HH 2022/5/31
 */
@Service("payCallbackService")
public class PayCallbackService implements CallBackService {

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

    @Resource
    FinancialMasterService financialMasterService;

    @Override
    public void onCallback(Event event) {
        logger.info("支付回调: {}", event);
        String data = event.getData();
        PayCallback payment = JSON.parseObject(data, PayCallback.class);
        PaymentDTO dto = financialMasterService.selectPaymentById(payment.getId());
        // 校验是否是本系统发出去的支付请求
        if (dto != null) {
            // 更新交易记录
            PaymentDTO param = new PaymentDTO();
            param.setId(payment.getId());
            param.setFeeAmt(payment.getFeeAmt());
            param.setStatus(payment.getStatus());
            param.setPayTime(LocalDateTime.now());
            financialMasterService.updatePayment(param);

            if (AdapayStatusEnum.succeeded.code.equals(payment.getStatus())) {
                // 更新主财务单状态
                financialMasterService.paySucceeded(payment.getId(), payment.getPayChannel());
            } else {
                logger.warn("支付失败 : {}", payment);
            }
        } else {
            logger.warn("系统中不存在这条交易记录: {}", event);
        }
    }

    @Override
    public void onResponse(JSONObject response) {
        logger.info("发起支付 Response: {}", response.toJSONString());
        // 保存一条支付记录
        PaymentDTO payment = response.toJavaObject(PaymentDTO.class);
        String status = payment.getStatus();
        financialMasterService.insertPayment(payment);

        if (AdapayStatusEnum.succeeded.code.equals(status)) {
            FinancialMaster update = new FinancialMaster();
            update.setOrderMasterCode(payment.getOrderNo().split("_")[0]);
            update.setPaymentId(payment.getId());
            financialMasterService.updateFinancialMaster(update);
        } else {
            logger.warn("发起支付失败 : {}", response.toJSONString());
        }
    }

}
