package cn.hmsoft.hmplatform.wxtoken.control;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.application.web.AjaxControl;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAgentUtil;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.hmplatform.wxtoken.data.dao.PWxDefineDao;
import cn.hmsoft.hmplatform.wxtoken.data.model.PWxDefine;
import cn.hmsoft.hmplatform.wxtoken.service.PlatformWeixinTokenService;
import cn.hmsoft.hmplatform.wxtoken.util.WeixinTokenModuleParamUtil;
import cn.hmsoft.hmplatform.wxtoken.util.WeixinTokenNoticeThread;
import cn.hmsoft.log.LogHelper;

@RestController
public class WeixinTokenControl extends AjaxControl {

	@Autowired
	private PWxDefineDao daoDefine;
	@Autowired
	private PlatformWeixinTokenService sToken;

	@RequestMapping("platform/weixin/token/fetch")
	public void fetch(PWxDefine w, String request_key, String internet_addr, String deploy_addr) {
		if (StringHelper.isEmpty(request_key) || StringHelper.isEmpty(internet_addr)
				|| StringHelper.isEmpty(deploy_addr))
			return;
		if (!request_key.equals(SecureHelper.md5(WeixinTokenModuleParamUtil.FetchWeixinTokenPass)))
			return;
		LogHelper.info("--公众号应用上线:[" + w.getWx_name() + "][" + internet_addr + "][" + deploy_addr + "]");

		String request_addr = FrameAgentUtil.getUserAddr(this.getRequest());
		this.sToken.fetchToken(w, internet_addr, deploy_addr, request_addr);
		PWxDefine wx = null;
		int tryTimes = 1;
		do {
			tryTimes++;
			wx = daoDefine.findWxDefine(w.getApp_id());
			if (wx == null || wx.getApp_token_expired() == null
					|| wx.getApp_token_expired().isBefore(LocalDateTime.now())) {
				try {
					Thread.sleep(1000);
				} catch (Exception e) {

				}
				wx = null;
			} else
				break;
		} while (wx == null && tryTimes < 10);
		Map<String, String> map = new HashMap<String, String>();
		if (wx != null) {
			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()));
		}
		this.writeText(JsonHelper.fromObject(map));
	}

	@RequestMapping("platform/weixin/token/notice")
	public Ajax notice(String app_id) {
		PWxDefine wx = daoDefine.findWxDefine(app_id);
		if (wx == null)
			throw new BusinessException("公众号未加入该平台");
		new WeixinTokenNoticeThread(wx).start();
		return new Ajax();
	}
}
