package com.wteam.framework.modules.pay.serviceimpl.handler;

import com.alibaba.fastjson.JSON;
import com.egzosn.pay.common.api.DefaultPayMessageHandler;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.egzosn.pay.wx.v3.bean.response.WxPayMessage;
import com.wteam.framework.common.utils.SpringContextUtil;
import com.wteam.framework.modules.book.service.OrderInfoService;

import com.wteam.framework.modules.pay.entity.enums.PaymentMethodEnum;
import com.wteam.framework.modules.pay.entity.vo.CallbackParamVO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

/**
 * 微信支付回调处理器
 * Created by ZaoSheng on 2016/6/1.
 */
@Slf4j
@Component
public class WxV3PayMessageHandler implements PayMessageHandler<WxPayMessage, PayService> {



    private final Logger LOG = LoggerFactory.getLogger(DefaultPayMessageHandler.class);


    @Override
    public PayOutMessage handle(WxPayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
        LOG.info("回调支付消息处理器，回调消息：{}", JSON.toJSONString(payMessage));
        //订单号
        String outTradeNo = payMessage.getOutTradeNo();
        Map<String, Object> message = payMessage.getPayMessage();
        //交易状态
        String tradeStatus = (String) message.get("trade_state");
        String transactionId = (String) message.get("transaction_id");
        Date successTime = (Date) payMessage.getSuccessTime();
        Map<String, Object> map = (Map<String, Object>) message.get("amount");
        Integer intValue = (Integer) map.get("payer_total");
        BigDecimal payAmount = new BigDecimal(intValue).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
        CallbackParamVO callbackParamVO = new CallbackParamVO(transactionId, outTradeNo, PaymentMethodEnum.WECHAT.name(), payAmount, successTime);
        if ("SUCCESS".equals(tradeStatus)) {
//            异步处理订单
            OrderInfoService orderInfoService = (OrderInfoService) SpringContextUtil.getBean(OrderInfoService.class);
            Boolean aBoolean = orderInfoService.checkOrder(Long.valueOf(outTradeNo));
            if (!aBoolean) {
                return payService.getPayOutMessage("SUCCESS", "成功");
            }
            orderInfoService.processOrders(callbackParamVO);
            return payService.getPayOutMessage("SUCCESS", "成功");
        }
        return payService.getPayOutMessage("FAIL", "失败");
    }


}
