package com.palmnest.service.dorm.service.impl;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.input.DormCheckOutDto;
import com.palmnest.application.dto.input.DormRoomerListDto;
import com.palmnest.application.dto.output.DormReleaseDto;
import com.palmnest.application.dto.output.DormRoomerDto;
import com.palmnest.application.dto.output.WxDormCheckOutDto;
import com.palmnest.application.dto.output.WxDormRoomerDto;
import com.palmnest.model.User;
import com.palmnest.model.dorm.DormCheckOut;
import com.palmnest.model.dorm.DormReleaseInfo;
import com.palmnest.model.dorm.DormRoomerInfo;
import com.palmnest.model.emig.BillOperationRecodes;
import com.palmnest.model.estateserve.SmsAuthCode;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.service.UserManager;
import com.palmnest.service.dorm.manager.DormCheckOutManager;
import com.palmnest.service.dorm.manager.DormReleaseInfoManager;
import com.palmnest.service.dorm.manager.DormRoomerManager;
import com.palmnest.service.dorm.service.DormCheckOutService;
import com.palmnest.service.estateserve.BillOperationRecodesManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 退宿申请单service实现类
 *
 * @author longmeizhen
 */
@Slf4j
@Service("dormCheckOutService")
public class DormCheckOutServiceImpl implements DormCheckOutService {


	@Autowired
	private DormCheckOutManager         dormCheckOutManager;
	@Autowired
	private DormRoomerManager           dormRoomerManager;
	@Autowired
	private BillOperationRecodesManager billOperationRecodesManager;
	@Autowired
	private SmsAuthCodeManager          smsAuthCodeManager;
	@Autowired
	private ScWxuserManager             scWxuserManager;
	@Autowired
	private DormReleaseInfoManager      dormReleaseInfoManager;
	@Autowired
	private WeChatApiManager            weChatApiManager;

	@Autowired
	private UserManager userManager;

	private static final String TSSQ        = "tssq";
	//base64加密宿管放行
	public static        String AUTHENTCODE = "5a6/566h5pS+6KGM";

	public static String host            = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wxCheckInOutUrl = PropertiesKit.readPropertiesValue("wxCheckInOutUrl", "wechat.properties");

