package com.palmnest.service.estateserve.impl;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.EmojiFilterUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.output.WxUserDto;
import com.palmnest.dao.estateserve.PublicNoDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.estateserve.VisitorInFoDao;
import com.palmnest.model.estateserve.UserImageInfo;
import com.palmnest.model.estateserve.WxPublicnoOrgRelation;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.wechat.WeChatApiManager;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

@Service("scWxuserManager")
public class ScWxuserManagerImpl extends GenericManagerImpl<WxUser, Integer> implements ScWxuserManager {

	private Logger LOG = LoggerFactory.getLogger(ScWxuserManagerImpl.class);

	private ScWxuserDao scWxuserDao;

	public ScWxuserDao getScWxuserDao() {
		return scWxuserDao;
	}

	@Autowired
	public void setScWxuserDao(ScWxuserDao scWxuserDao) {
		this.scWxuserDao = scWxuserDao;
		this.dao = scWxuserDao;
	}

	@Autowired
	private VisitorInFoDao   visitorInFoDao;
	@Autowired
	private WeChatApiManager weChatApiManager;
	@Autowired
	private PublicNoDao      publicNoDao;


	@Override
	public WxUser getScWxuserByOpenId(String openId) {
		return scWxuserDao.getScWxuserByOpenId(openId);
	}

	@Override
	public List<WxUser> getWxUserListByOrgId(int organizationId) {
		return scWxuserDao.getWxUserListByOrgId(organizationId);
	}

	public WxUser getScWxuserByUserId(int userId) {
		return scWxuserDao.getScWxuserByUserId(userId);
	}

	public WxUser getScWxuserByWxUserId(Integer wxUserId) {
		return scWxuserDao.getScWxuserByWxUserId(wxUserId);
	}

	@Override
	public Page getMemberPage(int pageNo, String keyWord,
							  String organizationId, String virtualId, String beginTime,
							  String endTime, String organizationIdStr, String status) {

		StringBuffer strSQL = new StringBuffer("SELECT t1.ID as wxUserId,t1.headimgUrl,t1.nickName,t2.ID as userId,t2.userName,t2.userMobile,t2.`status`,t2.createTime,t3.`name` as organizationName,t4.`name` as virtualName");
		strSQL.append(" FROM tb_wxuser t1");
		strSQL.append(" LEFT JOIN tb_user t2 ON t1.userId = t2.ID");
		strSQL.append(" LEFT JOIN tb_organization t3 on t1.organizationId=t3.ID");
		strSQL.append(" LEFT JOIN tb_virtualarchitecture t4 on t2.virtualArchId=t4.id");
		strSQL.append(" where t1.organizationId in (" + organizationIdStr + ")");

		if (StringUtils.isNotBlank(keyWord)) {
			strSQL.append(" and (t2.userName LIKE '%" + keyWord + "%' or t2.userMobile like '%" + keyWord + "%')");
		}
		if (StringUtils.isNotBlank(organizationId)) {
			strSQL.append(" and t1.organizationId=" + organizationId);
		}
		if (StringUtils.isNotBlank(virtualId)) {
			strSQL.append(" and t2.virtualArchId=" + virtualId);
		}
		if (StringUtils.isNotBlank(beginTime)) {
			strSQL.append(" and t2.createTime>'" + beginTime + "'");
		}
		if (StringUtils.isNotBlank(endTime)) {
			strSQL.append(" and t2.createTime<'" + endTime + "'");
		}
		if (StringUtils.isNotBlank(status)) {
			strSQL.append(" and t2.status='" + status + "'");
		}
		strSQL.append(" order by t1.subscribeTime desc");
		return scWxuserDao.getMemberPage(pageNo, Constants.LIMIT_PAGESIZE, strSQL.toString());
	}

