package cn.com.poc.thirdparty.resource.demand.pay.rest.impl;


import cn.com.poc.thirdparty.resource.demand.pay.dto.payConfig.PayCallBackRequest;
import cn.com.poc.thirdparty.resource.demand.pay.entity.DgtoolsPayOrderEntity;
import cn.com.poc.thirdparty.resource.demand.pay.processor.IPayPostProcessor;
import cn.com.poc.thirdparty.resource.demand.pay.rest.PayCallBackRest;
import cn.com.poc.thirdparty.resource.demand.pay.service.DgtoolsPayLogService;
import cn.com.poc.thirdparty.resource.demand.pay.service.DgtoolsPayOrderService;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Roger Wu
 */
@Service
public class PayCallBackRestImpl implements PayCallBackRest {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private DgtoolsPayOrderService dgtoolsPayOrderService;
    @Resource
    private DgtoolsPayLogService dgtoolsPayLogService;
    @Resource
    private IPayPostProcessor iPayPostProcessor;


    @Override
    public String payCallBack(PayCallBackRequest payRequest) {
        String bizUniqueNo = payRequest.getBizUniqueNo();
        String payLogSn = payRequest.getPayLogSn();

        log.info("支付-接受回调消息-回调交易流水号:{}-回调交易记录流水号:{}-", bizUniqueNo, payLogSn);
        DgtoolsPayOrderEntity payOrderEntity = dgtoolsPayOrderService.findPayOrderByPaySn(bizUniqueNo);
        if (payOrderEntity == null) {
            throw new BusinessException("支付回调,找不到账单信息");
        }
        dgtoolsPayOrderService.changePayOrder2PaidStatus(bizUniqueNo, payRequest.getAmount(), payRequest.getPayChannel());
        //更新支付流水
        dgtoolsPayLogService.changePayLog2PaidStatus(bizUniqueNo, payLogSn);
        // 支付後置處理
        iPayPostProcessor.postProcess(payOrderEntity.getPayOrderType(), payOrderEntity.getPayOrderSn());
        return "success";
    }
}
