package com.yingying.tourist.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

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.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yingying.tourist.common.HttpRequestSimple;
import com.yingying.tourist.domain.User;
import com.yingying.tourist.service.WechatService;

@Service
public class WechatServiceImpl implements WechatService {

	@Autowired
	private StringRedisTemplate redisTemplate;

	
	
	@Value("${weixin.appid}")
	private String appId;
	@Value("${weixin.appSecret}")
	private String appSecret;

	/**
	 * 微信测试号
	 */
//	private static String appId = "wx8a98f5f7df1e89b5";
//	private static String appSecret = "f622f3300cb3d12d01f8e82ff1cce1ee";

	/**
	 * 获取微信服务端token
	 * 
	 * @return
	 */
	@Override
	public String getToken() {

		ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

		String tokenResult = opsForValue.get("token");
		if (StringUtils.isNoneBlank(tokenResult)) {
			return tokenResult;
		}

		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret="
				+ appSecret;
		String result = HttpRequestSimple.doGet(url);

		JSONObject jsonObject = JSONObject.parseObject(result);

		String token = jsonObject.getString("access_token");
		opsForValue.set("token", token, 7200, TimeUnit.SECONDS);
		return token;
	}

	/**
	 * JS-SDK使用权限签名算法 获取ticket
	 * 
	 * @return
	 */
	@Override
	public String getTicket() {

		String token = getToken();

		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
		String result = HttpRequestSimple.doGet(url);

		JSONObject jsonObject = JSONObject.parseObject(result);

		String ticket = jsonObject.getString("ticket");
		return ticket;
	}

	/**
	 * 通过code换取网页授权access_token
	 * 
	 * @param code
	 * @return
	 */
	@Override
	public String getAuthToken(String code) {

		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret
				+ "&code=" + code + "&grant_type=authorization_code";
		String result = HttpRequestSimple.doGet(url);

		return result;
	}

	@Override
	public User getWechatUser(String token, String openId) throws UnsupportedEncodingException {
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openId
				+ "&lang=zh_CN";
		String result = HttpRequestSimple.doGet(url);

		String decodeResult = new String(result.getBytes("ISO-8859-1"), "UTF-8");

		User user = JSON.parseObject(decodeResult, User.class);

		return user;

	}

}
