package com.xxfc.platform.summit.service;



import com.xxfc.platform.summit.model.JsTicket;
import com.xxfc.platform.summit.util.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
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.RedisTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.TimeUnit;


/**
 * 
 * 生成签名之前必须先了解一下jsapi_ticket，jsapi_ticket是公众号用于调用微信JS接口的临时票据
 * https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
 * 
 * 微信卡券接口签名凭证api_ticket
 * https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
 */

@Service
@Slf4j
public class JsTicketService {


	@Autowired
	private RedisTemplate summbitRedisTemplate;

	@Autowired
	AccessTokenService tokenService;

	private static String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";

	@Value("${wx.appid}")
	private String wy_appid;
	@Value("${wx.appSercet}")
	private String  wy_secret;


	/**
	 * JSApi的类型
	 * 
	 * jsapi: 用于分享等js-api
	 * 
	 * wx_card：用于卡券接口签名凭证api_ticket
	 * 
	 */
	public enum JsApiType {
		jsapi, wx_card
	}

	/**
	 * 
	 * http GET请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）
	 * 
	 * @param jsApiType
	 * @return JsTicket
	 */
	@SuppressWarnings("null")
	public  JsTicket getTicket(JsApiType jsApiType) {
		
		String key = wy_appid + ':' + jsApiType.name();
		//从缓存中取出来

		//RedisUtil redisUtil = new RedisUtil(ConstantConfig.REDIS_IP,ConstantConfig.REDIS_PORT);
		JsTicket jsTicket = new JsTicket();
		String jsTicketRedis = summbitRedisTemplate.opsForValue().get(key) == null ? "" : summbitRedisTemplate.opsForValue().get(key).toString();
		log.info("---jsTicketRedis===="+jsTicketRedis);
		if (StringUtils.isNotBlank(jsTicketRedis))
		{
			JSONObject objTemp = new JSONObject();
			objTemp = JSONObject.parseObject(jsTicketRedis).getJSONObject(key);
			jsTicket.setExpiredTime(objTemp.getLong("expiredTime"));
			jsTicket.setTicket(objTemp.getString("ticket"));
			jsTicket.setExpires_in(objTemp.getInteger("expiresIn"));
			
		//   jsTicket = JSON.parseObject(redisUtil.get(key), JsTicket.class);
		    		  
		    		  //(JsTicket) JSON.parseObject(redisUtil.get(key)).get(key);
			  if(!jsTicket.isAvailable())
			  {
				  log.info("---jsTicket----失效");
				//  https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card 
				  String json =  HttpRequestUtil.httpGet(apiUrl+"access_token="+ tokenService.getAccessTokenStr()+"&type="+jsApiType.name());
				  log.info("---json===="+json);
				  jsTicket = new JsTicket(json);
					/*Element element = new Element(SystemConfig.WINXIN_AppID, jsTicket);
					ehcache.put(element);*/
					log.info("----jsTicket===="+jsTicket);
				  JSONObject obj = new JSONObject();
				  obj.put(key, jsTicket);
				  summbitRedisTemplate.delete(key);
				  Boolean suc=summbitRedisTemplate.opsForValue().setIfAbsent(key,  obj.toJSONString());
				  if (suc) {
					  summbitRedisTemplate.expire(wy_appid, jsTicket.getExpiresIn(), TimeUnit.MINUTES);
				  }
			  }
		}else{
			  String json =  HttpRequestUtil.httpGet(apiUrl+"access_token="+ tokenService.getAccessTokenStr()+"&type="+jsApiType.name());
			 log.info("---json===="+json);
			  jsTicket = new JsTicket(json);
				/*Element element = new Element(SystemConfig.WINXIN_AppID, jsTicket);
				ehcache.put(element);*/
			  JSONObject obj = new JSONObject();
			  obj.put(key, jsTicket);
			Boolean suc=summbitRedisTemplate.opsForValue().setIfAbsent(key,  obj.toJSONString());
			if (suc) {
				summbitRedisTemplate.expire(wy_appid, jsTicket.getExpiresIn(), TimeUnit.MINUTES);
			}
		}

		return jsTicket;
	}



}