package com.dgtis.dorm.manager.db.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.dgtis.dorm.manager.db.dao.AlumniFriUserMapper;
import com.dgtis.dorm.manager.db.dao.AlumniUserMapper;
import com.dgtis.dorm.manager.db.dao.AlumniUserMessageMapper;
import com.dgtis.dorm.manager.db.domain.AlumniFriUser;
import com.dgtis.dorm.manager.db.domain.AlumniUser;
import com.dgtis.dorm.manager.db.domain.AlumniUserMessage;
import com.dgtis.dorm.manager.db.util.PYIndexStrUtil;
import com.dgtis.dorm.manager.db.util.wx.WeixinUtil;
import com.dgtis.dorm.manager.db.util.wx.entity.AccessToken;
import com.dgtis.dorm.manager.db.util.wx.entity.MessageData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
	@Resource
	private AlumniUserMapper alumniUserMapper;

	@Resource
	private AlumniFriUserMapper alumniFriUserMapper;

	@Resource
	private AlumniUserMessageMapper alumniUserMessageMapper;
	
	/**
	 * 查询校友录列表,待审核中的用户除外
	 * @param alumniUser
	 * @param page
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> queryAlumniUser(AlumniUser alumniUser, Integer page, Integer limit,
                                                String sort, String order) {
		PageHelper.startPage(page, limit);
		List<AlumniUser> list = alumniUserMapper.selectAlumniUser(alumniUser);
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/**
	 * 查询游客数量，待审核中的用户除外
	 * @param page
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> queryAlumniUserNotYK(Integer page, Integer limit,
													 String sort, String order){
		PageHelper.startPage(page, limit);
		List<AlumniUser> list = alumniUserMapper.selectAlumniUserNotYK();
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}


	
	/**
	 * 查询待审核用户列表
	 * @param page
	 * @param size
	 * @param sort
	 * @param order
	 * @return
	 */
	public PageInfo<AlumniUser> querySelective(AlumniUser example, 
			Integer page, Integer size, String sort, String order) {

		PageHelper.startPage(page, size);
		List<AlumniUser> list = alumniUserMapper.selectByExample(example);
		PageInfo<AlumniUser> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/**
	 * 批量审核成员
	 * @param ids
	 * @return
	 */
	public Map<String, Object> passAudit(Integer auditStatus, 
			String reason, String[] ids) {
		Map<String,Object> map = new HashMap<String,Object>();
		for (String id : ids) {
			AlumniUser user = alumniUserMapper.selectByPrimaryKey(Integer.valueOf(id));
			if(user != null && user.getAuditStatus() == 1) {
				user.setAuditStatus(auditStatus);
				user.setAuditDataTime(new Date());
				user.setLastLoginTime(null);
				if(auditStatus == 2) {
					user.setReason(reason);

				} else {

					user.setReason("");
				}
				alumniUserMapper.updateByPrimaryKeySelective(user);
				//发送系统消息通知用户
				String content = "";
				String result = "";
				if(auditStatus == 3) {
					result = "通过";
					content = "恭喜你通过审核认证";
				} else {
					result = "驳回";
					String re = "";
					if(!StringUtils.isEmpty(reason))
						re="驳回原因："+reason;
					content = "sorry,您的资料审核未通过。"+re;
				}
				sendMessage(user.getId()+"", "system", content, null);
				
				//发送微信通知
				MessageData msgData = new MessageData();
				msgData.setKeyword1(user.getUserName());
				msgData.setKeyword2("审核认证");
				msgData.setKeyword3(result);
				msgData.setKeyword4(content);
				sendWXMSG(user.getId(), msgData);
			}
		}
		map.put("state", "success");
		map.put("massege", "审核成功 ");
		return map;
	}

	/**
	 * 审核
	 * @param alumniUser
	 * @return
	 */
	public Map<String, Object> auditUser(AlumniUser alumniUser) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(alumniUser.getId());
		if(user != null && user.getAuditStatus() == 1) {
			Integer auditStatus = alumniUser.getAuditStatus();
			String reason = alumniUser.getReason();
			user.setAuditStatus(auditStatus);
			user.setAuditDataTime(new Date());
			user.setLastLoginTime(null);
			if(auditStatus == 2) {
				user.setReason(reason);

			} else {

				user.setReason("");
			}
			alumniUserMapper.updateByPrimaryKeySelective(user);

			//发送系统消息通知用户
			String content = "";
			String result = "";
			if(auditStatus == 3) {
				result = "通过";
				content = "恭喜你通过审核认证";
			} else {
				result = "驳回";
				String re = "";
				if(!StringUtils.isEmpty(reason))
					re="驳回原因："+reason;
				content = "sorry,您的资料审核未通过。"+re;
			}
			sendMessage(user.getId()+"", "system", content, null);

			//发送微信通知
			MessageData msgData = new MessageData();
			msgData.setKeyword1(user.getUserName());
			msgData.setKeyword2("审核认证");
			msgData.setKeyword3(result);
			msgData.setKeyword4(content);
			sendWXMSG(user.getId(), msgData);

			resultMap.put("state", "success");
			resultMap.put("massege", "审核成功");
		} else {
			resultMap.put("state", "failuren");
			resultMap.put("massege", "用户不存在");
		}
		return resultMap;

	}
	
	/**
	 * 根据主键id查询用户
	 * @param userId
	 * @return
	 */
	public AlumniUser findById(Integer userId) {
		return alumniUserMapper.selectByPrimaryKey(userId);
	}

	public Map findAlumniUserByUserId(Integer userId) {
		return alumniUserMapper.selectById(userId);
	}
	/**
	 * 查询用户数量
	 * @return
	 */
	public int count(AlumniUser user) {
		return (int)alumniUserMapper.countByUser(user);
	}
	/**
	 * 根据openId查询用户
	 * @param openId
	 * @return
	 */
	public AlumniUser queryByOid(String openId) {

		return alumniUserMapper.selectOneByOpenId(openId);
	}
	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(AlumniUser user) {
		AlumniUser alumniUser = alumniUserMapper.selectOneByOpenId(user.getOpenId());
		if(alumniUser == null)
			alumniUserMapper.insertSelective(user);
	}
	/**
	 * 修改用户
	 * @param user
	 */
	public void updateUser(AlumniUser user) {
		alumniUserMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 查询我关注的用户
	 * @param userId
	 * @return
	 */
	public Map<String, Object> findUserConcernedByUserId(Integer userId, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniFriUserMapper.selectUserByFKUserId(userId);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("pageNum",pageinfo.getPageNum());
		resMap.put("pageSize", pageinfo.getPageSize());
		resMap.put("startRow", pageinfo.getStartRow());
		resMap.put("endRow", pageinfo.getEndRow());
		resMap.put("total", pageinfo.getTotal());
		resMap.put("pages", pageinfo.getPages());

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}
	/**
	 * 搜索我关注的用户
	 * @param userId
	 * @param valString
	 * @return
	 */
	public Map<String, Object> findUserConcerned(Integer userId, String valString) {
		List<Map> list = alumniFriUserMapper.selectUserConcerned(userId, valString);
		Map<String,Object> resMap = new HashMap<String,Object>();

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 查询校友录列表
	 * @param page
	 * @param size
	 * @return
	 */
	public Map<String, Object> findAlumniRecordById(Integer userId, Integer page, Integer size) {
		List<Map> list = alumniUserMapper.findAlumniRecordById(userId, (page - 1) * size, size);
		int total = alumniUserMapper.selectTotalCount(userId);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("page",page);
		resMap.put("pageSize", size);
		resMap.put("total", total);

		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 添加关注用户记录
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> alreadyFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null && user.getAuditStatus() == 3) {
			AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
			if(afriUser == null) {
				afriUser = new AlumniFriUser();
				afriUser.setFkUserId(userId);
				afriUser.setFriUserId(friUserId);
				afriUser.setCreateDate(new Date());
				alumniFriUserMapper.insertSelective(afriUser);
				result.put("state", "success");
				result.put("massege", "关注成功");
			} else {
				result.put("state", "failuren");
				result.put("massege", "已关注");
			}
		} else {
			result.put("state", "failuren");
			result.put("massege", "您的身份目前待验证");
		}
		return result;
	}
	
	/**
	 * 查询是否关注
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> checkFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
		if(afriUser == null) {
			result.put("isFollowed", false);
		} else {
			result.put("isFollowed", true);
		}
		return result;
	}

	/**
	 * 按条件查询校友录
	 * @param userId
	 * @param valString
	 * @return
	 */
	public Map<String, Object> findAlumniRecord(Integer userId, String valString, Integer valInt) {
		List<Map> list = alumniUserMapper.findAlumniRecord(userId, valString, valInt);
		Map<String,Object> resMap = new HashMap<String,Object>();
		Map<String, List<Object>> mapZm = new LinkedHashMap<String, List<Object>>();
		String[] zm = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
				"L", "M", "N", "O", "P", "Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "#" };
		for (int i = 0; i < zm.length; i++) {
			mapZm.put(zm[i], new ArrayList<Object>());
		}
		//将对应的list放入相应的字母
		for (Map<String, String> map : list) {
			String enUserName = map.get("en_user_name");
			String pinyin = "";
			if(StringUtils.isNoneBlank(enUserName)) {
				if(enUserName.matches("[a-zA-Z]+")) {
					pinyin = enUserName.toUpperCase();
				} else {
					pinyin = enUserName;
				}
			} else {
				String userName = map.get("user_name");
				if(userName != null && userName != "") {
					String strFirst = userName.substring(0, 1).toUpperCase();
					
					if(PYIndexStrUtil.isChinese(strFirst)) {
						pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
					} else if(strFirst.matches("[a-zA-Z]+")) {
						pinyin = strFirst.toUpperCase();
					} else {
						pinyin = strFirst;
					}
				}
			}
			//如果mapZm的key 包含pinyin  
			if (mapZm.containsKey(pinyin)) {
				mapZm.get(pinyin).add(map);
			} else {
				mapZm.get("#").add(map);
			}
		}
		for (String str : zm) {
			List<Object> key = mapZm.get(str);
			if(key.size() == 0) 
				mapZm.remove(str);
		}
		resMap.put("items", mapZm);
		return resMap;
	}

	/**
	 * 提交待审核认证
	 * @param userId
	 * @return
	 */
	public Map<String, Object> submitAudit(Integer userId, String formId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String temRoleType = user.getRoleType();
			if(StringUtils.isNotBlank(temRoleType)){
				if("非清华公管人".equals(temRoleType)) {
					user.setAuditStatus(3);
					user.setRoleType(temRoleType);
					alumniUserMapper.updateByPrimaryKeySelective(user);
					result.put("state", "success");
					result.put("massege", "提交成功");
				} else if("游客".equals(temRoleType)){
					user.setAuditStatus(0);
					user.setRoleType("游客");
					alumniUserMapper.updateByPrimaryKeySelective(user);
					result.put("state", "success");
					result.put("massege", "提交成功");
				} else {
					user.setAuditStatus(1);
					alumniUserMapper.updateByPrimaryKeySelective(user);
					updateUserFormId(user.getId(), formId);
					result.put("state", "success");
					result.put("massege", "提交成功");
				}
			} else {
				result.put("state", "failuren");
				result.put("massege", "角色不存在");
			}

		} else {
			result.put("state", "failuren");
			result.put("massege", "用户不存在");
		}
		return result;
	}

	/**
	 * 取消关注
	 * @param userId
	 * @param friUserId
	 * @return
	 */
	public Map<String, Object> cancelAlreadyFollowed(Integer userId, Integer friUserId) {
		Map<String, Object> result = new HashMap<String, Object>();
		AlumniFriUser afriUser = alumniFriUserMapper.selectFriUser(userId, friUserId);
		if(afriUser != null) {
			alumniFriUserMapper.deleteByPrimaryKey(afriUser.getId());
			result.put("state", "success");
			result.put("massege", "取消成功");
		} else {
			result.put("state", "failuren");
			result.put("massege", "取消失败");
		}
		return result;
	}

	public Map<String, Object> selectUserConcernedByUserId(Integer id, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniFriUserMapper.selectUserByFKUserId(id);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("total", pageinfo.getTotal());
		resMap.put("items", list);
		return resMap;
	}

	public Map<String, Object> findMyOrganize(Integer id, Integer page, Integer size) {
		PageHelper.startPage(page, size);
		List<Map> list = alumniUserMapper.selectMyOrganizeByUserId(id);
		PageInfo pageinfo = new PageInfo(list);
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("total", pageinfo.getTotal());
		resMap.put("items", list);
		return resMap;
	}

	public List<AlumniUser> selectUserByUserName(String userName){
		return alumniUserMapper.selectUserByUserName(userName);
	}
	

	/**
	 * 更新用户的formId
	 * @param userId
	 * @param formId
	 */
	public void updateUserFormId(Integer userId, String formId) {
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String form_Id = user.getFormId();
			if(StringUtils.isNotBlank(form_Id)) {
				String[] formIds = form_Id.split(",");
				List<String>list = Arrays.asList(formIds);
				StringBuilder sb = new StringBuilder();
				for(int i = 0; i < list.size(); i++) {
					sb.append(list.get(i));
					if (sb.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
						sb.append(",");
					}
				}
				sb.append(formId);
				
				user.setFormId(sb.toString());
				alumniUserMapper.updateByPrimaryKeySelective(user);
			} else {
				StringBuilder sb = new StringBuilder();
				sb.append(formId);
				user.setFormId(sb.toString());
				alumniUserMapper.updateByPrimaryKeySelective(user);
			}
		}
	}

	/**
	 * 发送微信通知
	 * @param userId
	 * @param msgData
	 */
	public void sendWXMSG(Integer userId, MessageData msgData) {
		AlumniUser user = alumniUserMapper.selectByPrimaryKey(userId);
		if(user != null) {
			String form_Id = user.getFormId();
			if(StringUtils.isNotBlank(form_Id)) {
				String[] formIds = form_Id.split(",");
				List<String> listformId = new ArrayList<String>();
				for (String string : formIds) {
					listformId.add(string);
				}
				if(listformId.size() > 0) {
					String fromId = listformId.get(0);
					listformId.remove(0);
					if(listformId.size() > 0)
						user.setFormId(StringUtils.join(listformId, ","));
					else 
						user.setFormId("");
					
					alumniUserMapper.updateByPrimaryKeySelective(user);
					
					AccessToken accessToken = WeixinUtil.getAccessToken();
					if(accessToken != null) {
						String errmsg = WeixinUtil.sendWXMessage(accessToken.getToken(),user.getOpenId(), fromId, msgData);
						if(errmsg != null && !"ok".equals(errmsg)) {
							System.out.println(errmsg);
							sendWXMSG(userId, msgData);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 发送消息通知
	 * @param fkUserId 接收人id
	 * @param type 消息类型
	 * @param content 消息内容
	 * @param fromUserId 发送人id
	 */
	public void sendMessage(String fkUserId, String type, String content, String fromUserId) {
		AlumniUserMessage message = new AlumniUserMessage();
		message.setFkUserId(fkUserId);
		message.setMessageType(type);
		message.setContent(content);
		if(StringUtils.isNotBlank(fromUserId)) {
			message.setFromUserId(fromUserId);
		}
		message.setCreateTime(new Date());
		message.setIsRead(false);
		message.setIsDelete(false);
		alumniUserMessageMapper.insertSelective(message);
	}

    /**
     * 查询校友录数量（非游客）
     * @return
     */
    public int selectCountNotYK() {
        return (int)alumniUserMapper.selectCountNotYK();
    }

    public List<AlumniUser> allAlumniUser(AlumniUser alumniUser) {
    	return alumniUserMapper.selectAlumniUser(alumniUser);
    }
}