	/**
	 * 获取退宿申请列表
	 *
	 * @param dto      查询条件
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@Override
	public Page getDormCheckOutList(DormRoomerListDto dto, int pageNo,
									int pageSize) {
		return dormCheckOutManager.getDormCheckOutList(dto, pageNo, pageSize);
	}

	@Override
	public Map<String, Object> getDormCheckById(Long id) {
		if (dormCheckOutManager.exists(id)) {
			Map<String, Object> map           = new HashMap<String, Object>();
			DormCheckOut        dormCheckInfo = dormCheckOutManager.get(id);
			if (dormCheckInfo != null) {
				DormRoomerDto dto = new DormRoomerDto();
				if (dormRoomerManager.exists(dormCheckInfo.getDormId())) {
					DormRoomerInfo dormInfo = dormRoomerManager.get(dormCheckInfo.getDormId());
					dto.setApartment(dormInfo.getApartment());
					dto.setBuild(dormInfo.getBuild());
					dto.setFloor(dormInfo.getFloor());
					dto.setRoom(dormInfo.getRoom());
					dto.setBedNo(dormInfo.getBedNo());
					dto.setUserName(dormInfo.getUserName());
					dto.setIDcard(dormInfo.getIDcard());
					dto.setSex(dormInfo.getSex());
					dto.setMobile(dormInfo.getMobile());
					dto.setWorkNo(dormInfo.getWorkNo());
					dto.setId(id);
					dto.setNumber(dormCheckInfo.getNumber());
					if (dormCheckInfo.getCreateTime() != null) {
						dto.setCreateTime(DateHelper.formatDate(dormCheckInfo.getCreateTime(), DateHelper.DATE_TIME_STRING));
					}
					dto.setBedEmptyImage(dormCheckInfo.getBedEmptyImage());
					dto.setBedLabelImage(dormCheckInfo.getBedLabelImage());
					dto.setGoodsInfo(dormCheckInfo.getGoodsInfo());
					if (StringUtils.isNotEmpty(dormCheckInfo.getOtherImage())) {
						String[] otherImage = dormCheckInfo.getOtherImage().split(";");
						dto.setOtherImage(otherImage);
					} else {
						String[] otherImage = new String[0];
						dto.setOtherImage(otherImage);
					}
					dto.setStatus(dormCheckInfo.getStatus());
					//舍友信息
					dto.setRoomerId(dormCheckInfo.getRoomerId());
					dto.setRoomerImage(dormCheckInfo.getRoomieImage());
					dto.setRoomerWorkNo(dormCheckInfo.getRoomieNo());
					//根据id查名字
					String roomerName = "";
					if (StringUtils.isNotEmpty(dormCheckInfo.getRoomerId())) {
						if (dormRoomerManager.exists(Long.parseLong(dormCheckInfo.getRoomerId()))) {
							DormRoomerInfo dormRoomer = dormRoomerManager.get(Long.parseLong(dormCheckInfo.getRoomerId()));
							if (dormRoomer != null) {
								roomerName = dormRoomer.getUserName();
							}
						}
					}
					dto.setRoomerName(roomerName);
					map.put("dormRoomInfo", dto);
					//获取操作记录
					BillOperationRecodes recode = billOperationRecodesManager.getRecodeBySourId(dormCheckInfo.getId(), 4, "20,21");//查询退宿的审核记录
					if (recode != null) {
						Map<String, Object> recodeMap = new HashMap<String, Object>();
						User                user      = userManager.get(recode.getCreator());
						recodeMap.put("result", recode.getOperation());
						recodeMap.put("reason", recode.getRepresent());
						if (user != null) {
							recodeMap.put("auditor", user.getFullName());
						}
						recodeMap.put("auditTime", DateHelper.formatDate(recode.getCreateTime(), DateHelper.DATE_TIME_STRING));
						map.put("recodeInfo", recodeMap);
					} else {
						map.put("recodeInfo", null);
					}

					//获取放行记录
					DormReleaseInfo releaseInfo = dormReleaseInfoManager.getReleaseInfoByCheckId(id);
					if (releaseInfo != null) {
						DormReleaseDto releaseDto = new DormReleaseDto();
						releaseDto.setReleaseGoods(releaseInfo.getReleaseGoods());
						if (StringUtils.isNotEmpty(releaseInfo.getReleaseImages())) {
							String[] releaseImages = releaseInfo.getReleaseImages().split(";");
							releaseDto.setReleaseImages(releaseImages);
						} else {
							String[] releaseImages = new String[0];
							releaseDto.setReleaseImages(releaseImages);
						}

						if (StringUtils.isNotEmpty(releaseInfo.getReleaseMan())) {
							User user = userManager.get(Long.parseLong(releaseInfo.getReleaseMan()));
							releaseDto.setReleaseMan(user.getFullName());
						}

						releaseDto.setReleaseReason(releaseInfo.getReleaseReason());
						if ("1".equals(releaseInfo.getReleaseResult())) {
							releaseDto.setReleaseResult("通过");
						} else if ("2".equals(releaseInfo.getReleaseResult())) {
							releaseDto.setReleaseResult("拒绝");
						}

						releaseDto.setReleaseTime(DateHelper.formatDate(releaseInfo.getReleaseTime(), DateHelper.DATE_TIME_STRING));
						map.put("releaseInfo", releaseDto);
					} else {
						map.put("releaseInfo", null);
					}
					return map;
				} else {
					return null;
				}
			}
		}
		return null;
	}

	/**
	 * 审批退宿
	 */
	@Transactional
	public AppResultDto auditDormCheckOut(Map<String, Object> map, MultipartHttpServletRequest request) {
		AppResultDto dto = new AppResultDto("100", "数据异常");
		try {
			if (map != null) {
				String id     = map.get("id").toString();
				String status = map.get("status").toString();
				String userId = map.get("userId").toString();
				String reason = map.get("reason").toString();
				if (StringUtils.isNotEmpty(id)) {
					if (dormCheckOutManager.exists(Long.parseLong(id))) {
						DormCheckOut dormCheck = dormCheckOutManager.get(Long.parseLong(id));
						if (dormCheck != null) {//申请退宿单不为空
							//首先增加操作记录
							Map<String, Object> resMap = saveBillRecodes(id, userId, status, reason);
							String              res    = resMap.get("res").toString();
							String              code   = resMap.get("code").toString();
							if (StringUtils.isNotEmpty(res)) {
								return AppResultUtil.createErrorDto(code, res);
							}
							//修改单据状态
							String rest = upDormCheckOut(map, dormCheck, request);
							if (StringUtils.isNotEmpty(rest)) {
								if (StringUtils.isEmpty(res)) {
									res = "操作异常";
								}
								return AppResultUtil.createErrorDto("100", res);
							}
							//推送消息给微信用户
							sendWechatMessage(id, dormCheck.getNumber(), status, dormCheck.getCreator(), DateHelper.formatDate(dormCheck.getCreateTime(), DateHelper.CURRENT_DATE));
							return AppResultUtil.createSuccesDto();
						}
					}
				}
			}
			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败：" + e.getMessage());
		}

	}

