package cn.pluss.platform.util;

import cn.pluss.platform.entitiy.ActionInfo;
import cn.pluss.platform.entitiy.Scene;
import cn.pluss.platform.entitiy.WechatQRCode;
import cn.pluss.platform.wechat.Oauth2Util;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author yuchen
 * 
 * @Description 
 */
public class TemporaryQRcode {
	
	
	/**
	 * 
	 * @param accessToken    接口访问凭证 
	 * @param expireSeconds    二维码有效时间   单位为秒   最长 1800秒 （30天）
	 *                              也就是说永久二维码一共可以创建10000个    临时的多
	 * @return
	 */
	public static WechatQRCode createForeverTicket(String accessToken, int expireSeconds, String sceneStr)
	{
		WechatQRCode wechatQRCode = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";// 拼接请求地址
		requestUrl = requestUrl.replace("TOKEN", accessToken);
		Map<String, Object> map= new HashMap<>(16);
		map.put("expire_seconds", expireSeconds);
		map.put("action_name", "QR_STR_SCENE");
		ActionInfo actionInfo=new ActionInfo();
		Scene scene=new Scene();
		scene.setScene_str(sceneStr);
		actionInfo.setScene(scene);
		map.put("action_info",actionInfo);
		String jsonmsg = com.alibaba.fastjson.JSONObject.toJSONString(map);
		System.out.println(jsonmsg);
		JSONObject jsonObject = Oauth2Util.httpRequest(requestUrl, "POST", jsonmsg);// 创建永久带参二维码
		if (null != jsonObject)
		{
			System.out.println(jsonObject);
			try
			{
				wechatQRCode=new WechatQRCode();
				System.out.println(1);
				wechatQRCode.setTicket(jsonObject.getString("ticket"));
				wechatQRCode.setExpire_seconds(jsonObject.getInteger("expire_seconds"));
				wechatQRCode.setUrl(jsonObject.getString("url"));
				System.out.println("带参二维码ticket成功=" + wechatQRCode.getTicket()+"Expire_seconds="+wechatQRCode.getExpire_seconds()+wechatQRCode.getUrl());
			} catch (Exception e)
			{
				wechatQRCode =null;
				int err = jsonObject.getInteger("errcode");
				String errormsg = jsonObject.getString("errmsg");
				System.out.println("永久带参二维码ticket失败失败errcode=" + err + "errmsg=" + errormsg);
				}
		}
		return wechatQRCode;
	}
	
	public static String getRQcode(String ticket, String savepath) throws UnsupportedEncodingException
	{
		String filepath = null;
		String  visitpath=null;
		String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
		requestUrl = requestUrl.replace("TICKET", URLEncoder.encode(ticket, "utf-8"));
		try
		{
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			if (!savepath.endsWith("/")){
				savepath += "/";
			}
			// 将ticket 作为文件名
			filepath = savepath + ticket + ".jpg";
			Properties prop = System.getProperties();
			String os = prop.getProperty("os.name");
			if (os.startsWith("win") || os.startsWith("Win")) {
				visitpath="http://127.0.0.1/resources/manage/upload"+"/"+ticket+".jpg";
			}else {
				visitpath=ParametersUtil.upload_visit_path+"/"+ticket+".jpg";
			}
			// 将微信服务器返回的输入流写入文件
 
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(filepath);
 
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.close();
			bis.close();
 
			System.out.println(conn);
			conn.disconnect();
			System.out.println("根据ticket换取二维码成功");
		} catch (Exception e)
		{
			filepath = null;
			System.out.println("根据ticket换取二维码失败" + e);
		}
		return visitpath;
	}


	

}

