package com.palmnest.dao.estateserve.impl;

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

import com.palmnest.model.estateserve.WxPublicnoOrgRelation;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.output.WxUserDto;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.estateserve.WxUser;

/**
 * 微信用户数据持久层Dao实现类
 *
 * @author yubing
 * @since 2017-1-14
 */
@Repository("scWxuserDao")
public class ScWxuserDaoImpl extends GenericDaoHibernate<WxUser, Integer> implements ScWxuserDao {

	public ScWxuserDaoImpl() {
		super(WxUser.class);
	}

	@Override
	public WxUser getScWxuserByOpenId(String openId) {
		String strHQL = "from WxUser where openId=?";
		List<WxUser> list = getSession().createQuery(strHQL).setString(0, openId).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public WxUser getScWxuserByUserId(int userId) {
		String strHQL = "from WxUser where userId=?";
		List<WxUser> list = getSession().createQuery(strHQL).setInteger(0, userId).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public WxUser getScWxuserByWxUserId(Integer WxUserId) {
		String strHQL = "from WxUser where id=?";
		List<WxUser> list = getSession().createQuery(strHQL).setInteger(0, WxUserId).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public WxUser getScWxuserByPhone(String phone) {
		String sql = "select t1.* FROM tb_wxuser t1 join tb_user t2 on t1.userId=t2.id where t2.userMobile=?";
		List<WxUser> list = getSession().createSQLQuery(sql).addEntity(WxUser.class).setString(0, phone).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<WxPublicnoOrgRelation> getWxOrgRelation(String developId, String orgName) {
		String sql = "SELECT t2.* FROM tb_wxpublicno t1 INNER JOIN tr_wxpublicno_org t2 ON t1.ID = t2.publicNoId INNER JOIN tb_organization t3 ON t2.organizationId = t3.ID" +
				" WHERE t1.developId='" + developId + "'";
		if (StringUtils.isNotBlank(orgName)) {
			sql += " AND t3.name like '%" + orgName + "%'";
		}
		return getSession().createSQLQuery(sql).addEntity(WxPublicnoOrgRelation.class).list();
	}

	@Override
	public List<WxUser> getWxUserByPermId(Integer permId, Integer virId,String ranks) {
		String sql = " SELECT DISTINCT t1.`ID`, t1.`developId`, t1.`openId`, t1.`nickName`," +
				" t1.`city`, t1.`country`, t1.`province`, t1.`language`, t1.`headimgUrl`," +
				" t1.`subscribeTime`, t1.`unSubscribeTime`, t1.`isSubscribe`, t1.`isBinding`, " +
				"t1.`accountType`, t1.`organizationId`, t2.id userId FROM tb_wxuser t1"
				+ " LEFT JOIN tb_user t2 ON (t1.openId = IFNULL(t2.bind_openid, t2.openId)) "
				+ " LEFT JOIN tb_department dp on dp.id =  t2.departmentId "
				+ " LEFT JOIN tb_vir_perm_config cf ON cf.id = t2.virPermId "
				+ " WHERE t2.virPermId =" + permId + " AND t2.virtualArchId = " + virId;
		
		if (StringUtils.isNotBlank(ranks)) {
			sql += " AND " + ranks;
			sql += " AND cf.`code` = 'BMGLY' ";
		}		
		System.out.println("[查询推送用户]getWxUserByPermId sql ===>"+ sql);
		List<WxUser> users = (ArrayList<WxUser>) getSession().createSQLQuery(sql).addEntity(WxUser.class).list();
		return users;
	}

	@Override
	public List<WxUser> getWxUserListByOrgId(int organizationId) {
		String strHQL = "";
		if (organizationId == 0) {
			strHQL = "from WxUser where isSubscribe=?";
			return getSession().createQuery(strHQL).setString(0, "subscribe").list();
		} else {
			strHQL = "from WxUser where organizationId=? and isSubscribe=?";
			return getSession().createQuery(strHQL).setInteger(0, organizationId).setString(1, "subscribe").list();
		}
	}

	@Override
	public Page getMemberPage(int pageNo, int pageSize, String strSQL) {
		return pagedQueryByJdbcTemplate(strSQL, pageNo, 10);
	}

	@Override
	public Page getUserPage(int pageNo, int pageSize, String strSQL) {
		return pagedQueryByJdbcTemplate(strSQL, pageNo, 10);
	}

	@Override
	public List<WxUser> getResisterWxUserList() {
		String strHQL = "from WxUser where userId is not null";
		return getSession().createQuery(strHQL).list();
	}

	@Override
	public Page getWxUserList(int pageNo, int pageSize, String nickName,
							  String accountType, String isBinding, String organizationId) {
		StringBuffer strSQL = new StringBuffer("SELECT t1.id,t1.openId,t1.nickName,t1.isBinding,t2.`name` as publicnoName,t3.ID as organizationId,t3.`name` as organizationName,t1.subscribeTime,t4.ID as staffId,t4.`name` as staffName");
		strSQL.append(" FROM tb_wxuser t1");
		strSQL.append(" INNER JOIN tb_wxpublicno t2 ON t1.developId = t2.developId");
		strSQL.append(" INNER JOIN tb_organization t3 ON t1.organizationId = t3.ID");
		strSQL.append(" LEFT JOIN tb_staff t4 on t1.userId=t4.ID");
		strSQL.append(" where t2.isEnabled='1' and t3.isEnabled='1'");
		if (StringUtils.isNotBlank(nickName)) {
			strSQL.append(" and t1.nickName like '%" + nickName + "%'");
		}
		if (StringUtils.isNotBlank(accountType)) {
			strSQL.append(" and t1.accountType='" + accountType + "'");
		}
		if (StringUtils.isNotBlank(isBinding)) {
			strSQL.append(" and t1.isBinding='" + isBinding + "'");
		}
		strSQL.append(" and organizationId in(" + organizationId + ")");
		return pagedQueryByJdbcTemplate(strSQL.toString(), pageNo, pageSize);
	}

	@Override
	public void updateBindWxuser(Integer... wxUserId) {
		this.getSession().createQuery("update WxUser set isBinding='" + Constants.UNBINDING + "',userId=null where id in(:ids)").setParameterList("ids", wxUserId).executeUpdate();
	}
	/**
	 * 根据项目获取公众号，然后再拿公众号下面所有的粉丝
	 * @param orgId
	 * @return
	 */
	@Override
	public List<WxUserDto> getWxUserByDevelopId(String developId) {
		StringBuilder sb=new StringBuilder("");
		sb.append(" SELECT DISTINCT developId, openId ");
		sb.append(" FROM tb_wxuser  ");
		sb.append("  WHERE developId ='"+developId+"'  ");
		List<Map<String, Object>> list=getJdbcTemplate().queryForList(sb.toString());
		List<WxUserDto> users=new ArrayList<WxUserDto>();
		if(!CollectionUtils.isEmpty(list)){
			for(Map map:list){
				if(null == map || !map.containsKey("developId") || !map.containsKey("openId") 
						|| null == map.get("developId") || null == map.get("openId") 
						|| StringUtils.isBlank(map.get("developId").toString())  || StringUtils.isBlank(map.get("openId").toString())){
					continue;
				}
				WxUserDto dto=new WxUserDto();
				dto.setDevelopId(map.get("developId").toString());
				dto.setOpenId(map.get("openId").toString());
				users.add(dto);
			}
		}
		return users;
	}
}
