package com.palmnest.dao.impl;

import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.UserDateActiveDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.UserDateActiveCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Slf4j
@Repository("userDateActiveDao")
public class UserDateActiveDaoImpl extends GenericDaoHibernate<UserDateActiveCount, Long> implements UserDateActiveDao {

	public UserDateActiveDaoImpl() {
		super(UserDateActiveCount.class);
	}

	@Override
	public UserDateActiveCount getUserDateActive(String date, String orgId, String userId) {
		String sql = " select * " +
				"	from tb_user_date_activecount " +
				"	where " +
				"		date='" + date + "' " +
				"		and orgId=" + orgId + " " +
				"		and userId=" + userId;

		List<UserDateActiveCount> list = getSession().createSQLQuery(sql).addEntity(UserDateActiveCount.class).list();

		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getUserDateActive(String orgId,
													   int dateType, String date, String endDate) {
		StringBuilder sql = new StringBuilder();

		sql.append("  select userDate.orgId,COUNT(userDate.count) activeCount  ");
		sql.append("  from (select orgId,userId,count  ");
		sql.append("  from tb_user_date_activecount   ");
		sql.append(" where 1=1  ");

		if (StringUtil.isNotEmpty(orgId)) {
			sql.append("  and orgId='" + orgId + "' ");
		}
		if (dateType == 1) {//年度
			sql.append("  and year(date)='" + date + "'   ");
		} else if (dateType == 2) {//季度
			sql.append("  and year(date)='" + date + "'  and QUARTER(date)='" + endDate + "'  ");
		} else if (dateType == 3) {//月
			sql.append("  and date_format(date,'%Y-%m')='" + date + "'    ");
		} else if (dateType == 4) {//周、日
			sql.append("  and date_format(date,'%Y-%m-%d')>='" + date + "'  and date_format(date,'%Y-%m-%d')<='" + endDate + "'   ");
		}
		sql.append(" group by orgId,userId) userDate  ");
		sql.append(" group by userDate.orgId  ");
		sql.append(" order by userDate.orgId  ");
		List<Map<String, Object>> list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}
}
