package com.palmnest.dao.dinner.impl;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import cn.jiguang.common.utils.StringUtils;

import com.palmnest.application.bean.Page;
import com.palmnest.dao.dinner.ConsumerDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.dinner.Consumer;

/**
 * 订餐用户DAO实现类
 *
 * @author longmeizhen
 */
@Repository("consumerDao")
public class ConsumerDaoImpl extends GenericDaoHibernate<Consumer, Long> implements ConsumerDao {
	private static Logger LOG = LoggerFactory.getLogger(ConsumerDaoImpl.class);

	public ConsumerDaoImpl() {
		super(Consumer.class);
	}

	/**
	 * 根据openId获取用户
	 *
	 * @param orgId
	 * @param openId
	 * @return
	 */
	@Override
	public Consumer getConsumerByOpenId(String orgId, String openId) {
		String sql = "from Consumer where openId=? and orgId=? and isEnabled='1' ";
		List<Consumer> list = getSession().createQuery(sql).setString(0, openId).setString(1, orgId).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	/**
	 * 根据用户名密码查找相应的用户
	 * @param orgId
	 * @param loginName
	 * @param password
	 * @return
	 */
//	@Override
//	public Consumer getConsumerByLoginName(String orgId, String loginName,
//			String password) {
//		String sql="from Consumer where orgId=? and loginName=? and password=? ";
//		List<Consumer> list=getSession().createQuery(sql).setString(0, orgId).setString(1, loginName).setString(2, password).list();
//		if(list!=null&&list.size()>0){
//			return list.get(0);
//		}
//		return null;
//	}
	/**
	 * 根据登录名获取用户信息
	 * @param orgId
	 * @param loginName
	 * @return
	 */
//	@Override
//	public List<Consumer> getUserByLoginName(String orgId, String loginName) {
//		String sql="from Consumer where orgId=? and loginName=? ";
//		List<Consumer> list=getSession().createQuery(sql).setString(0, orgId).setString(1, loginName).list();
//		return list;
//	}

	/**
	 * 查询企业人员列表
	 *
	 * @return
	 */
	@Override
	public Page findList(Map<String, Object> paramets, int pageSize, int pageNo) {
		
		StringBuilder sql = getFindListSql(paramets);
		LOG.info("findList-sql:{}",sql.toString());
		
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}
	
	
	/**
	 * 查询企业人员列表
	 *
	 * @return
	 */
	@Override
	public List<Map<String, Object>> findListForReport(Map<String, Object> paramets) {
		
		StringBuilder sql = getFindListSql(paramets);
		LOG.info("findListForReport-sql:{}",sql.toString());
		
		return getJdbcTemplate().queryForList(sql.toString());
	}

	private StringBuilder getFindListSql(Map<String, Object> paramets) {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select tmp.* from (");
		sql.append(" select u.virPermId,tg.`name` as orgName,tv.`name` as virName,u.id,u.userName ");
		sql.append(" ,u.userNumber,(case when u.userSex='1' then '男'  when u.userSex='2' then '女' else '' end ) userSex ");
		sql.append(" ,u.email,dl.name deptStr,dl.name dept,u.userMobile mobile,u.address addressId ");
		sql.append(" ,ifnull(doi.itemname,di.itemname) address,u.roleType,u.integral,u.organizationId  ");
		sql.append(" ,date_format(u.createTime,'%Y-%m-%d %T') createTime,u.isEnabled,tg.passType,ifnull(tvpc.name,'暂未设置') permName ");
		sql.append(" ,ifnull(u.isPushState,1) pushState ");
		sql.append(" from tb_user u ");
		sql.append(" left join tb_department dl on dl.id=u.departmentId ");
		sql.append(" left join tb_dictionary_item di on di.id=u.address ");
		sql.append(" left join tb_dictionary_org_item doi on doi.id=u.address ");
		sql.append(" left join tb_organization tg on tg.id=u.organizationId ");
		sql.append(" left join tb_virtualarchitecture tv on tv.id=u.virtualArchId ");
		sql.append(" left join tb_vir_perm_config tvpc on tvpc.id=u.virPermId ");
		sql.append(" where 1=1 and (userType <> '-1' OR userType IS NULL) and (u.`STATUS` IS NULL OR u.`STATUS` <> '5') and u.userMobile is not null ");
		if (StringUtils.isNotEmpty(paramets.get("orgId") == null ? "" : paramets.get("orgId").toString())) {
			sql.append(" and u.organizationId in (" + paramets.get("orgId") + ")  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("userName") == null ? "" : paramets.get("userName").toString())) {
			sql.append(" and u.userName like '%" + paramets.get("userName") + "%'  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("roleType") == null ? "" : paramets.get("roleType").toString()) && !"0".equals(paramets.get("roleType"))) {
			sql.append(" and u.roleType='" + paramets.get("roleType") + "'  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("dept") == null ? "" : paramets.get("dept").toString()) && !"0".equals(paramets.get("dept"))) {
			sql.append(" and u.departmentId=" + paramets.get("dept") + "  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("mobile") == null ? "" : paramets.get("mobile").toString())) {
			sql.append(" and u.userMobile like '%" + paramets.get("mobile") + "%' ");
		}
		if (StringUtils.isNotEmpty(paramets.get("virtualArchId") == null ? "" : paramets.get("virtualArchId").toString())) {
			sql.append(" and u.virtualArchId='" + paramets.get("virtualArchId").toString() + "'  ");
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(paramets.get("isEnabled") == null ? "" : paramets.get("isEnabled").toString())) {
			sql.append(" and u.isEnabled='" + paramets.get("isEnabled").toString() + "'  ");
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(paramets.get("status") == null ? "" : paramets.get("status").toString())) {
			sql.append(" and (u.status='" + paramets.get("status").toString() + "' or u.status is null ) ");
		}
		sql.append(" ) tmp where 1=1 ");

		if (StringUtils.isNotEmpty(paramets.get("pushState") == null ? "" : paramets.get("pushState").toString())) {
			sql.append(" and tmp.pushState=" + paramets.get("pushState").toString() + "  ");
		}
		sql.append(" order by tmp.createTime desc ");
		return sql;
	}


	/**
	 * 查询员工通行列表
	 *
	 * @param paramets
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	@Override
	public Page findEmployeeList(Map<String, Object> paramets, int pageSize, int pageNo) {

		StringBuilder sql = new StringBuilder("");
		sql.append(" SELECT DISTINCT temp.* FROM (  ");
		sql.append("select DISTINCT tg.`name` as orgName,tv.`name` as virName,u.id,u.userName,dl.itemname deptStr,dl.itemname dept,u.userMobile mobile,u.address addressId,di.itemname address,u.roleType,u.integral,u.organizationId,date_format(u.createTime,'%Y-%m-%d %T') createTime,u.isEnabled,tg.passType");
		sql.append("  ,	c.id cardId,c.card_code cardCode,date_format(c.create_time,'%Y-%m-%d %T') cardCreateTime,g.group_name groupName  ");
		sql.append("  from tb_user u  ");
		sql.append(" left join tb_dictionary_item dl on dl.id=u.departmentId ");
		sql.append(" left join tb_dictionary_item di on di.id=u.address ");
		sql.append(" left join tb_organization tg on tg.id=u.organizationId ");
		sql.append(" left join tb_virtualarchitecture tv on tv.id=u.virtualArchId ");
		
		
		sql.append(" LEFT JOIN tr_user_lingling_card l ON l.user_id = u.ID  ");
		sql.append(" LEFT JOIN tb_lingling_card c ON c.id = l.card_id  ");
		sql.append(" LEFT JOIN tr_perm_group_user gu ON gu.user_id = u.ID  ");
		sql.append(" LEFT JOIN tb_device_perm_group g ON g.id = gu.device_perm_group_id ");
		
		sql.append(" where 1=1 and (userType <> '-1' OR userType IS NULL) and u.userMobile is not null and u.isEnabled='1' ");
		if (StringUtils.isNotEmpty(paramets.get("orgId") == null ? "" : paramets.get("orgId").toString())) {
			sql.append(" and u.organizationId in (" + paramets.get("orgId") + ")  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("userName") == null ? "" : paramets.get("userName").toString())) {
			sql.append(" and u.userName like '%" + paramets.get("userName") + "%'  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("roleType") == null ? "" : paramets.get("roleType").toString()) && !"0".equals(paramets.get("roleType"))) {
			sql.append(" and u.roleType='" + paramets.get("roleType") + "'  ");
		}

		if (StringUtils.isNotEmpty(paramets.get("mobile") == null ? "" : paramets.get("mobile").toString())) {
			sql.append(" and u.userMobile like '%" + paramets.get("mobile") + "%' ");
		}
		if (StringUtils.isNotEmpty(paramets.get("virtualArchId") == null ? "" : paramets.get("virtualArchId").toString())) {
			sql.append(" and u.virtualArchId='" + paramets.get("virtualArchId").toString() + "'  ");
		}
		if (StringUtils.isNotEmpty(paramets.get("hasPermGroup") == null ? "" : paramets.get("hasPermGroup").toString())) {
			String hasPermGroup = paramets.get("hasPermGroup").toString();
			if ("0".equals(hasPermGroup)) {
				sql.append(" AND NOT EXISTS (SELECT gu.user_id FROM tr_perm_group_user gu WHERE gu.user_id = u.ID)");
			} else if ("1".equals(hasPermGroup)) {
				sql.append(" AND EXISTS (SELECT gu.user_id FROM tr_perm_group_user gu WHERE gu.user_id = u.ID)");
			}
		}

		sql.append(" order by u.createTime desc ");
		sql.append(" 	) temp ");
		return pagedQueryByJdbcTemplate(sql.toString(), pageNo, pageSize);
	}


	/**
	 * 根据项目获取所有用户
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Consumer> getConsumerListByOrgId(String orgId) {
		String sql = "from Consumer where orgId=? and isEnabled='1' ";
		List<Consumer> list = getSession().createQuery(sql).setString(0, orgId).list();
		return list;
	}

	@Override
	public Consumer getConsumerByMobile(String orgId, String mobile) {
		String sql = "from Consumer where orgId=? and mobile=? and isEnabled='1' ";
		List<Consumer> list = getSession().createQuery(sql).setString(0, orgId).setString(1, mobile).list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 获取所有有效的代订类型的账号以及管理员账号
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Consumer> getConsByOrgId(String orgId) {
		String sql = "from Consumer where orgId=?  and isEnabled='1'  and (roleType='1' or roleType='3') ";
		List<Consumer> list = getSession().createQuery(sql).setString(0, orgId).list();
		return list;
	}

}
