package com.hys.app.pay.wx;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
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 com.github.binarywang.wxpay.util.SignUtils;
import com.github.wxpay.sdk.WXPayUtil;
import com.hys.app.framework.database.annotation.Id;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.JsonUtil;
import com.hys.app.pay.ali.PayOrder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class WxPayServiceMy {
    @Resource
    private WxConfig wxConfig;

    private WxPayService getPayService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(wxConfig.getAppId());
        payConfig.setMchId(wxConfig.getMchId());
        payConfig.setMchKey(wxConfig.getMchKey());
        payConfig.setKeyPath(wxConfig.getKeyPath());
        payConfig.setApiV3Key(wxConfig.getApiV3Key());
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }


    public Object pay(PayOrder payOrder) throws UnknownHostException, WxPayException {
//        WxPayService wxPayService = getPayService();
//        //H5
//        WxPayUnifiedOrderRequest build = WxPayUnifiedOrderRequest.newBuilder()
//                .body(payOrder.getSubject())
//                .outTradeNo(payOrder.getTraceNo())
//                .feeType("CNY")
//                .totalFee((int) Math.round(payOrder.getTotalAmount() * 100))
//                .spbillCreateIp(InetAddress.getLocalHost().getHostAddress())
//                .notifyUrl(wxConfig.getNotifyUrl())
//                .tradeType("MWEB")
//                .build();
//        //        // 设置商户子账户id
//        build.setSubMchId(wxConfig.getSubMchId());
//        WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxPayService.unifiedOrder(build);
//        return wxPayUnifiedOrderResult.getMwebUrl(); // 包含 mweb_url


//        WxPayUnifiedOrderRequest orderRequest = WxPayUnifiedOrderRequest.newBuilder()
//                .body(payOrder.getSubject())
//                .outTradeNo(payOrder.getTraceNo())
//                .totalFee((int) Math.round (payOrder.getTotalAmount()*100)) // 单位是分
//                .spbillCreateIp(InetAddress.getLocalHost().getHostAddress())
//                .notifyUrl(wxConfig.getNotifyUrl())
//                .tradeType("NATIVE")
//                .productId(IdUtil.fastUUID())
//                .build();
//        // 设置商户子账户id
//        orderRequest.setSubMchId(wxConfig.getSubMchId()); //
//        try {
//            WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(orderRequest);
//            return result.getCodeURL(); // 获取生成的二维码URL
//        } catch (WxPayException e) {
//            e.printStackTrace();
//            return null;
//        }


        WxPayService wxPayService = getPayService();

        WxPayUnifiedOrderRequest orderRequest = WxPayUnifiedOrderRequest.newBuilder()
                .body(payOrder.getSubject())
                .openid(payOrder.getOpenId())
                .outTradeNo(payOrder.getTraceNo())
                .totalFee((int) Math.round(payOrder.getTotalAmount() * 100)) // 单位是分
                .spbillCreateIp(InetAddress.getLocalHost().getHostAddress())
                .notifyUrl(wxConfig.getNotifyUrl())
                .tradeType("JSAPI")
                .productId(IdUtil.fastUUID())
                .build();

        // 设置商户子账户id
        orderRequest.setSubMchId(wxConfig.getSubMchId());
        try {
            WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(orderRequest);
            Map<String, String> payData = new HashMap<>();
            payData.put("appId", wxConfig.getAppId());
            payData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
            payData.put("nonceStr", result.getNonceStr());
            payData.put("package", "prepay_id=" + result.getPrepayId());
            payData.put("signType", "MD5");
            String sign = SignUtils.createSign(payData, wxPayService.getConfig().getMchKey(), null, null);
            payData.put("paySign", sign);
            System.out.println(payData);
            return payData;
        } catch (WxPayException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getOpenIdCode(Long orderId, String ip) throws UnsupportedEncodingException {
        String oAuth2Url = wxConfig.getOAuth2Url();
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("ip", ip);
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                wxConfig.getAppId(), URLEncoder.encode(wxConfig.getOAuth2Url(), "UTF-8"), "snsapi_base", orderId+"--"+ip);
    }

    public String getOpenId(String code) {

        String urlString = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                wxConfig.getAppId(), wxConfig.getSecret(), code);
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            Map<String, Object> map = JsonUtil.toMap(response.toString());
            return map.get("openid").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;  // 或者处理错误
        }
    }
}