	@Override
	public Page getUserPage(int pageNo, String keyWord, String organizationId,
							String virtualId, String beginTime, String endTime,
							String organizationIdStr, String status) {
		StringBuffer strSQL = new StringBuffer("SELECT t2.ID AS wxUserId,t2.headimgUrl,t2.nickName,t1.ID AS userId,t1.userName,t1.userMobile,t1.`status`,date_format(t1.createTime,'%Y-%m-%d %H:%i') createTime,t3.`name` as organizationName,t4.`name` as virtualName");
		strSQL.append(" FROM tb_user t1");
		strSQL.append(" LEFT JOIN tb_wxuser t2 ON t1.ID = t2.userId");
		strSQL.append(" LEFT JOIN tb_organization t3 ON t1.organizationId = t3.ID");
		strSQL.append(" LEFT JOIN tb_virtuser t5 ON t5.userId = t1.id ");
		strSQL.append(" LEFT JOIN tb_virtualarchitecture t4 ON t5.virId = t4.id ");
		strSQL.append(" where t1.isEnabled=1 and t1.organizationId in (" + organizationIdStr + ")");
		if (StringUtils.isNotBlank(keyWord)) {
			strSQL.append(" and (t1.userName LIKE '%" + keyWord + "%' or t1.userMobile like '%" + keyWord + "%')");
		}
		if (StringUtils.isNotBlank(organizationId)) {
			strSQL.append(" and t1.organizationId=" + organizationId);
		}
		if (StringUtils.isNotBlank(virtualId)) {
			strSQL.append(" and t5.virId=" + virtualId);
		}
		if (StringUtils.isNotBlank(beginTime)) {
			strSQL.append(" and t1.createTime>'" + beginTime + "'");
		}
		if (StringUtils.isNotBlank(endTime)) {
			strSQL.append(" and t1.createTime<'" + endTime + "'");
		}
		if (StringUtils.isNotBlank(status)) {
			strSQL.append(" and t1.status='" + status + "'");
		}

		if (StringUtils.isEmpty(status) || "0".equals(status)) {
			strSQL.append("  order by t1.status, t1.createTime desc");
		} else {
			strSQL.append(" order by t1.modifyTime desc");
		}
		Page page = scWxuserDao.getMemberPage(pageNo, Constants.LIMIT_PAGESIZE, strSQL.toString());
		for (int i = 0; i < page.getItems().size(); i++) {
			Map<String, Object> map = (Map<String, Object>) page.getItems().get(i);
			String userId = map.get("userId") + "";
			List<UserImageInfo> list = visitorInFoDao.getUserImageInfo(Integer.parseInt(userId), "1");
			map.put("imageUserList", list);
			page.getItems().set(i, map);

		}
		return page;
	}

	@Override
	public Page getWxUserList(int pageNo, int pageSize, String nickName,
							  String accountType, String isBinding, String organizationId) {
		return scWxuserDao.getWxUserList(pageNo, pageSize, nickName, accountType, isBinding, organizationId);
	}

	@Override
	public void updateBindWxuser(Integer... wxUserId) {
		scWxuserDao.updateBindWxuser(wxUserId);
	}

