package com.dk.mdm.service.wxapi.basic;

import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.util.*;
import com.dk.mdm.infrastructure.config.WechatPayConfigInfo;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付服务
 * 后台管理设置的金额 从dkic_ms里取数据 金额
 * 所以放到了 权限的oauth-server 的服务里240327--作废
 * @author 姜永辉
 * @since 20223-07-01 09:41:05
 */
@Service("wechatPayService")
@Slf4j
public class WechatPayService {
    @Autowired
    private WechatPayConfigInfo wechatPayConfigInfo;

    /**
     * 商户 下单选取旗舰版或专业版的订单
     *
     * @param param
     * @return
     * @throws WxPayException
     */
    public ResponseResultVO unifiedOrder(Map<String, Object> param) throws WxPayException {
        String paymentSn = param.get("paymentSn").toString();
        String openId = param.get("openId").toString();
        log.info("下单选取旗舰版或专业版的订单1----------" + param.toString());
        try {
            // 获取单据的金额 --后台管理设置的金额 从dkic_ms里取数据 金额
            // 所以放到了 权限的oauth-server 的服务里
            // todo。。。。。。。。。。。。

            String payFee = "0.01";
            WxPayService wxPayService = this.getWxPayService();
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody("商品测试");
            orderRequest.setOutTradeNo(paymentSn);
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(payFee.toString()));//元转成分
            orderRequest.setOpenid(openId);
            orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            orderRequest.setNotifyUrl(wechatPayConfigInfo.getWechatNotifyUrl() + "/" + wechatPayConfigInfo.getAppId());
            orderRequest.setTradeType("JSAPI");
            // 生成预支付订单
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxPayService.unifiedOrder(orderRequest);
            String prepay_id = wxPayUnifiedOrderResult.getPrepayId();
            String timeStamp = new Date().getTime() + "";
            String nonceStr = UUID.fastUUID().toString(true);
            String pack = "prepay_id=" + prepay_id;
            String signType = "MD5";
            String paySign = "";
            String sigmTemp = "appId=" + wxPayUnifiedOrderResult.getAppid() + "&nonceStr=" + nonceStr + "&package="
                    + pack + "&signType=" + signType + "&timeStamp=" + timeStamp;
            sigmTemp = sigmTemp + "&key=" + wechatPayConfigInfo.getMchKey();
            paySign = Md5Utils.hash(sigmTemp);
            log.info("下单选取旗舰版或专业版的订单2----------" + prepay_id + "--" + sigmTemp + "--");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("appId", wxPayUnifiedOrderResult.getAppid());
            params.put("timeStamp", timeStamp);
            params.put("nonceStr", nonceStr);
            params.put("pack", pack);
            params.put("signType", signType);
            params.put("paySign", paySign);
            log.info("下单选取旗舰版或专业版的订单3----------" + params.toString());
            return ResponseResultUtil.success(params);
        } catch (Exception e) {
            log.error("unifiedOrder--微信支付失败！支付单号：{},原因:{}", paymentSn, e.getMessage());
            return ResponseResultUtil.error("支付失败，请稍后重试！");
        }
    }

    /**
     * @desc : 处理支付成功逻辑
     * @author : 姜永辉
     * @date : 2024/03/06 11:29
     */
    public ResponseResultVO notifyWechatPay(WxPayOrderNotifyResult info) {
        log.info("处理支付成功逻辑----------" + info.getOutTradeNo() + "---------" + info.toString());

//  判断支付金额是否一致
//        ShopOrderPaymentDto sop = new ShopOrderPaymentDto();
//        sop.setPaymentsn(info.getOutTradeNo());
//        sop.setPaystatus(0L);
//        ShopOrderPayment shopOrderPaymentReturn = shopOrderPaymentMapper.selectEntity(sop);
//        log.info("从订单流水表没有查到数据----------" + info.getOutTradeNo());
//        if (shopOrderPaymentReturn == null) {
//            log.error("从订单流水表没有查到数据----------" + info.getOutTradeNo());
//            return ResponseResultUtil.error("从订单流水表没有查到数据----------" + info.getOutTradeNo());
//        }
//        // //  230918  在生成 微信码时候插入 待支付的 数据
//        BigDecimal payFee = new BigDecimal(info.getTotalFee()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
//        log.info("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
//                + "--" + payFee);
//        if (shopOrderPaymentReturn.getAmount().compareTo(payFee) != 0) {
//            log.error("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
//                    + "--" + payFee);
//            return CommonResult.fail("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
//                    + "--" + payFee);
//
//        }
        //判断是否已经做支付处理
//        log.info("判断是否已经做支付处理----------" + shopOrderPaymentReturn.getPaystatus().toString());

        return ResponseResultUtil.success();
    }

    /**
     * @desc : 获取商户配置信息
     * @author : 姜永辉
     * @date : 2023-08-02 17:30
     */
    public WxPayService getWxPayService() {
        log.info("getWxPayService----------" + wechatPayConfigInfo.toString());
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(wechatPayConfigInfo.getAppId()));
        payConfig.setMchId(StringUtils.trimToNull(wechatPayConfigInfo.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(wechatPayConfigInfo.getMchKey()));
//        payConfig.setSubAppId(null);
//        payConfig.setSubMchId(null);
//        payConfig.setKeyPath(StringUtils.trimToNull(wechatPayConfigInfo.getKeyPath()));
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}
