package cn.hmsoft.hmplatform.wxtoken.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.http.HttpHelper;
import cn.hmsoft.helper.http.HttpRequestEntity;
import cn.hmsoft.hmplatform.wxtoken.data.dao.PWxDeployDao;
import cn.hmsoft.hmplatform.wxtoken.data.model.PWxDefine;
import cn.hmsoft.hmplatform.wxtoken.data.model.PWxDeploy;
import cn.hmsoft.hmplatform.wxtoken.service.PlatformWeixinTokenService;
import cn.hmsoft.weixin.util.WeiXinParamUtil;

/*************************
 * 获取线程token
 *
 */
public class WeixinTokenNoticeThread extends Thread {

	private List<PWxDeploy> targetArray = null;
	private PWxDefine wx;
	private PWxDeployDao daoDeploy;

	public WeixinTokenNoticeThread(PWxDefine wx) {
		this.wx = wx;
		this.daoDeploy = SpringHelper.getBean(PWxDeployDao.class);
		targetArray = this.daoDeploy.listInternetAddr(this.wx.getToken_id());
	}

	@Override
	public void run() {
		for (PWxDeploy r : targetArray) {
			final PWxDeploy deploy = new PWxDeploy();
			deploy.setToken_id(this.wx.getToken_id());
			deploy.setInternet_addr(r.getInternet_addr());
			new Thread(() -> {
				HttpRequestEntity entity = new HttpRequestEntity();
				entity.setHttp_url(deploy.getInternet_addr() + (deploy.getInternet_addr().endsWith("/") ? "" : "/")
						+ "weixin/token/notice.htm");
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("request_key", SecureHelper.md5(WeixinTokenModuleParamUtil.FetchWeixinTokenPass));
				map.put("app_id", wx.getApp_id());
				map.put("app_accesstoken", wx.getApp_accesstoken());
				map.put("app_jsapi", wx.getApp_jsapi());
				map.put("app_token_expired", LocalDateHelper.format(wx.getApp_token_expired()));
				entity.setRequestMap(map);
				entity.setRead_timeout(WeiXinParamUtil.HttpConnectTimeoutSeconds * 1000);
				entity.setConnect_timeout(WeiXinParamUtil.HttpConnectTimeoutSeconds * 1000);
				Ajax ajax = null;
				int total = 0;
				do {
					try {
						ajax = HttpHelper.jsonRequest(entity, Ajax.class);
					} catch (Exception e) {
						e.printStackTrace();
						try {
							Thread.sleep(3000);
						} catch (Exception ex) {
						}
					}
					total++;
				} while (total < 10 && ajax == null);
				SpringHelper.getBean(PlatformWeixinTokenService.class).logTokenNotice(this.wx, deploy, ajax);

			}).start();

		}
	}

}
