package com.diaoyun.zion.chinafrica.service.impl;

import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.service.PayPalService;
import com.diaoyun.zion.chinafrica.vo.TbCfOrderVo;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.common.RedisCache;
import com.diaoyun.zion.master.config.DomainProperties;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.egzosn.pay.paypal.api.PayPalConfigStorage;
import com.egzosn.pay.paypal.api.PayPalPayService;
import com.egzosn.pay.paypal.bean.PayPalTransactionType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

@Service("payPalService")
public class PayPalServiceImpl implements PayPalService {
    @Autowired
    private DomainProperties domainProperties;
    @Resource
    private RedisCache<Object> orderRedisCache;
    private static Logger logger = LoggerFactory.getLogger(TbCfOrderServiceImpl.class);

    @Override
    @Transactional
    public Result payForOrder(String orderId) {
        Result result = new Result();
        PayPalConfigStorage storage = new PayPalConfigStorage();
        storage.setClientID(domainProperties.getProperty("paypal.client.app"));
        storage.setClientSecret(domainProperties.getProperty("paypal.client.secret"));
        //storage.setTest(true);
        //发起付款后的页面转跳地址
        storage.setReturnUrl(domainProperties.getProperty("paypal.success.url"));
        //取消按钮转跳地址,这里用异步通知地址的兼容的做法
        storage.setNotifyUrl(domainProperties.getProperty("paypal.cancel.url"));
        HttpConfigStorage httpConfigStorage = new HttpConfigStorage();

        PayService service = new PayPalPayService(storage);
        TbCfOrderVo tbCfOrderVo = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
        try {
            if (tbCfOrderVo != null) {
                BigDecimal realityPay = tbCfOrderVo.getRealityPay();
                PayOrder order = new PayOrder("Order_payment:", "Order payment", realityPay, UUID.randomUUID().toString().replace("-", ""), PayPalTransactionType.sale);
                Map orderInfo = service.orderInfo(order);
                service.buildRequest(orderInfo, MethodType.POST);
            }
        } catch (Exception e) {
            result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;
    }

    @Override
    public Result payForSuccess(HttpServletRequest request,String orderId) {
        Result result = new Result();
        PayPalConfigStorage storage = new PayPalConfigStorage();
        storage.setClientID(domainProperties.getProperty("paypal.client.app"));
        storage.setClientSecret(domainProperties.getProperty("paypal.client.secret"));
        //storage.setTest(true);
        //发起付款后的页面转跳地址
        storage.setReturnUrl(domainProperties.getProperty("paypal.success.url"));
        //取消按钮转跳地址,这里用异步通知地址的兼容的做法
        storage.setNotifyUrl(domainProperties.getProperty("paypal.cancel.url"));
        HttpConfigStorage httpConfigStorage = new HttpConfigStorage();

        PayService service = new PayPalPayService(storage);
        Map<String, Object> params = null;
        TbCfOrderVo tbCfOrderVo = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
        try {
            params = service.getParameter2Map(request.getParameterMap(), request.getInputStream());
            if (service.verify(params)) {
                System.out.println("支付成功");
                result.setData("支付成功");
                removeRedisCache(tbCfOrderVo);
            }
        } catch (IOException e) {
            result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }

        return result;
    }
    private void removeRedisCache(TbCfOrderVo tbCfOrderVo) {
        orderRedisCache.delete(KeyConstant.ORDER_DET + tbCfOrderVo.getOrderId());
        String couponId = "";
        if (StringUtils.isNotBlank(tbCfOrderVo.getCouponId())) {
            couponId = tbCfOrderVo.getCouponId();
        }
        String orderIdAndCouponId = tbCfOrderVo.getOrderId() + ":" + tbCfOrderVo.getUserId() + ":" + couponId;
        orderRedisCache.delete(KeyConstant.ORDER_EXP + orderIdAndCouponId);
    }
}