	@Async
	public void sendWechatMessage(String id, String number, String status, String openId, String createTime) {
		WxUser wxUser  = scWxuserManager.getScWxuserByOpenId(openId);
		String content = "";
		String url     = host + wxCheckInOutUrl.replaceAll("@id", id);
		if (wxUser != null) {
			if ("1".equals(status)) {//审核通过
				content = "您好，您" + createTime + "日提交的退宿申请已经审核通过了！";
			} else if ("2".equals(status)) {//审核不通过
				content = "您好，您" + createTime + "日提交的退宿申请审核未通过！" + "<a href='" + url + "'>查看详情</a>";
			} else if ("3".equals(status)) {//放行通过
				content = "您好，您" + createTime + "日提交的退宿申请已放行成功！";
			} else if ("4".equals(status)) {//放行不通过
				content = "您好，您" + createTime + "日提交的退宿申请放行失败！" + "<a href='" + url + "'>查看详情</a>";
			}
			weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
		}

	}

	public String getPicture(MultipartHttpServletRequest request) throws Exception {
		String           picUrl    = "";
		Iterator<String> fileNames = request.getFileNames();
		while (fileNames.hasNext()) {
			MultipartFile multipartFile = request.getFile(fileNames.next());

			//获得文件原始名称
			InputStream stream   = null;
			String      fileExt  = null;
			String      fileName = "";
			if (multipartFile != null) {
				stream = multipartFile.getInputStream();
				fileName = multipartFile.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;
			}

			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String url = fileUploadUtils.uploadFile(stream, fileExt);
			picUrl += ";" + fileUploadUtils.fullVisitPath(url);
		}
		if (picUrl.length() > 0) {
			picUrl = picUrl.substring(1);
		}
		return picUrl;
	}

