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.apache.commons.codec.digest.DigestUtils;
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 org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

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.*;

@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();
        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 = createSign(payData, wxConfig.getMchKey());
            payData.put("paySign", sign); // 将签名放入参数中
            System.out.println(payData);
            return payData;
        } catch (WxPayException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String createSign(Map<String, String> params, String signKey) {
        // 1. 对参数进行排序
        StringBuilder toSign = new StringBuilder();
        for (String key : new TreeMap<>(params).keySet()) {
            String value = params.get(key);
            if (value != null && !value.isEmpty()) {
                toSign.append(key).append("=").append(value).append("&");
            }
        }
        toSign.append("key=").append(signKey); // 2. 添加商户密钥

        // 3. 生成签名
        return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); // 使用 MD5 签名
    }


    public String getOpenIdCode(Long userId, String ip) throws UnsupportedEncodingException {
        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_userinfo", userId);
    }

    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());
            System.out.println(map.get("openid").toString() +"openid 是什么--------------------------------");
            return map.get("openid").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;  // 或者处理错误
        }
    }


    public String getAccessToken(String code) {
        RestTemplate restTemplate = new RestTemplate();
        String url = UriComponentsBuilder.fromHttpUrl(wxConfig.getTokenUrl())
                .queryParam("appid", wxConfig.getAppId())
                .queryParam("secret", wxConfig.getSecret())
                .queryParam("code", code)
                .queryParam("grant_type", "authorization_code")
                .toUriString();

        return restTemplate.getForObject(url, String.class);
    }

    public String getUserInfo(String accessToken, String openId) {
        RestTemplate restTemplate = new RestTemplate();
        String url = UriComponentsBuilder.fromHttpUrl(wxConfig.getUserInfoUrl())
                .queryParam("access_token", accessToken)
                .queryParam("openid", openId)
                .queryParam("lang", "zh_CN")
                .toUriString();

        return restTemplate.getForObject(url, String.class);
    }

}
