package cn.hmsoft.weixin.control;

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.AjaxControl;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.weixin.constants.WxParamName;
import cn.hmsoft.weixin.data.dao.WxDefineDao;
import cn.hmsoft.weixin.data.model.WxDefine;
import cn.hmsoft.weixin.util.WeiXinUtil;

@RestController
public class WxTokenControl extends AjaxControl {
	@Autowired
	private WxDefineDao daoDefine;

	@RequestMapping("weixin/token/notice")
	public void notice(WxDefine w, String request_key) {
		if (StringHelper.isEmpty(w.getApp_id()) || StringHelper.isEmpty(request_key))
			return;
		WxDefine ww = this.daoDefine.find("app_id", w.getApp_id());
		if (ww == null)
			return ;
		if (!request_key.equals(SecureHelper.md5(ww.getParamValue(WxParamName.TokenCenterPass, "hm2020"))))
			return;
		ww.setApp_token_expired(w.getApp_token_expired());
		ww.setApp_accesstoken(w.getApp_accesstoken());
		ww.setApp_jsapi(w.getApp_jsapi());
		this.daoDefine.update(ww);
		WxDefine wx = WeiXinUtil.getWxDefine(w.getApp_id());
		if (wx != null){
			wx.setApp_accesstoken(w.getApp_accesstoken());
			wx.setApp_token_expired(w.getApp_token_expired());
			wx.setApp_jsapi(w.getApp_jsapi());
		}
		if (wx != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("app_id", wx.getApp_id());
			map.put("success", true);
			this.writeText(JsonHelper.fromObject(map));
		}
	}
	

}
