package cn.hmsoft.hmplatform.wxtoken.data.dao;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.stereotype.Repository;

import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.hmplatform.wxtoken.data.model.PWxDeploy;
import cn.hmsoft.jdbc.core.PlatformDaoSupport;
import cn.hmsoft.jdbc.entity.Pager;
import cn.hmsoft.jdbc.entity.QueryOrder;

@Repository
public class PWxDeployDao extends PlatformDaoSupport<PWxDeploy> {
	private final static String LIST_INTERNET_ADDR = "select internet_addr from p_wx_deploy where token_id=? and (notice_time is null or notice_time>?) group by internet_addr";

	/****************
	 * 列出通知目标，一天以内的都认为需要通知
	 */
	public List<PWxDeploy> listInternetAddr(int token_id) {
		return this.listBySql(LIST_INTERNET_ADDR, token_id, LocalDateTime.now().minusDays(1));
	}

	private final static String FIND_DEPLOY = "select * from p_wx_deploy where token_id=? and internet_addr=? and deploy_addr=?";

	/*****************
	 * 判断是否由此部署了
	 */
	public PWxDeploy findDeploy(int token_id, String internet_addr, String deploy_addr) {
		return this.findBySql(FIND_DEPLOY, token_id, internet_addr, deploy_addr);
	}

	private final static String NOTICE_DEPLOY = "update p_wx_deploy set notice_time=? where token_id=? and internet_addr=?";

	/*****************
	 * 更新通知
	 */
	public void noticeDeploy(int token_id, String internet_addr) {
		this.updateBySql(NOTICE_DEPLOY, LocalDateTime.now(), token_id, internet_addr);
	}

	public Pager pageDeploy(Integer token_id, Integer start, Integer limit, String query, QueryOrder queryOrder) {
		StringBuilder sql = new StringBuilder();
		sql.append("select * from p_wx_deploy ");
		sql.append("where 1=1 ");
		if (token_id != null) {
			sql.append(" and token_id=").append(token_id);
		}
		if (StringHelper.isEmpty(query)) {
			return this.pageMapBySql(queryOrder, start, limit, sql.toString());
		}
		sql.append(" and (internet_addr like ?)");
		return this.pageMapBySql(queryOrder, start, limit, sql.toString(), "%" + query + "%");
	}
}
