package com.cyl.external;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cyl.external.resp.AccessTokenResp;
import com.cyl.external.resp.BaseResp;
import com.cyl.external.resp.UserInfoResp;
import com.cyl.wechat.WechatPayData;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "wechat")
@Slf4j
public class WechatUtil {
    private static String appId;
    private static String secret;
    public void setAppId(String appId) {
        WechatUtil.appId = appId;
    }
    public void setSecret(String secret) {
        WechatUtil.secret = secret;
    }
    public static boolean validParam(String signature, String... arr) {
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        String[] var2 = arr;
        int var3 = arr.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String a = var2[var4];
            sb.append(a);
        }

        return signature.equals(DigestUtils.sha1Hex(sb.toString()));
    }
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    public static AccessTokenResp getAccessToken(String code) {
        String url = ACCESS_TOKEN_URL.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
        String res = HttpUtil.get(url);
        AccessTokenResp resp = JSON.parseObject(res, AccessTokenResp.class);
        validResp(resp);
        return resp;
    }

    public static UserInfoResp getUserInfo(String accessToken, String openid) {
        String url = USER_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        String res = HttpUtil.get(url);
        UserInfoResp resp = JSON.parseObject(res, UserInfoResp.class);
        validResp(resp);
        return resp;
    }
    public static void validResp(BaseResp resp) {
        if (resp.getErrcode() != null) {
            throw new ExternalException(resp.getErrcode() + "", resp.getErrmsg());
        }
    }

    public static Object getPhoneNumber(String code, Integer sourceType)
    {
        //通过appid和secret来获取token
        //WXContent.APPID是自定义的全局变量
        //String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/getStableAccessToken?grant_type=client_credential&appid=%s&secret=%s", appId, secret);
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/stable_token");
        log.info(tokenUrl.toString());

        Map<String, Object> paramMap1 = new HashMap<>();
        paramMap1.put("grant_type","client_credential");
        if (new Integer("1").equals(sourceType)) {
            paramMap1.put("appid", WechatPayData.staffAppId);
            paramMap1.put("secret", WechatPayData.staffSecret);
        }else {
            paramMap1.put("appid", WechatPayData.miniProgramAppId);
            paramMap1.put("secret", WechatPayData.miniProgramSecret);
        }

        log.info(paramMap1.toString());
        String result = HttpUtils.sendPost(tokenUrl,JSONObject.toJSONString(paramMap1));
                //.post(tokenUrl, paramMap1);
        //String result = HttpUtil.get(tokenUrl);

        log.info(result);
        JSONObject token = JSON.parseObject(result);

        //通过token和code来获取用户手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        log.info(url);
        //封装请求体
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);

        String phoneInfo = HttpUtils.sendPost(url, JSONObject.toJSONString(paramMap));
        //String phoneInfo = HttpUtil.post(url, paramMap);

        //封装请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//
//        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);
//
//        //通过RestTemplate发送请求，获取到用户手机号码
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

        log.info(phoneInfo);


        JSONObject respPhoneObj = JSONObject.parseObject(phoneInfo);
        JSONObject phoneObj = (JSONObject) respPhoneObj.get("phone_info");

        //获取手机号
        String phone = phoneObj.getString("phoneNumber");


        //返回到前端展示
        return phone;
    }
}
