package org.cs.web.product.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.cs.core.service.impl.BaseService;
import org.cs.util.DateUtil;
import org.cs.util.Pager;
import org.cs.web.product.dao.IWxacessTokenDao;
import org.cs.web.product.model.WxaccessToken;
import org.cs.web.product.service.IWxacessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @ClassName: Pty 
 * @Description:  
 * @author: cosco gt.fan@msn.cn
 * @date: 2017-07-04 15:06:21
 */
@Service("wxacessTokenService")
public class WxacessTokenService /*extends BaseService<WxaccessToken> implements IWxacessTokenService*/{
	private Logger log = Logger.getLogger(WxacessTokenService.class);
	public static String APP_ID="wx5511007567ec7ad1";
	public static String APP_SECRET="4fbf52b7a61bfba41d806c9a655e03f9";
	
	/*@Autowired
	private IWxacessTokenDao wxtdao;*/
	
	/*@Override*/
	public String getOpenId(HttpServletRequest request,String code) {
		
		String accessToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";//获取openid的微信接口
		
        log.info("code:========"+code);
        String urlstr = accessToken.replace("APPID", APP_ID).replace("SECRET", APP_SECRET).replace("CODE", code);
        String sendGET = SendGET(urlstr);        
        org.json.JSONObject json = new org.json.JSONObject(sendGET);
        String openId = json.getString("openid");
        String state = request.getParameter("state");
        log.info("state:========"+state);
        if(state!=null){
        	String[] states = state.split("_");        	
        }
        return openId;
	}

	/*@Override
	@Transactional(readOnly=false)*/
	public WxaccessToken getTokens() {
		String token = "";
		String ticket = "";
		WxaccessToken setting = null;
		boolean flag = true;
		Date date = new Date();
		//获取数据库token
		Pager page= null;
//		List<WxaccessToken> list = wxtdao.findAll(page);
		
		/*if(list!=null&&list.size()>0){
			setting = list.get(0);
			Date wxTime = setting.getWxTime();
			if(wxTime!=null){
				long time = DateUtil.getSecondDays(wxTime, date);
				if(time>7000){
					//超时  获取
					token = getRealToken();
					ticket = getTicket(token);
				}else{
					token = setting.getAccessToken();
					ticket=setting.getJsapiTicket();
					flag = false;
				}
			}else{
				//没存时  获取
				token = getRealToken();
				ticket = getTicket(token);
			}
		}else{
			//没存时  获取
			setting = new WxaccessToken();
			token = getRealToken();
			ticket = getTicket(token);
		}*/
		setting = new WxaccessToken();
		token = getRealToken();
		ticket = getTicket(token);
		
		System.out.println("----insert-----token----------"+token);
		System.out.println("----insert-----ticket----------"+ticket);
		if(flag){
			setting.setAccessToken(token);
			setting.setJsapiTicket(ticket);
			setting.setWxTime(date);
//			setting = wxtdao.insert(setting);
		}
		
		return setting;
	}

	/*@Override*/
	public String SendGET(String url) {
		System.out.println("-----SendGET---------begin-----");
		String result="";//访问返回结果
		   BufferedReader read=null;//读取访问结果
		   try {
		    //创建url
		    URL realurl=new URL(url);
		    //打开连接
		    URLConnection connection=realurl.openConnection();
		     // 设置通用的请求属性
		             connection.setRequestProperty("accept", "*/*");
		             connection.setRequestProperty("connection", "Keep-Alive");
		             connection.setRequestProperty("user-agent",
		                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		             //建立连接
		             connection.connect();
		             read = new BufferedReader(new InputStreamReader(
		                     connection.getInputStream(),"UTF-8"));
		             String line;//循环读取
		             while ((line = read.readLine()) != null) {
		                 result += line;
		             }
		   } catch (IOException e) {
		    e.printStackTrace();
		   }finally{
		    if(read!=null){//关闭流
		     try {
		      read.close();
		     } catch (IOException e) {
		      e.printStackTrace();
		     }
		    }
		   }	
		   
		   System.out.println("-----SendGET---------end --**---");
		   System.out.println(result);
		   System.out.println("-----SendGET---------end ---***--");
		   return result; 
	}
	

	private String getRealToken(){
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appId&secret=appSecret";
		url = url.replace("appId", APP_ID).replace("appSecret", APP_SECRET);
		String tokenJsonStr = SendGET(url);
		Map tokenMap = JSON.parseObject(tokenJsonStr);
		//获取access_token
		return (String)tokenMap.get("access_token");
	}
	
	private String getTicket(String token){
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
		String ticketJsonStr = SendGET(url);
		Map ticketMap = JSON.parseObject(ticketJsonStr);
		//获取jsapi_ticket
		System.out.println(ticketMap.get("ticket")+"--------------获取ticket----------------------");
		return (String)ticketMap.get("ticket");
	}

	/*@Override*/
	public String  LoadCode(String redirectUrl) {		
		System.out.println("--------------LoadCode begin-----------------");	
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String codurl="https://open.weixin.qq.com/connect/oauth2/authorize?"
			     + "appid="+APP_ID
			     + "&redirect_uri="+redirectUrl
			     + "&response_type=code"
			     + "&scope=snsapi_userinfo"
			     + "&state=123#wechat_redirect";
        System.out.println("---------codurl----------------------"+codurl);
      	//SendGET(codurl);
      	return codurl;
        
	}
	
	
}
