package com.icloud.server.wxserver;


import com.alibaba.fastjson.JSONObject;
import com.icloud.server.scala.engine.service.GoodsPayService;
import com.icloud.server.scala.engine.service.Goodspaye;
import io.swagger.annotations.Api;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.*;

/**获取微信参数授权
 * @Author : yang
 * @Date : 2022-04-30 12:06 AM
 * @Version : 2.1.2
 */
@Api( tags =  "获取微信参数授权" , value = "API" )
@RestController
@RequestMapping("wxconfigutils")
@CrossOrigin
public class WxConfigUtils {

    @Autowired
    private StringRedisTemplate stringredistemplate;
    @Autowired
    private AccessTokenAPI accesstokenapi;

    @Autowired
    private GoodsPayService goodspayservice;



    @PostMapping("getwxconfig")
    public Map<String,Object> getWxconfig(@RequestParam String goodsid, HttpServletRequest request, HttpServletResponse response){
        System.out.println("=====goodsid=======:"+goodsid);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("appId","");
        map.put("timestamp","");
        map.put("nonceStr","");
        map.put("signature","");
        //获取域名
        String realmname = request.getHeader("Referer");
        if(realmname==null){
            return map;
        }
        Goodspaye gp = goodspayservice.getGoodsPayById(goodsid);
        String appId=gp.payrealmname().appid();
        String appSecret=gp.payrealmname().secret();
//        gp.payrealmname

        String params = request.getQueryString();
        if(StringUtils.isEmpty(params)){
            params="";
        }else{
            params="?"+params;
        }
        String url = realmname+"/"+request.getRequestURI()+params;
        //request.getRequestURL().toString();

        // 时间戳
        String timestamp = Long.toString(System.currentTimeMillis()/ 1000);
        // 随机串
        String nonceStr = UUID.randomUUID().toString();

        //获取access_token
        String ak = stringredistemplate.opsForValue().get(realmname+"access_token");
        if(ak==null){
            AccessToken access_token=accesstokenapi.getAccessToken(appId,appSecret);
            stringredistemplate.opsForValue().set(realmname+"_access_token",access_token.getToken(), Duration.ofMinutes(120));
            ak=access_token.getToken();
        }

        // 根据 tocker 获取 jstl
        //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ak+"&type=jsapi";
        JSONObject jsonObject = HttpRequestUtil.httpRequest(urlStr, "");
        String ticket = jsonObject.getString("ticket");
        System.out.println("要加密的参数："+nonceStr+" "+ticket+" "+timestamp+" "+url);
        String signature = getsig(nonceStr,ticket,timestamp,url);
        String signature1 = getSignature(nonceStr, ticket, timestamp, url);
        System.out.println(signature);
        System.out.println(signature1);
        map.put("appId",appId);
        map.put("timestamp",timestamp);
        map.put("nonceStr",nonceStr);
        map.put("signature",signature);
        return map;
    }

    public static String getSignature( String nonceStr,String jsapiTicket,String timestamp,String url) {
        String gensignature = null;
        // 生成随机字符串
        // 时间戳
        // 通过jsapi_ticket、随机字符串、时间戳
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("jsapi_ticket=").append(jsapiTicket).append("&")
                .append("noncestr=").append(nonceStr).append("&")
                .append("timestamp=").append(timestamp).append("&")
                .append("url=").append(url.indexOf("#") >= 0 ? url.substring(0, url.indexOf("#")) : url);
        String signatureStr = stringBuilder.toString();
        gensignature = DigestUtils.sha1Hex(signatureStr);

        return gensignature;
    }


    private static String getsig(String noncestr,String jsapi_ticket,String timestamp,String url){
        String[] paramArr = new String[] { "jsapi_ticket=" + jsapi_ticket,
                "timestamp=" + timestamp, "noncestr=" + noncestr, "url=" + url };
        Arrays.sort(paramArr);
        // 将排序后的结果拼接成一个字符串
        String content = paramArr[0].concat("&"+paramArr[1]).concat("&"+paramArr[2])
                .concat("&"+paramArr[3]);
        String gensignature = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 对拼接后的字符串进行 sha1 加密
            System.out.println("拼接加密签名："+content);
            byte[] digest = md.digest(content.getBytes());
            gensignature = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将 sha1 加密后的字符串与 signature 进行对比
        if (gensignature != null) {
            return gensignature;// 返回signature
        } else {
            return "false";
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

}