package cn.hmsoft.weixin.data.dao;

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

import org.springframework.stereotype.Component;

import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.jdbc.core.PlatformDaoSupport;
import cn.hmsoft.weixin.constants.WxSeqName;
import cn.hmsoft.weixin.data.model.WxDefine;
import cn.hmsoft.weixin.data.model.WxUserLog;
import cn.hmsoft.weixin.entity.message.BasicMessage;
import cn.hmsoft.weixin.entity.request.custom.CustomRequestJson;

@Component
public class WxUserLogDao extends PlatformDaoSupport<WxUserLog> {

	private final static String UPDATE_SQL = "update wx_user set active_time=? where open_id=? and wx_id=?";

	private final static String INSERT_LOG_SQL = "insert into wx_user_log(log_id,msg_time,msg_type,xml_value,open_id,send_flag,wx_id) values ("
			+ WxSeqName.WxUserLogId + ".nextval,?,?,?,?,?,?)";

	public Date logMessage(WxDefine wx, BasicMessage msg, String xml) {
		Date log_time = new Date(msg.getCreateTime() * 1000);

		try {
			// 判断是否记录日志
			if (FrameStatus.Active.toString().equals(wx.getRecord_user_log())) {
				this.updateBySql(INSERT_LOG_SQL, log_time, msg.getMsgType(), xml, FrameStatus.InActive,
						msg.getFromUserName(), wx.getWx_id());

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			this.updateBySql(UPDATE_SQL, log_time, msg.getFromUserName(), wx.getWx_id());
		} catch (Exception e) {
			e.printStackTrace();

		}
		return log_time;
	}

	public WxUserLog logMessage(int wx_id,CustomRequestJson msg) {
		WxUserLog log = new WxUserLog();
		log.setMsg_time(LocalDateTime.now());
		log.setMsg_type(msg.getMsgtype());
		log.setXml_value(JsonHelper.fromObject(msg));
		log.setSend_flag(FrameStatus.Active.toString());
		log.setOpen_id(msg.getTouser());
		log.setWx_id(wx_id);
		try {
			this.insert(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return log;
	}

}