package com.wteam.framework.common.utils;

import com.alipay.api.internal.util.codec.Base64;
import com.wteam.framework.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

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

@Slf4j
public class QRCode {
    public Object getWxCode(String accessToken, String page, String scene, String checkPath, String envVersion) {
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            RestTemplate rest = new RestTemplate();
            Map<String, Object> param = new HashMap<>();
            // 限制32位
            param.put("scene", scene);
            // 跳转的页面，默认首页面，非必填
            param.put("page", page);
            param.put("check_path", false);//checkPath
            param.put("width", 430);
            param.put("auto_color", false);
            param.put("env_version", "trial");//envVersion
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            log.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
//            log.info(Base64.encodeBase64String(result));
            String res = Base64.encodeBase64String(result);
            if (StringUtils.isNotBlank(res)) {
//                "data:image/jpg;base64," +
                String encoded = res.replaceAll("[\\s*\t\n\r]", "");
                return encoded;
            }
            return result;
        } catch (Exception e) {
            log.error("调用小程序生成二维码失败:{}", e);
            throw new ServiceException("调用小程序生成二维码失败");
        }
//        return null;
    }

    /**
     * 获取小程序二维码--》128字节
     *
     * @param accessToken
     * @param path
     * @param
     * @return
     */
    public Object getWxCodelimit(String accessToken, String path) {
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
            RestTemplate rest = new RestTemplate();
            Map<String, Object> param = new HashMap<>();
            // 限制32位
//            param.put("scene", scene);
            // 跳转的页面，默认首页面，非必填
            param.put("path", path);
//            param.put("check_path",false);//checkPath
            param.put("width", 430);
            param.put("auto_color", false);
//            param.put("env_version","trial");//envVersion
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            log.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
//            log.info(Base64.encodeBase64String(result));
            String res = Base64.encodeBase64String(result);
            if (StringUtils.isNotBlank(res)) {
//                "data:image/jpg;base64," +
                String encoded = res.replaceAll("[\\s*\t\n\r]", "");
                return encoded;
            }
            return result;
        } catch (Exception e) {
            log.error("调用小程序生成二维码失败:{}", e);
            throw new ServiceException("调用小程序生成二维码失败");
        }
    }


//
//    /**
//     * 生成不限个数的小程序码（建议使用）
//     *
//     * @param accessToken
//     * @param filePath
//     * @return
//     */
//    public static void getminiqrQr(String accessToken, String filePath) {
//        String WxCode_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";//小程序密钥
////        String fileName = "code1.png";
//        String fileName = UUID.randomUUID().toString();
//        try {
//            String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN", accessToken);
//            URL url = new URL(wxCodeURL);
//            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//            httpURLConnection.setRequestMethod("POST");// 提交模式
//            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
//            // conn.setReadTimeout(2000);//读取超时 单位毫秒
//            // 发送POST请求必须设置如下两行
//            httpURLConnection.setDoOutput(true);
//            httpURLConnection.setDoInput(true);
//            // 获取URLConnection对象对应的输出流
//            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//            // 发送请求参数
//            JSONObject paramJson = new JSONObject();
//            // 注意小程序页面如果不存在，则注释掉page参数
//            //paramJson.put("page", "pages/index/index");
//            paramJson.put("scene", "1234567890");
//            paramJson.put("width", 430);
//            paramJson.put("is_hyaline", true);
//            paramJson.put("auto_color", true);
//            printWriter.write(paramJson.toString());
//            // flush输出流的缓冲
//            printWriter.flush();
//            //开始获取数据
//            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//            OutputStream os = new FileOutputStream(new File(filePath + fileName));
//            int len;
//            byte[] arr = new byte[1024];
//            while ((len = bis.read(arr)) != -1) {
//                os.write(arr, 0, len);
//                os.flush();
//            }
//            //-----------------可能是在这里把流/二进制文件返回吧
//            os.close();
//        } catch (Exception e) {
//            log.error("===> error : ", e);
//        }
//    }


}
