package com.yn.bftl.thirdparty.modules.business.service.impl;

import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.common.common.util.RouteUtil;
import com.yn.bftl.common.modules.account.entity.Payment;
import com.yn.bftl.common.modules.order.entity.Order;
import com.yn.bftl.common.modules.order.enums.PayStatus;
import com.yn.bftl.common.modules.order.enums.PaymentMethod;
import com.yn.bftl.common.modules.order.enums.UnionpayAppTradeStatus;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.exception.YnceNoRollErrorException;
import com.yn.bftl.thirdparty.common.repository.PaymentRepository;
import com.yn.bftl.thirdparty.modules.business.service.PaymentService;
import com.yn.bftl.thirdparty.modules.unionpay.service.UmsPayService;
import com.yn.bftl.thirdparty.modules.unionpay.vo.base.UnionpayResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 支付服务实现类
 *
 * @author huabiao
 * @create 2023/4/20  21:23
 **/
@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private PaymentRepository paymentRepository;
    @Resource
    private UmsPayService umsPayService;

    @Override
    public void checkPaymentStatus(Order order) {
        Long companyId = order.getConsignmentCompany() != null ? order.getConsignmentCompany().getId() : order.getSellerCompany().getId();
        // 判断支付单是否已支付
        List<Payment> paymentList = paymentRepository.findAllByOrderId(order.getId().toString());
        for (Payment payment : paymentList) {
            // 预存款
            if (payment.getPaymentMethod().equals(PaymentMethod.DEPOSIT) && (payment.getPayStatus().equals(PayStatus.SUCC) || payment.getPayStatus().equals(PayStatus.PROGRESS))) {
                throw new YnceErrorException(YnceError.YNCE_204093);
            } else if (payment.getPaymentMethod().equals(PaymentMethod.WECHAT) || payment.getPaymentMethod().equals(PaymentMethod.ALIPAY) || payment.getPaymentMethod().equals(PaymentMethod.CHINA_UNIONPAY_QUICK_PASS)) {
                if (payment.getPayStatus().equals(PayStatus.SUCC) || payment.getPayStatus().equals(PayStatus.PROGRESS)) {
                    throw new YnceErrorException(YnceError.YNCE_204093);
                } else if (payment.getPayStatus().equals(PayStatus.READY)) {
                    if (StringUtils.isNotBlank(payment.getUnionpaySn())) {
                        String route = RouteUtil.ROUTE_UNIONPAY_NETPAY_QUERY;
                        if (payment.getPaymentMethod().equals(PaymentMethod.ALIPAY)) {
                            route = RouteUtil.ROUTE_UNIONPAY_NETPAY_QUERY_TRADE;
                        } else if (payment.getPaymentMethod().equals(PaymentMethod.WECHAT)) {
                            route = RouteUtil.ROUTE_UNIONPAY_NETPAY_QUERY_WX;
                        }
                        try {
                            UnionpayResponseVO unionpayResponseVO = umsPayService.tradeQuery(route, payment.getUnionpaySn(), companyId);
                            if (UnionpayAppTradeStatus.UNKNOWN.equals(unionpayResponseVO.getStatus()) || UnionpayAppTradeStatus.TRADE_SUCCESS.equals(unionpayResponseVO.getStatus())) {
                                throw new YnceErrorException(YnceError.YNCE_204093);
                            } else if (UnionpayAppTradeStatus.NEW_ORDER.equals(unionpayResponseVO.getStatus()) || UnionpayAppTradeStatus.WAIT_BUYER_PAY.equals(unionpayResponseVO.getStatus())) {
                                // 银联未支付订单默认过期时间30分钟   云闪付不支持订单关闭
                                if (!payment.getPaymentMethod().equals(PaymentMethod.CHINA_UNIONPAY_QUICK_PASS) && LocalDateTime.now().isBefore(payment.getCreatedOn().plusMinutes(30))) {
                                    String closeRoute = RouteUtil.ROUTE_UNIONPAY_NETPAY_CLOSE;
                                    if (payment.getPaymentMethod().equals(PaymentMethod.ALIPAY)) {
                                        closeRoute = RouteUtil.ROUTE_UNIONPAY_NETPAY_TRADE_CLOSE;
                                    } else if (payment.getPaymentMethod().equals(PaymentMethod.WECHAT)) {
                                        closeRoute = RouteUtil.ROUTE_UNIONPAY_NETPAY_WX_CLOSE;
                                    }
                                    try {
                                        UnionpayResponseVO closeResponseVO = umsPayService.tradeClose(closeRoute, payment.getUnionpaySn(), companyId);
                                        if (UnionpayAppTradeStatus.TRADE_CLOSED.equals(closeResponseVO.getStatus())) {
                                            payment.setPayStatus(PayStatus.CANCEL);
                                            paymentRepository.save(payment);
                                        }
                                    } catch (Exception e) {
                                        throw new YnceNoRollErrorException(e.getMessage());
                                    }
                                }
                            }
                        } catch (YnceNoRollErrorException ye) {
                            throw new YnceErrorException(ye.getMessage());
                        } catch (Exception e) {
                            log.warn("聚合支付查询支付单状态异常 - ", e);
                        }
                    }
                }

            } else if (payment.getPaymentMethod().equals(PaymentMethod.POS) &&
                    (payment.getPayStatus().equals(PayStatus.SUCC) || payment.getPayStatus().equals(PayStatus.PROGRESS))) {
                throw new YnceErrorException(YnceError.YNCE_204093);
            }
        }
    }
}
