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

import com.alibaba.fastjson.JSON;
import com.yn.bftl.common.common.util.RouteUtil;
import com.yn.bftl.common.modules.configuration.entity.ThirdPartyPaySet;
import com.yn.bftl.common.modules.order.entity.AfterSale;
import com.yn.bftl.common.modules.order.entity.Order;
import com.yn.bftl.common.modules.order.entity.OrderFeeRatio;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.modules.unionpay.dto.UnionpayPreOrderDTO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.UnionpayRefundDTO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.UnionpaySubOrderItemDTO;
import com.yn.bftl.thirdparty.modules.unionpay.enums.UnionpayAppOrderType;
import com.yn.bftl.thirdparty.modules.unionpay.repository.OrderFeeRatioRepository;
import com.yn.bftl.thirdparty.modules.unionpay.service.UmsPayService;
import com.yn.bftl.thirdparty.modules.unionpay.util.UnionpayUtil;
import com.yn.bftl.thirdparty.modules.unionpay.vo.base.UnionpayResponseVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全民付服务实现
 *
 * @author huabiao
 * @create 2022/9/5  17:10
 **/
@Service
public class UmsPayServiceImpl implements UmsPayService {

    @Resource
    private UnionpayUtil unionpayUtil;
    @Resource
    private OrderFeeRatioRepository orderFeeRatioRepository;

    @Override
    public Map<String, Object> appPreOrder(Order order, String unionpaySn, UnionpayAppOrderType unionpayAppOrderType) {
        LocalDateTime now = LocalDateTime.now();
        // 拼接请求参数
        Long companyId = order.getConsignmentCompany() != null ? order.getConsignmentCompany().getId() : order.getSellerCompany().getId();
        ThirdPartyPaySet thirdPartyPaySet = unionpayUtil.getThirdPartyPaySet(companyId);
        UnionpayPreOrderDTO unionpayPreOrderDTO = UnionpayPreOrderDTO.builder()
                .requestTimestamp(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .merOrderId(unionpaySn)
                .mid(thirdPartyPaySet.getUnionpayMid())
                .tid(thirdPartyPaySet.getUnionpayTid())
                .expireTime(null)
                .orderDesc(null)
                .originalAmount(order.getGoodsAmount().multiply(new BigDecimal(100)).longValue())
                .totalAmount(order.getAmount().multiply(new BigDecimal(100)).longValue())
                .divisionFlag(false)
                .notifyUrl(thirdPartyPaySet.getUnionpayCallbackUrl())
                .build();
        if (UnionpayAppOrderType.WECHAT.equals(unionpayAppOrderType)) {
            unionpayPreOrderDTO.setTradeType("APP");
            unionpayPreOrderDTO.setSubAppId(thirdPartyPaySet.getUnionpayWechatSubAppId());
        }
        // 调用银联接口
        return unionpayUtil.execute(unionpayUtil.getRequestUrl(unionpayAppOrderType), JSON.toJSONString(unionpayPreOrderDTO), now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")), companyId).getAppPayRequest();
    }

    @Override
    public String refund(String unionpaySn, BigDecimal refundAmount, Long companyId) {
        ThirdPartyPaySet thirdPartyPaySet = unionpayUtil.getThirdPartyPaySet(companyId);
        String unionpayRefundSn = unionpayUtil.generateUnionpaySn(AfterSale.class, companyId);
        LocalDateTime now = LocalDateTime.now();

        UnionpayRefundDTO unionpayRefundDTO = UnionpayRefundDTO.builder()
                .requestTimestamp(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .merOrderId(unionpaySn)
                .mid(thirdPartyPaySet.getUnionpayMid())
                .tid(thirdPartyPaySet.getUnionpayTid())
                .refundAmount(refundAmount.multiply(new BigDecimal(100)).longValue())
                .refundOrderId(unionpayRefundSn)
                .build();
        // 调用退款接口
        return unionpayUtil.execute(RouteUtil.ROUTE_UNIONPAY_REFUND, JSON.toJSONString(unionpayRefundDTO), now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")), companyId).getRefundOrderId();
    }

    @Override
    public UnionpayResponseVO tradeQuery(String route, String merOrderId, Long companyId) {
        LocalDateTime now = LocalDateTime.now();
        ThirdPartyPaySet thirdPartyPaySet = unionpayUtil.getThirdPartyPaySet(companyId);
        Map<String, Object> dto = new HashMap<>();
        dto.put("requestTimestamp", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        dto.put("mid", thirdPartyPaySet.getUnionpayMid()); // 商户号
        dto.put("tid", thirdPartyPaySet.getUnionpayTid()); // 终端号
        dto.put("instMid", "APPDEFAULT"); // 业务类型
        dto.put("merOrderId", merOrderId); // 商户订单号
        return unionpayUtil.execute(route, JSON.toJSONString(dto), now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")), companyId);
    }

    @Override
    public UnionpayResponseVO tradeClose(String route, String merOrderId, Long companyId) {
        LocalDateTime now = LocalDateTime.now();
        ThirdPartyPaySet thirdPartyPaySet = unionpayUtil.getThirdPartyPaySet(companyId);
        Map<String, Object> dto = new HashMap<>();
        dto.put("requestTimestamp", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        dto.put("mid", thirdPartyPaySet.getUnionpayMid()); // 商户号
        dto.put("tid", thirdPartyPaySet.getUnionpayTid()); // 终端号
        dto.put("instMid", "APPDEFAULT"); // 业务类型
        dto.put("merOrderId", merOrderId); // 商户订单号
        return unionpayUtil.execute(route, JSON.toJSONString(dto), now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),companyId);
    }
}