	/**
	 * 修改退宿申请单
	 *
	 * @param userId    操作用户
	 * @param status    操作状态(1审核通过2审核不通过)
	 * @param dormCheck 退宿申请单
	 * @return
	 */
	@Transactional
	public String upDormCheckOut(Map<String, Object> map, DormCheckOut dormCheck, MultipartHttpServletRequest request) {
		String res    = "";
		String userId = map.get("userId").toString();
		String status = map.get("status").toString();
		try {
			if ("1".equals(status)) {//审核通过
				dormCheck.setStatus("2");
				//放行通过后生成一张放行单
			} else if ("2".equals(status)) {//审核不通过
				dormCheck.setStatus("4");
			} else if ("3".equals(status)) {//已放行
				dormCheck.setStatus("3");
			} else if ("4".equals(status)) {//放行不通过
				dormCheck.setStatus("5");
			}
			dormCheck.setModifier(userId);
			dormCheck.setModifyTime(new Date());
			dormCheckOutManager.updateModel(dormCheck);
			if ("3".equals(status) || "4".equals(status)) {//放行时修改放行单的状态
				String          pic          = getPicture(request);
				String          releaseGoods = map.get("recycledGoods").toString();
				String          reason       = map.get("reason").toString();
				DormReleaseInfo dormRelease  = new DormReleaseInfo();
				if ("3".equals(status)) {//已放行
					dormRelease.setStatus("2");
					dormRelease.setReleaseResult("1");//通过
				} else if ("4".equals(status)) {//放行不通过
					dormRelease.setStatus("3");
					dormRelease.setReleaseResult("2");//拒绝
				}
				dormRelease.setCreateTime(new Date());
				dormRelease.setCreator(userId);
				dormRelease.setSourId(dormCheck.getId());
				dormRelease.setReleaseImages(pic);
				dormRelease.setReleaseMan(userId);
				dormRelease.setReleaseGoods(releaseGoods);
				dormRelease.setReleaseReason(reason);
				dormRelease.setReleaseTime(new Date());
				dormRelease.setModifier(userId);
				dormRelease.setModifyTime(new Date());
				dormReleaseInfoManager.save(dormRelease);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			res = "修改退宿申请单失败：" + e.getMessage();
		}
		return res;
	}

	/**
	 * 保存操作记录
	 *
	 * @param id     来源单据id
	 * @param userId 操作用户
	 * @param status 操作状态(1审核通过2审核不通过)
	 * @param reason 审核意见
	 * @return
	 */
	public Map<String, Object> saveBillRecodes(String id, String userId, String status, String reason) {
		String              res       = "";
		String              code      = "";
		String              operation = "";
		String              opType    = "";
		Map<String, Object> map       = new HashMap<String, Object>();
		try {
			if ("1".equals(status)) {
				operation = "审核通过";
				opType = "20";
			} else if ("2".equals(status)) {
				operation = "审核不通过";
				opType = "21";
			} else if ("3".equals(status)) {
				operation = "放行通过";
				opType = "22";
			} else if ("4".equals(status)) {
				operation = "放行不通过";
				opType = "23";
			}
			BillOperationRecodes billRecodes = billOperationRecodesManager.getRecodeBySourId(Long.parseLong(id), 4, Integer.parseInt(opType));

			if (billRecodes != null) {
				res = "该单据已有用户操作";
				code = CodeConstants.USEED_CODE;
			} else {
				billOperationRecodesManager.saveRecode(Long.parseLong(id), 4, Integer.parseInt(opType), Long.parseLong(userId), operation, reason);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			res = "保存操作记录失败：" + e.getMessage();
			code = "100";
		}
		map.put("code", code);
		map.put("res", res);
		return map;
	}

	/**
	 * 获取验证码并且校验用户输入的身份信息是否存在
	 *
	 * @param userMobile
	 * @param idCard
	 * @return
	 */
	@Override
	public AppResultDto getDormAuthCode(String type, String userMobile, String idCard, String orgId, String openId) {
		String result = "Error";
		//首先校验身份信息是否存在
		DormRoomerInfo dormInfo = dormRoomerManager.getDormRoomerByMobileAndIdcard(userMobile, idCard, orgId);
		if (dormInfo == null) {
			return AppResultUtil.createErrorDto("100", "找不到该员工信息");
		}
		if (StringUtils.isNotEmpty(dormInfo.getMobile())) {//如果该用户的电话号码不为空的时候，登录时就需要手机号验证了
			if (!dormInfo.getMobile().equals(userMobile)) {
				return AppResultUtil.createErrorDto("300", "您现在输入的手机号与系统中手机号不符，请联系管理员.");
			}
		}
		if ("2".equals(type)) {//为退宿时登录
			int hasCheck = dormCheckOutManager.hasCheckOutByStatus(orgId, idCard, userMobile);
			if (hasCheck == 1) {//存在未处理完的单据
				return AppResultUtil.createErrorDto("300", "您还存在未处理的退宿单据，请到[申请信息]中查看进度。");
			}
		}
		//然后再进行传输验证码
		String code    = NumberUtils.getValidateCode();
		String content = "您的验证码为" + code + "，15分钟内有效，如非本人操作，请忽略。";
		//发送短信
//		result=smsAuthCodeManager.sendSms(userMobile, content);
		result = smsAuthCodeManager.smsSendByOrgId(orgId, content, userMobile, code, CodeConstants.SMS_CODE_TYPE);
		if ("Success".equals(result.trim())) {
			return AppResultUtil.createSuccesDto(result);
		} else if ("3".equalsIgnoreCase(result)) {
			return AppResultUtil.createErrorDto("100", "该项目下未配置短信账号");
		} else {
			return AppResultUtil.createErrorDto("100", "验证码发送失败");
		}

	}

	/**
	 * 根据电话号码和身份证
	 *
	 * @param mobile电话
	 * @param idCard身份证
	 * @param orgId项目
	 * @return
	 */
	@Override
	public DormRoomerInfo getDormRoomerByMobileAndIdcard(String mobile,
														 String idCard, String orgId) {
		return dormRoomerManager.getDormRoomerByMobileAndIdcard(mobile, idCard, orgId);
	}

	/**
	 * 判断所填写的code和该号码获取到的是否同一个
	 *
	 * @param mobile
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@Override
	public int isExistence(String mobile, String code) throws Exception {
		SmsAuthCode smsCode = smsAuthCodeManager.getSmsAuthCode(mobile, code, "1", 30);
		if (smsCode == null) {
			return 1;
		}
		return 2;
	}

	/**
	 * 登录员工信息获取员工入宿信息
	 *
	 * @param userMobile 电话号码
	 * @param idCard身份证
	 * @param code验证码
	 * @param orgId项目
	 * @param openId
	 * @return
	 */
	@Override
	public AppResultDto login(String type, String userMobile, String idCard, String code,
							  String orgId, String openId) {
		String res = "";
		try {
			DormRoomerInfo dormInfo = dormRoomerManager.getDormRoomerByMobileAndIdcard(userMobile, idCard, orgId);
			if (dormInfo == null) {
				return AppResultUtil.createErrorDto("100", "找不到该员工信息");
			} else {
				if (StringUtils.isNotEmpty(dormInfo.getMobile())) {//如果该用户的电话号码不为空的时候，登录时就需要手机号验证了
					if (!dormInfo.getMobile().equals(userMobile)) {
						return AppResultUtil.createErrorDto("300", "您现在输入的手机号与系统中手机号不符，请联系管理员.");
					}
				}
				if ("2".equals(type)) {//为退宿时登录
					int hasCheck = dormCheckOutManager.hasCheckOutByStatus(orgId, idCard, userMobile);
					if (hasCheck == 1) {//存在未处理完的单据
						return AppResultUtil.createErrorDto("300", "您还存在未处理的退宿单据，请到[申请信息]中查看进度。");
					}
				}
				//如果用户存在了，就对比code,然后返回成功
				int isExist = isExistence(userMobile, code);
				if (isExist == 1) {//没找到对应的数据
					return AppResultUtil.createErrorDto("100", "验证码无效");
				} else {
					//身份信息存在了之后需要查找对应的入宿信息，并且将该入宿信息设置成空的openId
					DormRoomerInfo dormRoomerInfo = dormRoomerManager.getDormInfoByOpenId(openId, orgId);
					if (dormRoomerInfo != null) {
						dormRoomerInfo.setOpenId("");
						dormRoomerInfo.setModifier(openId);
						dormRoomerInfo.setModifyTime(new Date());
						dormRoomerManager.updateModel(dormRoomerInfo);
					}
					//登录成功后需要将用户和微信用户绑定
					dormInfo.setOpenId(openId);
					dormInfo.setMobile(userMobile);
					dormInfo.setModifyTime(new Date());
					dormRoomerManager.updateModel(dormInfo);
					res = dormInfo.getApartment() + dormInfo.getBuild() + dormInfo.getFloor() + dormInfo.getRoom() + dormInfo.getBedNo();
					return AppResultUtil.createSuccesDto(res);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("提交失败：" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "提交失败：" + e.getMessage());
		}
	}

	/**
	 * 提交退宿信息
	 *
	 * @param checkDto
	 * @return
	 */
	@Override
	public AppResultDto applyCheckOut(DormCheckOutDto checkDto, MultipartHttpServletRequest request) {

		long startTime = System.currentTimeMillis();
		log.info("进入 DormCheckOutServiceImpl applyCheckOut 方法===================>时间为" + startTime);
		String openId = checkDto.getOpenId();
		String orgId  = checkDto.getOrgId();
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}

		DormRoomerInfo dormInfo = dormRoomerManager.getDormInfoByOpenId(openId, orgId);
		if (dormInfo != null) {
			int hasCheck = dormCheckOutManager.hasCheckOutByStatus(orgId, dormInfo.getIDcard(), dormInfo.getMobile());
			if (hasCheck == 1) {//存在未处理完的单据
				return AppResultUtil.createErrorDto("300", "您还存在未处理的退宿单据，请到[申请信息]中查看进度。");
			}

			DormCheckOut checkInfo = new DormCheckOut();
			checkInfo.setCreateTime(new Date());
			checkInfo.setCreator(openId);
			checkInfo.setDormId(dormInfo.getId());
			checkInfo.setGoodsInfo(checkDto.getGoodsInfo());
			checkInfo.setOrgId(orgId);
			checkInfo.setIsEnabled("1");
			checkInfo.setNumber(CodeGenerateUtils.generate(TSSQ));
			checkInfo.setRoomerId(checkDto.getRoomerId());
			checkInfo.setRoomieNo(checkDto.getRoomieNo());
			try {
				long startUploadTime = System.currentTimeMillis();
				checkInfo.setBedEmptyImage(uploadImage("bedEmptyImage", request));
				checkInfo.setBedLabelImage(uploadImage("bedLabelImage", request));
				checkInfo.setRoomieImage(uploadImage("roomieImage", request));
				checkInfo.setOtherImage(uploadImages(request));
				log.info("退宿图片上传消耗时间为:============>" + (System.currentTimeMillis() - startUploadTime));
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", "退宿上传图片失败：" + e.getMessage());
			}
			checkInfo.setStatus("1");
			checkInfo = dormCheckOutManager.save(checkInfo);
			//申请成功后需要推送消息给有审核权限的宿管员
			pushMessage(orgId, checkInfo.getId().toString(), "有新退宿申请.", "你有新的退宿申请待审核，请及时处理");

			log.info("退宿方法消耗时间为:============>" + (System.currentTimeMillis() - startTime));
			return AppResultUtil.createSuccesDto();//申请成功
		} else {
			return AppResultUtil.createErrorDto("100", "该用户找不到入宿信息");
		}

	}

	/**
	 *
	 */
	@Async
	public void pushMessage(String orgId, String id, String title, String content) {
		List<User> userList = new ArrayList<User>();
		try {
			List<Map<String, Object>> mapList = userManager.getPower(orgId, Integer.parseInt(CodeConstants.DORM_MANAGER));
			if (mapList != null && mapList.size() > 0) {
				for (int i = 0; i < mapList.size(); i++) {
					Map<String, Object> map = mapList.get(i);
					if (map.get("usId") != null && StringUtils.isNotEmpty(map.get("usId").toString())) {
						String userId = map.get("usId").toString();
						if (userManager.exists(Long.parseLong(userId))) {
							User user = userManager.get(Long.parseLong(userId));
							if (user != null) {
								userList.add(user);
							}
						}
					}
				}
			}
			PushMessageHelper helper=new PushMessageHelper();
			helper.pushMessage(Long.parseLong(id), CodeConstants.DORM_MANAGER, userList, title, content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 退宿上传图片
	 *
	 * @param checkInfo
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@Async
	public String uploadImage(String fileNames, MultipartHttpServletRequest request) throws IOException {
		String returnPath = "";
//		MultipartFile multipartFile = request.getFile(fileNames);
//		//获得文件原始名称
//        InputStream stream = null;
//        String fileExt = null;
//        String fileName = "";
//        if (multipartFile != null) {
//			stream = multipartFile.getInputStream();
//            fileName = multipartFile.getOriginalFilename();
//				fileName = new String(fileName.getBytes(), "utf-8");
//            fileExt = StringUtils.isNotEmpty(fileName) ? fileName
//                    .substring(fileName.lastIndexOf("."))
//                    : StringUtils.EMPTY;
//        }
//
//        FileUploadUtils fileUploadUtils = new FileUploadUtils();
//        fileUploadUtils.init();
//        String url = fileUploadUtils.uploadFile(stream, fileExt);
//        if(StringUtils.isNotEmpty(url)){
//        	path=fileUploadUtils.fullVisitPath(url);
//        }

		FileUploadUtils fileUploadUtils = new FileUploadUtils();
		fileUploadUtils.init();

		String base64ImgUrl = request.getParameter(fileNames);
		if (StringUtils.isNotBlank(base64ImgUrl)) {
			String path = FileUploadUtils.getBase64ImageUrl(base64ImgUrl);

			if (StringUtils.isNotEmpty(path)) {//外部访问的全路径
				returnPath = fileUploadUtils.fullVisitPath(path);
			}

			File file = new File(FileUploadUtils.getATTACHMENT_ROOT() + path);
			if (file != null && file.length() > (500 * 1024)) {
				log.info("图片大小为 =========>:" + file.length());
				FileUploadUtils.compressPic(file);
			}
		}

		return returnPath;
	}

	/**
	 * 上传其他图片
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@Async
	public String uploadImages(MultipartHttpServletRequest request) throws IOException {

		FileUploadUtils fileUploadUtils = new FileUploadUtils();
		fileUploadUtils.init();

		String picUrl = "";
//        Iterator<String> fileNames = request.getFileNames();
		String[] otherImages = request.getParameterValues("otherImage");

		if (otherImages == null || otherImages.length < 1) {
			return "";
		}
//		while(fileNames.hasNext()) {
//			String name=fileNames.next();
//			if(name.indexOf("otherImage")!=-1){
//				MultipartFile multipartFile = request.getFile(name);
//	        	//获得文件原始名称
//	            InputStream stream = null;
//	            String fileExt = null;
//	            String fileName = "";
//	            if (multipartFile != null) {
//					stream = multipartFile.getInputStream();
//	                fileName = multipartFile.getOriginalFilename();
//						fileName = new String(fileName.getBytes(), "utf-8");
//	                fileExt = StringUtils.isNotEmpty(fileName) ? fileName
//	                        .substring(fileName.lastIndexOf("."))
//	                        : StringUtils.EMPTY;
//	            }
//	            FileUploadUtils fileUploadUtils = new FileUploadUtils();
//	            fileUploadUtils.init();
//	            String url = fileUploadUtils.uploadFile(stream, fileExt);

		for (String base64ImgUrl : otherImages) {
			if (StringUtils.isNotBlank(base64ImgUrl)) {
				String url = FileUploadUtils.getBase64ImageUrl(base64ImgUrl);

				File file = new File(FileUploadUtils.getATTACHMENT_ROOT() + url);
				if (file != null && file.length() > (500 * 1024)) {
					log.info("图片大小为 =========>:" + file.length());
					FileUploadUtils.compressPic(file);
				}

				if (StringUtils.isNotEmpty(url)) {
					picUrl += ";" + fileUploadUtils.fullVisitPath(url);
				}
			}
		}

		if (picUrl.length() > 1) {
			picUrl = picUrl.substring(1);
		}
		return picUrl;
	}

	/**
	 * 获取登录微信用户的申请列表信息
	 *
	 * @param openId
	 * @return
	 */
	@Override
	public AppResultDto getCheckOutList(String openId, String orgId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "获取不到项目");
		}
		DormRoomerInfo  dormInfo = dormRoomerManager.getDormInfoByOpenId(openId, orgId);
		WxDormRoomerDto dto      = getRoomerInfo(dormInfo);
		if (dto == null) {
			return AppResultUtil.createErrorDto("100", "没有入宿信息");
		}
		//获取当前登录微信用户所申请的退宿信息列表
		List<WxDormCheckOutDto> dtoList = dormCheckOutManager.getCheckOutList(orgId, dormInfo.getIDcard(), dormInfo.getMobile());
		map.put("roomerInfo", dto);
		map.put("checkList", dtoList);
		return AppResultUtil.createSuccesDto(map);
	}

	/**
	 * 获取入宿信息
	 *
	 * @param dormInfo
	 * @return
	 */
	public WxDormRoomerDto getRoomerInfo(DormRoomerInfo dormInfo) {
		if (dormInfo != null) {
			WxDormRoomerDto dto = new WxDormRoomerDto();
			dto.setApartment(dormInfo.getApartment());
			dto.setBedNo(dormInfo.getBedNo());
			dto.setBuild(dormInfo.getBuild());
			dto.setFloor(dormInfo.getFloor());
			dto.setId(dormInfo.getId());
			dto.setIDcard(dormInfo.getIDcard());
			dto.setMobile(dormInfo.getMobile());
			dto.setRoom(dormInfo.getRoom());
			dto.setUserName(dormInfo.getUserName());
			dto.setSex(dormInfo.getSex());
			dto.setWorkNo(dormInfo.getWorkNo());
			return dto;
		}
		return null;
	}

	/**
	 * 退出登录
	 */
	@Override
	public String exitLogin(String openId, String orgId) {
		String         res      = "FAIL";
		DormRoomerInfo dormInfo = dormRoomerManager.getDormInfoByOpenId(openId, orgId);
		if (dormInfo != null) {
			dormInfo.setOpenId("");
			dormInfo.setModifier(openId);
			dormInfo.setModifyTime(new Date());
			dormRoomerManager.updateModel(dormInfo);
			res = "SUCCESS";
		} else {
			res = "抱歉！没有您的入住信息，如果您已更换手机号码请联系宿舍管理员修改入住信息。";
		}
		return res;
	}

	@Override
	public AppResultDto getQRCode(Long id) {
		try {
			if (dormCheckOutManager.exists(id)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("releaseCode", AUTHENTCODE);
				return AppResultUtil.createSuccesDto(map);
			} else {
				return AppResultUtil.createErrorDto("100", "非宿管物品放行单据");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取二维码相关信息失败：" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取二维码相关信息失败：" + e.getMessage());
		}
	}
}
