package com.iamberry.wechat.service.wechat;

import java.sql.SQLException;
import java.util.Date;

import com.iamberry.wechat.tools.WeixinUtil;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.wechat.core.entity.wx.Config;
import com.iamberry.wechat.core.entity.wx.ConfigJSSDK;
import com.iamberry.wechat.core.entity.wx.WechatShare;
import com.iamberry.wechat.face.wechat.ConfigService;
import com.iamberry.wechat.service.wechat.dao.ConfigDAO;
import com.iamberry.wechat.tools.SignUtil;

@Service
public class ConfigServiceImpl implements ConfigService {
	@Autowired
	private ConfigDAO configDAO;
	public void setConfigDAO(ConfigDAO configDAO) {
		this.configDAO = configDAO;
	}
	

	private WeixinUtil weixinUtil;

	public Config getConfig(String appId) {
		return configDAO.getConfig(appId);
	}

	public void updateConfig(Config config) {
		configDAO.updateConfig(config);
	}

	/**
	 * jsapi_ticket使用权限签名算法
	 * @param appid
	 * @param url
	 * @return
	 * @throws SQLException
	 */
	public JSONObject selectConfig(String appid,String url){
		try {
			// 数据库获取微信配置，并获取ticket
			Config cfg = configDAO.getConfig(appid);
			if(cfg == null) {
				return null;
			}
			
			// 准备数据
			String nonceStr = SignUtil.getNonceStr(),
				  timestamp = SignUtil.getTimeStamp(),
					 ticket = cfg.getTicket(), 
				  appsecret = cfg.getAppsecret();
			
			// 判断ticket是否失效，如果失效自动获取 ；如果 (当前时间 - config的创建时间) / 1000 = 剩余超时的秒
			if(ticket == null || (new Date().getTime() - cfg.getCreateTime()) / 1000 >= 7000){
				//获取access_token, 已经兼容缓存
				String token = weixinUtil.getAccessToken(appid, appsecret).getToken();
				
				//access_token换取jsapi_ticket
				if(token == null) {
					return null;
				}
				
				// 获取ticket
				ticket = weixinUtil.getTicket(token).getTicket();
				if(ticket == null) {
					return null;
				}
				//更新ticket
				cfg.setTicket(ticket);
				cfg.setCreateTime(new Date().getTime());
				configDAO.updateConfig(cfg);
			}
			
			//字典排序的签名参数
			String string1 = "jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s";
			string1 = String.format(string1, ticket, nonceStr, timestamp, url);
			//对string1进行sha1签名，得到signature
			String signature = SignUtil.md5(string1).toLowerCase();
			
			//最后组装json数据
			ConfigJSSDK config = new ConfigJSSDK();
			config.setAppId(appid);
			config.setTicket(ticket);
			config.setNonceStr(nonceStr);
			config.setSignature(signature);
			config.setTimestamp(timestamp);
			
			// 获取分享的数据
			WechatShare share = configDAO.selectWechatShareByHash(url.hashCode());
			if(share != null){
				config.setShare(share);
				share.setShareUrlHash(url.hashCode());
				share.setShareDataNum(1);
				share.setShareNum(0);
				configDAO.updateWechatShareByHash(share);		// 更新一次数据
			}
			
			return JSONObject.fromObject(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
