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 org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashSet;

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

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

    // 用HashSet检索效率高
    private final static HashSet<String> orderNoSet = new HashSet<>(1024);

    @Resource
    FinancialMasterService financialMasterService;

    @Override
    public void onCallback(Event event) {
        logger.debug("pay callback is {}", event);
        String data = event.getData();
        PayCallback payment = JSON.parseObject(data, PayCallback.class);
        Assert.hasText(payment.getOrderNo(), "orderNo is blank !!!");
        // 校验是否是本系统发出去的回调请求
        boolean ours = orderNoSet.remove(payment.getOrderNo());
        if (!ours) {
            //如果内存里没有 就从数据库里找这条记录
            PaymentDTO dto = financialMasterService.selectPaymentById(payment.getId());
            ours = dto != null;
        }
        if (ours) {
            // 更新交易记录
            PaymentDTO param = new PaymentDTO();
            param.setId(payment.getId());
            param.setStatus(payment.getStatus());
            param.setPayTime(payment.getPayTime());
            financialMasterService.updatePayment(param);

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

    @Override
    public void onResponse(JSONObject response) {
        // 保存一条支付记录
        PaymentDTO payment = response.toJavaObject(PaymentDTO.class);
        payment.setStatus("pending");
        financialMasterService.insertPayment(payment);

        if (AdapayStatusEnum.succeeded.code.equals(response.getString("status"))) {
            FinancialMaster update = new FinancialMaster();
            update.setOrderMasterCode(response.getString("order_no"));
            update.setPaymentId(response.getString("id"));
            financialMasterService.updateFinancialMaster(update);
        } else {
            logger.warn("请求支付失败 : {}", response.toJSONString());
        }
        // 将记录保存到临时会话中
        orderNoSet.add(response.getString("order_no"));
    }

}
