package cn.hmsoft.weixin.request;

import java.time.LocalDateTime;
import java.util.Date;

import org.springframework.beans.BeanUtils;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.weixin.data.model.WxUser;
import cn.hmsoft.weixin.data.model.WxUserTag;
import cn.hmsoft.weixin.entity.response.UserinfoResponseJson;

/*********************************
 * @note 获取用户基本信息
 * @author revisit@126.com
 * @Company: www.hmsoft.cn
 * @create 2017-05-09 01:13:04
 * @version 4.0.0
 */
public class UserinfoRequest extends AbstractRequest<UserinfoResponseJson, WxUser, String> {

	private String open_id;

	public UserinfoRequest(String open_id) {
		this.open_id = open_id;
	}

	private final String url = "https://api.weixin.qq.com/cgi-bin/user/info?";

	@Override
	protected String makeUrl() {
		return url + "access_token=" + this.wxDefine.getApp_accesstoken() + "&openid=" + open_id;
	}

	@Override
	public void processBusiness() {
		// 新建用户
		// wxUser = new WxUser();
		if (StringHelper.isEmpty(this.jsonEntity.getOpenid()))
			return;
		WxUser u = SpringHelper.AppGobalDao.find(WxUser.class, "open_id", this.jsonEntity.getOpenid());
		boolean newUser = false;
		if (u == null) {
			newUser = true;
			u = new WxUser();
			u.setOpen_id(this.jsonEntity.getOpenid());
			u.setWx_id(this.wxDefine.getWx_id());
		}
		WxUser wxUser = new WxUser();

		BeanUtils.copyProperties(this.jsonEntity, wxUser);

		wxUser.setWx_id(this.wxDefine.getWx_id());
		if (u != null)
			wxUser.setWuser_id(u.getWuser_id());
		if (this.jsonEntity.getSubscribe() - 1 == 0) {
			wxUser.setActive_time(LocalDateTime.now());
			wxUser.setSubscribe_time(LocalDateHelper.toLocalDateTime(new Date(jsonEntity.getSubscribe_time() * 1000L)));
			wxUser.setLast_subscribe_time(wxUser.getFirst_subscribe_time());
			wxUser.setOpen_id(jsonEntity.getOpenid());
			wxUser.setWuser_status(FrameStatus.Active.toString());
			wxUser.setSubscribe_scene(jsonEntity.getSubscribe_scene());
		} else {
			wxUser.setWuser_status(FrameStatus.InActive.toString());

		}
		if (!StringHelper.isEmpty(wxUser.getOpen_id())) {
			try {
				if (newUser)
					SpringHelper.AppGobalDao.insert(wxUser);
				else
					SpringHelper.AppGobalDao.update(wxUser);

			} catch (Exception e) {
				LogHelper.error(e);
			}
			SpringHelper.AppGobalDao.delete(WxUserTag.class, "open_id", wxUser.getOpen_id());
			if (this.jsonEntity.getTagid_list() != null) {
				for (int tag_id : this.jsonEntity.getTagid_list()) {
					WxUserTag tag = new WxUserTag();
					tag.setOpen_id(wxUser.getOpen_id());
					tag.setTag_id(tag_id);
					tag.setWx_id(this.wxDefine.getWx_id());
					SpringHelper.AppGobalDao.insert(tag);
				}
			}
		}
		this.returnEntity = wxUser;
	}
}
