package com.ssj.framework.weixin.card.util;

import com.alibaba.fastjson.JSONObject;
import com.ssj.framework.weixin.card.bean.GiftCardOrder;
import com.ssj.framework.weixin.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class GiftCardUtil {
	
	private  static Logger logger = LoggerFactory.getLogger(GiftCardUtil.class);
	
	//上传
	public static String API_UPLOAD_IMAGE="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN&type=TYPE";
	
	//创建礼品卡接口
	public static String API_GIFTCARD_CREATE="https://api.weixin.qq.com/card/create?access_token=ACCESS_TOKEN";
	
	//get礼品卡接口
	public static String API_GIFTCARD_GET="https://api.weixin.qq.com/card/get?access_token=ACCESS_TOKEN";
	
	//update礼品卡接口
	public static String API_GIFTCARD_UPDATE="https://api.weixin.qq.com/card/update?access_token=ACCESS_TOKEN";
	
	//查询-单个礼品卡订单信息接口
	public static String API_GIFTCARD_ORDER_GET="https://api.weixin.qq.com/card/giftcard/order/get?access_token=ACCESS_TOKEN";
	
	//创建-礼品卡货架接口
	public static String API_GIFTCARD_PAGE_ADD="https://api.weixin.qq.com/card/giftcard/page/add?access_token=ACCESS_TOKEN";
	
	//查询-礼品卡货架信息接口
	public static String API_GIFTCARD_PAGE_GET="https://api.weixin.qq.com/card/giftcard/page/get?access_token=ACCESS_TOKEN";
		
	//修改-礼品卡货架信息接口
	public static String API_GIFTCARD_PAGE_UPDATE="https://api.weixin.qq.com/card/giftcard/page/update?access_token=ACCESS_TOKEN";
		
	//查询-礼品卡货架列表接口
	public static String API_GIFTCARD_PAGE_BATCHGET="https://api.weixin.qq.com/card/giftcard/page/batchget?access_token=ACCESS_TOKEN";
			
	//下架-礼品卡货架接口
	public static String API_GIFTCARD_PAGE_MAINTAIN_SET="https://api.weixin.qq.com/card/giftcard/maintain/set?access_token=ACCESS_TOKEN";
	
	//上传小程序代码
	public static String API_GIFTCARD_WXA_SET="https://api.weixin.qq.com/card/giftcard/wxa/set?access_token=ACCESS_TOKEN";
	
	
	
	// 创建礼品卡接口
	public static void createGiftCard(String accessToken,String json){
		 String url = API_GIFTCARD_CREATE.replace("ACCESS_TOKEN", accessToken);  
		 WeixinUtil.httpRequest(url, "POST", json); 
	}
	
	
	public static JSONObject uploadMediaJson(String accessToken,String filePath) throws Exception {
		String result = null;
		String uploadMediaUrl = API_UPLOAD_IMAGE.replace("ACCESS_TOKEN", accessToken).replace("TYPE", "image");
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}
		URL urlObj = new URL(uploadMediaUrl);
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
		con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用缓存
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
				+ BOUNDARY);

		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
				+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");
		OutputStream out = new DataOutputStream(con.getOutputStream());
		out.write(head);

		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

		out.write(foot);
		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			logger.error("数据读取异常", e);
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		JSONObject jsonObj = JSONObject.parseObject(result);
		return jsonObj;   
	}
	 
	
		
	
	
	
	 /**
	  * 查询-单个礼品卡订单信息接口
	 */
	 public static GiftCardOrder getOrder(String accessToken, String orderId){
		  GiftCardOrder giftCardOrder =null;
		  String url = API_GIFTCARD_ORDER_GET.replace("ACCESS_TOKEN", accessToken);  
		  Map<String,String> map  =new HashMap<String, String>();
		  map.put("order_id", orderId);
		  String json = JSONObject.toJSONString(map);
		  JSONObject jsonObject =  WeixinUtil.httpRequest(url, "POST", json);
		  logger.info("查询-单个礼品卡订单信息接口-->"+jsonObject);
		  if("0".equals(jsonObject.getString("errcode"))){
			  giftCardOrder = (GiftCardOrder)JSONObject.toJavaObject(jsonObject.getJSONObject("order"), GiftCardOrder.class);  
		  }
		  return giftCardOrder;
	 }
	 
	 


}
