package cn.hmsoft.weixin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.service.FrameService;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.weixin.data.dao.WxTagDao;
import cn.hmsoft.weixin.data.model.WxTag;
import cn.hmsoft.weixin.request.TagCreateRequest;
import cn.hmsoft.weixin.request.TagDeleteRequest;
import cn.hmsoft.weixin.request.TagGetRequest;
import cn.hmsoft.weixin.request.TagUpdateRequest;
import cn.hmsoft.weixin.request.UserTagGetRequest;

@Service
public class WxTagService extends FrameService {

	@Autowired
	private WxTagDao daoTag;

	public void addTag(WxTag tag, FrameOptr optr) {
		FrameAssertUtil.checkParam(tag.getWx_id(), tag.getTag_name());
		String sql = "select * from wx_tag where tag_name=? and wx_id=?";
		FrameAssertUtil.isNull(this.daoTag.findBySql(sql, tag.getTag_name(), tag.getWx_id()),
				"用户标签[" + tag.getTag_name() + "]已经存在");
		// 去服务器请求
		TagCreateRequest tagReq = new TagCreateRequest(tag);
		tagReq.setWxDefine(tag.getWx_id());
		WxTag tg = tagReq.request();
		if (tg == null)
			throw new BusinessException("无法在微信服务器上创建标签");
		tg.setTag_desc(tag.getTag_desc());
		this.daoTag.updateTag(tg);

	}

	public void editTag(WxTag tag, FrameOptr optr) {
		FrameAssertUtil.checkParam(tag.getWx_id(), tag.getTag_id(), tag.getTag_name());
		WxTag wp = this.daoTag.findTag(tag.getWx_id(), tag.getTag_id());
		FrameAssertUtil.isNotNull(wp, "用户标签[" + wp.getTag_name() + "]不存在");
		// 去服务器请求
		TagUpdateRequest tagReq = new TagUpdateRequest(tag);
		tagReq.setWxDefine(tag.getWx_id());
		tagReq.request();
		this.daoTag.updateTag(tag);

	}

	public void delTag(int wx_id, int tag_id, FrameOptr optr) {
		WxTag wp = this.daoTag.findTag(wx_id, tag_id);
		FrameAssertUtil.isNotNull(wp, "用户标签[" + wp.getTag_name() + "]不存在");
		// 去服务器请求

		TagDeleteRequest tagReq = new TagDeleteRequest(tag_id);
		tagReq.setWxDefine(wx_id);
		tagReq.request();
		// 本地删除
		this.daoTag.delTag(wx_id, tag_id);
	}

	public void syncTag(int wx_id, FrameOptr optr) {
		// 去服务器请求
		TagGetRequest tagReq = new TagGetRequest();
		tagReq.setWxDefine(wx_id);
		tagReq.request();

	}

	public void syncTagUser(int wx_id, int tag_id, FrameOptr optr) {
		// 去服务器请求
		UserTagGetRequest tagReq = new UserTagGetRequest(tag_id, null);
		tagReq.setWxDefine(wx_id);
		tagReq.request();

	}

	public void syncTagAll(int wx_id, FrameOptr optr) {
		// 去服务器请求
		for (WxTag tag : this.daoTag.all()) {
			UserTagGetRequest tagReq = new UserTagGetRequest(tag.getTag_id(), null);
			tagReq.setWxDefine(wx_id);
			tagReq.request();
		}

	}

}
