package com.yonge.cooleshow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.config.HuifuConfiguration;
import com.yonge.cooleshow.enums.OrderStatusEnum;
import com.yonge.cooleshow.enums.PayChannelEnum;
import com.yonge.cooleshow.enums.PayStatusEnum;
import com.yonge.cooleshow.sdk.adapay.PaymentSdk;
import com.yonge.cooleshow.sdk.adapay.dto.RefundReq;
import com.yonge.cooleshow.sdk.req.DeviceInfo;
import com.yonge.cooleshow.sdk.req.OrderPayReq;
import com.yonge.cooleshow.sdk.adapay.dto.PaymentReq;
import com.yonge.cooleshow.sdk.req.OrderRefundReq;
import com.yonge.cooleshow.sdk.res.OrderRefundRes;
import com.yonge.cooleshow.sdk.res.OrderPayRes;
import com.yonge.cooleshow.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * Description
 *
 * @author liujunchi
 * @date 2022-04-21
 */
@Service("adapayPaymentService")
public class AdapayPaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentSdk paymentSdk;

    @Override
    public OrderPayRes orderPay(OrderPayReq payReq) {
        if (OrderStatusEnum.WAIT_PAY.equals(payReq.getOrderStatus())) {
            //处于待支付状态，需要调用汇付发起付款请求接口
            return orderPayWaitPay(payReq);
        } else if (OrderStatusEnum.PAYING.equals(payReq.getOrderStatus())) {
            //处于付款中状态，需要拉起付款接口返回信息，并且去到汇付
            return orderPayPaying(payReq);
        }
        OrderPayRes orderPayRes = new OrderPayRes();
        orderPayRes.setStatus(false);
        orderPayRes.setMessage("订单状态异常");
        return orderPayRes;
    }

    @Override
    public OrderPayRes orderPayWaitPay(OrderPayReq payReq) {
        PaymentReq paymentReq = new PaymentReq();
        paymentReq.setOrder_no(payReq.getOrderNo());
        paymentReq.setPay_channel(payReq.getPayChannel().getCode());
        paymentReq.setPay_amt(payReq.getOrderPrice().setScale(2, RoundingMode.HALF_UP).toString());
        paymentReq.setGoods_title(payReq.getGoodTitle());
        paymentReq.setGoods_desc(payReq.getGoodDesc());

        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDevice_ip(payReq.getIpAddress());

        paymentReq.setDevice_info(deviceInfo);
        //异步通知地址
        paymentReq.setNotify_url(HuifuConfiguration.getHuifuProperties().getNotifyUrl());

        if (PayChannelEnum.wx_lite.equals(payReq.getPayChannel())) {
            Map<String, Object> expend = new HashMap<>();
            expend.put("open_id", payReq.getOpenId());
            paymentReq.setExpend(expend);
        }
        //付款请求
        HttpResponseResult<Map<String, Object>> responseResult = paymentSdk.executePayment(paymentReq);
        OrderPayRes orderPayRes = new OrderPayRes();
        orderPayRes.setOrderNo(payReq.getOrderNo());
        orderPayRes.setPayChannel(payReq.getPayChannel().getCode());

        if (responseResult.getStatus()) {
            Map<String, Object> res = responseResult.getData();
            orderPayRes.setTransNo(res.get("id").toString());
            orderPayRes.setPay_amt(
                    new BigDecimal(res.get("pay_amt").toString()).setScale(2, RoundingMode.HALF_UP).toString()
            );
            String pay_info = ((JSONObject) res.get("expend")).getString("pay_info");
            orderPayRes.setPay_info(pay_info);
            orderPayRes.setPayStatus(PayStatusEnum.pending);
            return orderPayRes;
        } else {
            //入订单付款表，同时修改订单状态
            orderPayRes.setPayStatus(PayStatusEnum.failed);
            orderPayRes.setStatus(false);
            orderPayRes.setMessage(responseResult.getMsg());
            return orderPayRes;
        }
    }

    @Override
    public OrderPayRes orderPayPaying(OrderPayReq payReq) {
        OrderPayRes orderPayRes = new OrderPayRes();
        if (OrderStatusEnum.PAYING.getCode().equals(payReq.getOrderStatus().getCode())) {
            orderPayRes.setPay_info(payReq.getPayInfo());
            orderPayRes.setPay_amt(payReq.getOrderPrice().toString());
        } else {
            orderPayRes.setStatus(false);
            orderPayRes.setMessage("订单不处于支付状态中");
        }
        return orderPayRes;
    }

    @Override
    public OrderRefundRes orderRefund(OrderRefundReq orderRefundReq) {
        RefundReq refundReq = new RefundReq();
        refundReq.setRefund_order_no(orderRefundReq.getTransNo());
        refundReq.setRefund_amt(orderRefundReq.getRefundAmount());
        refundReq.setId(orderRefundReq.getTransNo());
        refundReq.setReason(orderRefundReq.getReason());
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDevice_ip(orderRefundReq.getIpAddress());

        refundReq.setDevice_info(deviceInfo);

        //异步通知地址
        refundReq.setNotify_url(HuifuConfiguration.getHuifuProperties().getNotifyUrl());
        //付款请求
        HttpResponseResult<Map<String, Object>> responseResult = paymentSdk.refundPayment(refundReq);

        OrderRefundRes  orderRefundRes = new OrderRefundRes();
        if (responseResult.getStatus()) {
            Map<String, Object> data = responseResult.getData();
            orderRefundRes.setTransNo(data.get("id").toString());
            orderRefundRes.setPayTransNo(data.get("payment_id").toString());
            orderRefundRes.setRefundOrderNo(data.get("refund_order_no").toString());
            orderRefundRes.setRefundAmount(new BigDecimal(data.get("refund_amt").toString())
                                                   .setScale(2,RoundingMode.HALF_UP).toString());
            orderRefundRes.setRefundStatus(PayStatusEnum.pending);

        } else {
            orderRefundRes.setStatus(false);
            orderRefundRes.setMessage(responseResult.getMsg());
        }
        return orderRefundRes;
    }
}