	@Override
	public void saveWxUser(String openId, String developId) {
		try {
			WxUser wxUser = getScWxuserByOpenId(openId);
			if (wxUser == null) {
				wxUser = new WxUser();
				wxUser.setDevelopId(developId);
				wxUser.setOpenId(openId);
				wxUser.setSubscribeTime(new Date());

				/*// 新增微信用户时 查询该公众号绑定的项目列表,默认给用户绑定第一个项目
				List<Map<String, Object>> relations = publicNoDao.getWxPublicnoOrgRelations(developId);
				if (relations != null && relations.size()>0){
					wxUser.setOrganizationId((Integer) relations.get(0).get("id"));
				}else {
					log.error("公众号未关联项目");
				}*/


				UserInfo userinfo = weChatApiManager.getUserInfo(developId, openId);
				if (userinfo != null) {
					if (userinfo.getSubscribe() == 1) {
						wxUser.setIsSubscribe("subscribe");
					}
					if (StringUtils.isNotEmpty(userinfo.getNickname())) {
						String nickName = StringUtil.StringFilter(EmojiFilterUtils
								.filterEmoji(userinfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
						wxUser.setNickName(nickName);
					} else {
						wxUser.setNickName("微信用户");
					}
					wxUser.setCity(userinfo.getCity());
					wxUser.setCountry(userinfo.getCountry());
					wxUser.setProvince(userinfo.getProvince());
					wxUser.setLanguage(userinfo.getLanguage());
					wxUser.setHeadimgUrl(userinfo.getHeadimgurl());
					wxUser.setIsBinding(Constants.UNBINDING);
					scWxuserDao.saveObj(wxUser);
				} else {
					scWxuserDao.saveObj(wxUser);
				}
			}
		} catch (Exception e) {
			LOG.error("saveWxUser occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	@Override
	public void updateAllWxUserInfo() {
		List<WxUser> wxUsers = getAll();
		if (!CollectionUtils.isEmpty(wxUsers)) {
			LOG.info("update WxUserInfo size:" + wxUsers.size());
			for (WxUser wxuser : wxUsers) {
				UserInfo userinfo = weChatApiManager.getUserInfo(wxuser.getDevelopId(), wxuser.getOpenId());
				if (userinfo != null) {
					if (StringUtils.isNotEmpty(userinfo.getNickname())) {
						String nickName = StringUtil.StringFilter(EmojiFilterUtils
								.filterEmoji(userinfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
						wxuser.setNickName(nickName);
					} else {
						wxuser.setNickName("微信用户");
					}
					wxuser.setCity(userinfo.getCity());
					wxuser.setCountry(userinfo.getCountry());
					wxuser.setProvince(userinfo.getProvince());
					wxuser.setLanguage(userinfo.getLanguage());
					wxuser.setHeadimgUrl(userinfo.getHeadimgurl());
					scWxuserDao.updateObj(wxuser);
				}
			}
		}
	}

	@Override
	public Page getUnselectdUserPage(int pageNo, String keyWord,
									 String beginTime, String endTime, String status) {
		StringBuffer strSQL = new StringBuffer("SELECT t2.ID AS wxUserId,t2.headimgUrl,t2.nickName,t1.ID AS userId,t1.userName,t1.userMobile,t1.`status`,date_format(t1.createTime,'%Y-%m-%d %H:%i') createTime,t3.`name` as organizationName,t4.`name` as virtualName");
		strSQL.append(" FROM tb_user t1");
		strSQL.append(" LEFT JOIN tb_wxuser t2 ON t1.ID = t2.userId");
		strSQL.append(" LEFT JOIN tb_organization t3 ON t1.organizationId = t3.ID");
		strSQL.append(" LEFT JOIN tb_virtualarchitecture t4 ON t1.virtualArchId = t4.id");
		strSQL.append(" where t1.isEnabled=1 and t1.organizationId is NULL");
		if (StringUtils.isNotBlank(keyWord)) {
			strSQL.append(" and (t1.userName LIKE '%" + keyWord + "%' or t1.userMobile like '%" + keyWord + "%')");
		}
		if (StringUtils.isNotBlank(beginTime)) {
			strSQL.append(" and t1.createTime>'" + beginTime + "'");
		}
		if (StringUtils.isNotBlank(endTime)) {
			strSQL.append(" and t1.createTime<'" + endTime + "'");
		}
		if (StringUtils.isNotBlank(status)) {
			strSQL.append(" and t1.status='" + status + "'");
		}
		strSQL.append(" order by t1.createTime desc");
		Page page = scWxuserDao.getMemberPage(pageNo, Constants.LIMIT_PAGESIZE, strSQL.toString());
		for (int i = 0; i < page.getItems().size(); i++) {
			Map<String, Object> map = (Map<String, Object>) page.getItems().get(i);
			String userId = map.get("userId") + "";
			List<UserImageInfo> list = visitorInFoDao.getUserImageInfo(Integer.parseInt(userId), "1");
			map.put("imageUserList", list);
			page.getItems().set(i, map);

		}
		return page;
	}

	@Override
	public WxUser getScWxuserByPhone(String phone) {
		return scWxuserDao.getScWxuserByPhone(phone);
	}

	@Override
	public List<WxPublicnoOrgRelation> getWxOrgRelation(String developId, String orgName) {
		return scWxuserDao.getWxOrgRelation(developId, orgName);
	}

	@Override
	public List<WxUser> getWxUserByPermId(Integer permId, Integer virId,String rank) {
		return scWxuserDao.getWxUserByPermId(permId, virId,rank);
	}
//	@Override
//	public String getOrgByOpenId(String openId) {
//		String orgId="";
//		WxUser wxUser=scWxuserDao.getScWxuserByOpenId(openId);
//		if(wxUser!=null){
//			List<WxPublicnoOrgRelation> orgList=scWxuserDao.getWxOrgRelation(wxUser.getDevelopId());
//			if(orgList!=null&&orgList.size()>0){
//				WxPublicnoOrgRelation orgPub=orgList.get(0);
//				orgId=orgPub.getOrganizationId().toString();
//			}
//		}
//		return orgId;
//	}
	/**
	 * 根据项目获取公众号，然后再拿公众号下面所有的粉丝
	 * @param orgId
	 * @return
	 */
	@Override
	public List<WxUserDto> getWxUserByDevelopId(String developId) {
		return scWxuserDao.getWxUserByDevelopId(developId);
	}
}
