package cn.hmsoft.weixin.request;

import java.time.LocalDateTime;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.weixin.data.model.WxTag;
import cn.hmsoft.weixin.entity.response.TagGetResponseJson;

/*****************************
 * @note 获取服务器标签信息
 * @author revisit@126.com
 * @Company: www.hmsoft.cn
 * @create 2017-05-09 00:51:28
 * @version 4.0.0
 */
public class TagGetRequest extends AbstractRequest<TagGetResponseJson, String, String> {

	private final static String url = "https://api.weixin.qq.com/cgi-bin/tags/get?";
	private final static String FIND_TAG_SQL = "select * from wx_tag where tag_id=?";
	private final static String UPDATE_TAG_SQL = "update  wx_tag  set tag_name =? ,tag_status=? where tag_id=?";

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

	@Override
	public void processBusiness() {
		// 更新
		SpringHelper.AppGobalDao.updateBySql("update wx_tag set tag_status=null");
		for (TagGetResponseJson.Tag tag : this.jsonEntity.getTags()) {
			WxTag tg = SpringHelper.AppGobalDao.findBySql(WxTag.class, FIND_TAG_SQL, tag.getId());
			if (tg == null) {
				// 没有，需要创建
				tg = new WxTag();
				tg.setCreate_time(LocalDateTime.now());
				tg.setTag_desc("from wx_server");
				tg.setTag_id(tag.getId());
				tg.setTag_name(tag.getName());
				tg.setWx_id(this.wxDefine.getWx_id());
				tg.setTag_status(FrameStatus.Active.toString());
				SpringHelper.AppGobalDao.insert(tg);
			} else {
				SpringHelper.AppGobalDao.updateBySql(UPDATE_TAG_SQL, tag.getName(), FrameStatus.Active.toString(), tag.getId());
				// 更新
			}
		}
		// 删除不存在于服务器上标签
		SpringHelper.AppGobalDao.updateBySql("delete from wx_tag where tag_status is null");
		SpringHelper.AppGobalDao.updateBySql("delete from wx_user_tag where tag_id not in (select tag_id from wx_tag)");

	}
}
