package com.palmnest.service.estateserve.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.EnterInputDto;
import com.palmnest.application.dto.input.EnterUpdateInputDto;
import com.palmnest.application.dto.output.*;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.UserDao;
import com.palmnest.dao.estateserve.*;
import com.palmnest.dao.repair.RepairBillDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.*;
import com.palmnest.model.emig.EmigrationSettle;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbBuild;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.model.repair.RepairBill;
import com.palmnest.service.AppFunctionManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.EnterpriseManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.property.PropertyManager;
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 javax.servlet.http.HttpServletRequest;

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

@Slf4j
@Service("enterpriseManager")
public class EnterpriseManagerImpl extends GenericManagerImpl<EnterpriseInfo, Integer> implements EnterpriseManager {


	private static final String QYRZ = "qyrz";

	private EnterpriseDao enterpriseDao;

	@Autowired
	public void setEnterpriseDao(EnterpriseDao enterpriseDao) {
		this.enterpriseDao = enterpriseDao;
		this.dao = enterpriseDao;
	}

	@Autowired
	private WatermeterDao      watermeterDao;
	@Autowired
	private RoomInfoDao        roomInfoDao;
	@Autowired
	private FloorInfoDao       floorInfoDao;
	@Autowired
	private EnterpriseAuditDao enterpriseAuditDao;
	@Autowired
	private UserDao            userDao;
	@Autowired
	private ReplayContentDao   replayContentDao;
	@Autowired
	private WeChatApiManager   weChatApiManager;
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private VirtualArchDao     virtualArchDao;
	@Autowired
	private RepairBillDao      repairBillDao;
	@Autowired
	private AppUserDao         appUserDao;
	@Autowired
	private VirtUserDao        virtUserDao;
	@Autowired
	private OrganizationDao    organizationDao;
	@Autowired
	private EmigrationDao      emigrationDao;
	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private VirArchModelDao    virArchModelDao;
	@Autowired
	private UserManager        userManager;
	@Autowired
	private AppFunctionManager appFunctionManager;

	public static String auditResultTempleteId   = PropertiesKit.readPropertiesValue("auditResultTempleteId", "wechat.properties");
	public static String enterEvaluateTempleteId = PropertiesKit.readPropertiesValue("enterEvaluateTempleteId", "wechat.properties");
	private       String hostUrl                 = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wxEnterEvaluateUrl      = PropertiesKit.readPropertiesValue("wxEnterEvaluateUrl", "wechat.properties");

	@Override
	public Page getEnterpriseListByStatus(int status, int pageSize, int pageNo) throws Exception {
		return enterpriseDao.getEnterpriseListByStatus(status, pageSize, pageNo);
	}


	@Override
	public Page getEnterListByStatus(String floorId, String roomId, String virName, int pageSize, int pageNo) throws Exception {
		return enterpriseDao.getEnterListByStatus(floorId, roomId, virName, pageSize, pageNo);
	}

	@Override
	public List<RepairBill> getRepaiBillByCodes(String codes) throws Exception {
		List<RepairBill> list = new ArrayList<RepairBill>();
		String           code = "";
		if (StringUtils.isNotEmpty(codes)) {
			String[] str = codes.split(";");
			if (str.length > 0) {
				for (int i = 0; i < str.length; i++) {
					code = "'" + str[i] + "',";
				}
				if (StringUtils.isNotEmpty(code)) {
					code = code.substring(0, code.length() - 1);
					list = enterpriseDao.getRepaiBillByCodes(code);
					return list;
				} else {
					return list;
				}
			} else {
				return list;
			}
		} else {
			return list;
		}
	}


	@Override
	public String isHavePower(String userId, int sysCode) throws Exception {
		return enterpriseDao.isHavePower(userId, sysCode);
	}


	public Page getEnterList(String virName, String type, int pageSize, int pageNo, int isHisList, String orgId) throws Exception {
		Page         page = enterpriseDao.getEnterList(virName, type, pageSize, pageNo, isHisList, orgId);
		List<Object> list = page.getItems();
		for (int i = 0; i < list.size(); i++) {
			Map<Object, Object> obj     = (Map<Object, Object>) list.get(i);
			int                 entId   = Integer.parseInt(obj.get("id").toString());
			EnterpriseInfo      entInfo = enterpriseDao.get(entId);
			if (entInfo != null) {
				String floorAndRoom = "";
				String roomIds      = entInfo.getRoomIds();
				if (StringUtils.isNotEmpty(roomIds)) {
					String[] roomIdStr = roomIds.split(";");
					if (roomIdStr != null && roomIdStr.length > 0) {
						for (int j = 0; j < roomIdStr.length; j++) {
							RoomInfo  roomInfo  = roomInfoDao.get(Integer.parseInt(roomIdStr[j]));
							FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
							floorAndRoom = floorAndRoom + floorInfo.getName() + "楼" + roomInfo.getName() + "、";
						}
					}
				}
				obj.put("floorAndRoom", floorAndRoom);
				String cutServic      = entInfo.getCustomerService();
				String cutServiceName = "";
				if (StringUtils.isNotEmpty(cutServic) && !"0".equals(cutServic)) {
					if (userDao.exists(Long.parseLong(cutServic))) {
						User user = userDao.get(Long.parseLong(cutServic));
						cutServiceName = user.getFullName();
					}
				}
				obj.put("cutServiceName", cutServiceName);
				String engPerson     = entInfo.getEngPerson();
				String engPersonName = "";
				if (StringUtils.isNotEmpty(engPerson) && !"0".equals(engPerson)) {
					if (userDao.exists(Long.parseLong(engPerson))) {
						User user = userDao.get(Long.parseLong(engPerson));
						engPersonName = user.getFullName();
					}
				}
				obj.put("engPersonName", engPersonName);

				if (Integer.parseInt(type) == 2) {
					String           isSendSettle = "1";//未发送
					EmigrationSettle esInfo       = emigrationDao.getEmigrationSettle(entId);
					if (esInfo != null) {
						isSendSettle = "2";//已发送
					}
					obj.put("isSendSettle", isSendSettle);
				}
			}
		}
		return page;
	}

	public Page getEnterListByUser(String virName, int userId, String floorIds, int pageSize,
								   int pageNo, int state, int isHisList, int havePower) throws Exception {
		Page         page = enterpriseDao.getEnterListByUser(virName, userId, floorIds, pageSize, pageNo, state, isHisList, havePower);
		List<Object> list = page.getItems();
		for (int i = 0; i < list.size(); i++) {
			Map<Object, Object> obj     = (Map<Object, Object>) list.get(i);
			int                 entId   = Integer.parseInt(obj.get("id").toString());
			EnterpriseInfo      entInfo = enterpriseDao.get(entId);
			if (entInfo != null) {
				String floorAndRoom = "";
				String roomIds      = entInfo.getRoomIds();
				if (StringUtils.isNotEmpty(roomIds)) {
					String[] roomIdStr = roomIds.split(";");
					if (roomIdStr != null && roomIdStr.length > 0) {
						for (int j = 0; j < roomIdStr.length; j++) {
							RoomInfo  roomInfo  = roomInfoDao.get(Integer.parseInt(roomIdStr[j]));
							FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
							floorAndRoom = floorAndRoom + floorInfo.getName() + "楼" + roomInfo.getName() + "、";
						}
					}
				}
				obj.put("floorAndRoom", floorAndRoom);
				String cutServic      = entInfo.getCustomerService();
				String cutServiceName = "";
				if (StringUtils.isNotEmpty(cutServic) && !"0".equals(cutServic)) {
					if (userDao.exists(Long.parseLong(cutServic))) {
						User user = userDao.get(Long.parseLong(cutServic));
						cutServiceName = user.getFullName();
					}
				}
				obj.put("cutServiceName", cutServiceName);
				obj.put("havePower", havePower);
				String engPerson     = entInfo.getEngPerson();
				String engPersonName = "";
				if (StringUtils.isNotEmpty(engPerson) && !"0".equals(engPerson)) {
					if (userDao.exists(Long.parseLong(engPerson))) {
						User user = userDao.get(Long.parseLong(engPerson));
						engPersonName = user.getFullName();
					}
				}
				obj.put("engPersonName", engPersonName);

				if (state == 2) {
					String           isSendSettle = "1";//未发送
					EmigrationSettle esInfo       = emigrationDao.getEmigrationSettle(entId);
					if (esInfo != null) {
						isSendSettle = "2";//已发送
					}
					obj.put("isSendSettle", isSendSettle);
				}
			}
		}
		return page;
	}

	@Override
	@Transactional
	public AppResultDto updateEnterInfo(EnterWaterRepailInfo enterWaterRepailInfo) throws Exception {
		EnterpriseInfo entInfo = enterWaterRepailInfo.getEnterpriseInfo();
//		List<RepairBill> repList=enterWaterRepailInfo.getRepairList();
		StringBuilder number = new StringBuilder("");
		try {
//			if(repList!=null&&repList.size()>0){
//				for(int i=0;i<repList.size();i++){
//					RepairBill repInfo=repList.get(i);
//					number.append(repInfo+";");
//				}
//			}
			if (entInfo != null) {
				//维修单由前端传以分号分隔
//				entInfo.setRepairNumber(number.toString());
				entInfo.setModifyTime(new Date());
				entInfo.setModifier(enterWaterRepailInfo.getUserId());
				entInfo.setStatus(enterWaterRepailInfo.getStatus());//0代表客服主管，1代表选了跟进客服，2代表选了跟进工程人员，3代表通过，4代表拒绝 ，100代表全部
				enterpriseDao.updateObj(entInfo);
			}
			if (entInfo != null && entInfo.getId() != 0) {//删除水电表信息
				watermeterDao.removeWaterList(entInfo.getId(), 1);
			}
			List<WatermeterInfo> wateList = enterWaterRepailInfo.getWateList();
			if (wateList != null && wateList.size() > 0) {
				for (int i = 0; i < wateList.size(); i++) {
					WatermeterInfo wateInfo = wateList.get(i);
					wateInfo.setCreateTime(new Date());
					wateInfo.setCreator(enterWaterRepailInfo.getUserId());
					watermeterDao.save(wateInfo);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败");
		}

		return AppResultUtil.createSuccesDto(entInfo);

	}


	@Override
	public Page getEnterHisListByUser(String virName, int status, int userId, String floorIds, int pageSize, int pageNo, int state) throws Exception {
		Page         page = enterpriseDao.getEnterHisListByUser(virName, status, userId, floorIds, pageSize, pageNo, state);
		List<Object> list = page.getItems();
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> map     = new HashMap<String, String>();
			Map<Object, Object> obj     = (Map<Object, Object>) list.get(i);
			int                 entId   = Integer.parseInt(obj.get("id").toString());
			EnterpriseInfo      entInfo = enterpriseDao.get(entId);
			if (entInfo != null) {
				String   floorAndRoom = "";
				String   roomIds      = entInfo.getRoomIds();
				String[] roomIdStr    = roomIds.split(";");
				if (roomIdStr != null && roomIdStr.length > 0) {
					for (int j = 0; j < roomIdStr.length; j++) {
						RoomInfo  roomInfo  = roomInfoDao.get(Integer.parseInt(roomIdStr[j]));
						FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
						floorAndRoom = floorAndRoom + floorInfo.getName() + "楼" + roomInfo.getName() + "、";
					}
				}
				obj.put("floorAndRoom", floorAndRoom);

				if (state == 2) {
					String           isSendSettle = "1";//未发送
					EmigrationSettle esInfo       = emigrationDao.getEmigrationSettle(entId);
					if (esInfo != null) {
						isSendSettle = "2";//已发送
					}
					obj.put("isSendSettle", isSendSettle);
				}
			}
		}
		return page;
	}


	@Override
	public EnterpriseDto getEnterInfo(int id, String userId) throws Exception {
		EnterpriseInfo enterInfo = enterpriseDao.get(id);
		try {
			if (enterInfo != null) {
				EnterInfoDto         dto          = new EnterInfoDto();
				String               floorAndRoom = getFloorAndRooms(enterInfo);
				List<TbOrganization> list         = virtualArchDao.getBuild();
				String               orgName      = "";
				if (list != null && list.size() > 0) {
					TbOrganization orgInfo = list.get(0);
					orgName = orgInfo.getName();
				}
				List<WatermeterInfo> wateList      = watermeterDao.getWatermeterList(id, 1, "", "");
				String               wateInfo      = "未提交";
				int                  waterInfoType = 1;
				if (wateList != null && wateList.size() > 0) {
					wateInfo = "已提交";
					waterInfoType = 2;
				}
				String                reason    = "";
				List<EnterpriseAudit> auditList = enterpriseAuditDao.getEnterAuditList("1", id);//1代表企业入驻
				if (auditList != null && auditList.size() > 0) {
					EnterpriseAudit audit = auditList.get(0);
					reason = audit.getContent();
				}
				String cusServiceName = "";
				if (StringUtils.isNotEmpty(enterInfo.getCustomerService()) && !"0".equals(enterInfo.getCustomerService())) {
					User user = userDao.get(Long.parseLong(enterInfo.getCustomerService()));
					cusServiceName = user.getFullName();
				}
				String engPersonName = "";
				if (StringUtils.isNotEmpty(enterInfo.getEngPerson()) && !"0".equals(enterInfo.getEngPerson())) {
					User user = userDao.get(Long.parseLong(enterInfo.getEngPerson()));
					engPersonName = user.getFullName();
				}
				String cusSerivce = "0";
				if (StringUtils.isNotEmpty(enterInfo.getCustomerService())) {
					cusSerivce = enterInfo.getCustomerService();
				}
				String engPeason = "0";
				if (StringUtils.isNotEmpty(enterInfo.getEngPerson())) {
					engPeason = enterInfo.getEngPerson();
				}

				String isSupervisor  = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
				String isCustService = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
				String isProgramme   = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERENG_PERMISSION));
				//havePower:1代表三种权限都包含;2代表有客服主管和客服权限；3代表客服主管和工程人员；4代表客服和工程人员；5客服主管；6客服；7工程人员
				String peasonPower = "";
//				if("1".equals(isSupervisor)&&"1".equals(isCustService)){
//					peasonPower="4";
//				}else if("1".equals(isSupervisor)){
//					peasonPower="1";
//				}else if("1".equals(isCustService)){
//					peasonPower="2";
//				}else if("1".equals(isProgramme)){
//					peasonPower="3";
//				}
//				
				if ("1".equals(isSupervisor) && "1".equals(isCustService) && "1".equals(isProgramme)) {
					peasonPower = "7";
				} else if ("1".equals(isSupervisor) && "1".equals(isCustService)) {
					peasonPower = "4";
				} else if ("1".equals(isSupervisor) && "1".equals(isProgramme)) {
					peasonPower = "5";
				} else if ("1".equals(isCustService) && "1".equals(isProgramme)) {
					peasonPower = "6";
				} else if ("1".equals(isSupervisor)) {
					peasonPower = "1";
				} else if ("1".equals(isCustService)) {
					peasonPower = "2";
				} else if ("1".equals(isProgramme)) {
					peasonPower = "3";
				}
				EnterpriseDto enDto = new EnterpriseDto(enterInfo.getId(), enterInfo.getEnterNumber(), enterInfo.getOrgId(), orgName, floorAndRoom, enterInfo.getVirName()
						, enterInfo.getApplyName(), enterInfo.getApplyTel(), enterInfo.getRemanEmail1(), enterInfo.getOtherRecord() == null ? "" : enterInfo.getOtherRecord(), enterInfo.getCreator()
						, enterInfo.getModifier(), enterInfo.getStatus(), enterInfo.getRepairNumber() == null ? "" : enterInfo.getRepairNumber(), Integer.parseInt(cusSerivce), Integer.parseInt(engPeason)
						, cusServiceName, engPersonName, wateInfo, waterInfoType, reason, peasonPower);
				enDto.setCreateTime(DateHelper.formatDate(enterInfo.getCreateTime(), DateHelper.DATE_STRING));
				if (enterInfo.getModifyTime() != null) {
					enDto.setModifyTime(DateHelper.formatDate(enterInfo.getModifyTime(), DateHelper.DATE_STRING));
				}
				return enDto;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new Exception(e);
		}

		return null;
	}

	@Override
	public String getFloorAndRooms(EnterpriseInfo enterInfo) {
		String   floorAndRoom = "";
		String   roomIds      = enterInfo.getRoomIds();
		String[] roomIdStr    = null;
		if (StringUtils.isNotBlank(roomIds)) {
			roomIdStr = roomIds.split(";");
		}
		if (roomIdStr != null && roomIdStr.length > 0) {
			for (int j = 0; j < roomIdStr.length; j++) {
				if(roomInfoDao.exists(Integer.parseInt(roomIdStr[j]))){
					RoomInfo  roomInfo  = roomInfoDao.get(Integer.parseInt(roomIdStr[j]));
					if(floorInfoDao.exists(Integer.parseInt(String.valueOf(roomInfo.getFloorId())))){
						FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
						floorAndRoom = floorAndRoom + floorInfo.getName() + "楼" + roomInfo.getName() + "、";
					}
				}
			}
		}
		return floorAndRoom;
	}

	public String getFloorAndRoom(int floorId, int roomId) {
		String    floorAndRoom = "";
		FloorInfo floor        = floorInfoDao.get(floorId);
		RoomInfo  room         = roomInfoDao.get(roomId);
		if (floor != null && room != null) {
			floorAndRoom = floor.getName() + "楼" + room.getName();
		}
		return floorAndRoom;
	}


	@Override
	public Map<String, Object> uploadImage(HttpServletRequest request)
			throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile               file             = multipartRequest.getFile("filedata");// 这里是表单的名字，在swfupload.js中this.ensureDefault("file_post_name",
			// "filedata");
			InputStream stream  = null;
			String      fileExt = null;
			if (file != null) {
				stream = file.getInputStream();
				String fileName = file.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);
			data.put("url", url.trim());
			data.put("preview", fileUploadUtils.fullVisitPath(url));
			return data;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return null;
		}
	}


	@Override
	@Transactional
	public AppResultDto updateEnterInfoDto(EnterUpdateInputDto enterUpdateInputDto) throws Exception {
		EnterInputDto        ent      = enterUpdateInputDto.getEnterInputDto();
		List<WatermenterDto> wateList = enterUpdateInputDto.getWateList();
		int                  userId   = enterUpdateInputDto.getUserId();
		try {
			EnterpriseInfo entInfo = enterpriseDao.get(ent.getId());
			entInfo.setCustomerService(ent.getCustomerService());
			entInfo.setEngPerson(ent.getEngPerson());
			entInfo.setRepairNumber(ent.getRepairNumber());
			if (StringUtils.isNotEmpty(ent.getCustomerService())) {
				if (StringUtils.isNotEmpty(ent.getEngPerson())) {//选了跟进客服并且选了跟进工程人员
					if (wateList != null && wateList.size() > 0) {
						entInfo.setStatus("5");
					} else {
						entInfo.setStatus("2");
					}
				} else {//只选了跟进客服
					entInfo.setStatus("1");
				}
			}

			entInfo.setCreateTime(new Date());
			entInfo.setCreator(userId);
			enterpriseDao.updateObj(entInfo);

			if (wateList != null && wateList.size() > 0) {
				//修改企业的时候需要判断走到谁那里了，需要推送消息
				if (entInfo != null && entInfo.getId() != 0) {//删除水电表信息
					watermeterDao.removeWaterList(entInfo.getId(), 1);
				}
				for (int i = 0; i < wateList.size(); i++) {
					WatermenterDto wateDto  = wateList.get(i);
					WatermeterInfo wateInfo = new WatermeterInfo();
					wateInfo.setEnterType(wateDto.getEnterType());
					wateInfo.setFloorId(wateDto.getFloorId());
					wateInfo.setWateImageUrl(wateDto.getWateImageUrl());
					wateInfo.setMaterImageUrl(wateDto.getMaterImageUrl());
					wateInfo.setIsEnabled("1");
					wateInfo.setWateReading(wateDto.getWateReading());
					wateInfo.setMaterReading(wateDto.getMaterReading());
					wateInfo.setRoomId(wateDto.getRoomId());
					wateInfo.setSourseId(wateDto.getSourseId());
					wateInfo.setCreateTime(new Date());
					wateInfo.setCreator(userId);
					watermeterDao.save(wateInfo);
				}
			}
			return AppResultUtil.createSuccesDto(entInfo);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败");
		}
	}


	@Override
	public List<Map<String, Object>> getPower(String floors, int sysCode) throws Exception {
		return enterpriseDao.getPower(floors, sysCode);
	}


	@Override
	public String getPowerFloor(int userId, int sysCode) throws Exception {
		String floorIds = "";
		List   list     = enterpriseDao.getPowerFloor(userId, sysCode);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = (Map<String, Object>) list.get(i);
			if (map.get("floorId") != null) {
				floorIds = floorIds + map.get("floorId") + ";";
			}

		}
		return floorIds;
	}

	public String getEngProFloor() throws Exception {
		String          floorIds = "";
		List<FloorInfo> list     = floorInfoDao.getFloorAll();
		for (int i = 0; i < list.size(); i++) {
			FloorInfo floorInfo = list.get(i);
			if (floorInfo != null) {
				floorIds = floorIds + floorInfo.getId() + ";";
			}

		}
		return floorIds;
	}

	@Override
	public String getPowerFloors(int userId, int sysCode, String orgId) throws Exception {
		String floorIds = "";
		List   list     = enterpriseDao.getPowerFloor(userId, sysCode);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = (Map<String, Object>) list.get(i);
			if (map.get("floorId") != null) {
				FloorInfo floorInfo = floorInfoDao.get(Integer.parseInt(map.get("floorId").toString()));
				if (StringUtils.isNotEmpty(orgId)) {
					if (orgId.equals(String.valueOf(floorInfo.getOrganizationId()))) {
						floorIds = floorIds + map.get("floorId") + ";";
					}
				}
			}

		}
		return floorIds;
	}


	@Override
	public List<Map<String, Object>> getEnterInfoList(int userId, int type, String port, String orgId) throws Exception {
		List<EnterpriseInfo>      list    = enterpriseDao.getEnterInfoList(userId, type, port, orgId);
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map       = new HashMap<String, Object>();
				EnterpriseInfo      enterInfo = list.get(i);
				if (enterInfo != null) {
					map.put("id", enterInfo.getId());
					map.put("name", enterInfo.getVirName());
					map.put("status", enterInfo.getStatus());//状态(1-待审核;2-通过;3拒绝;)
					map.put("time", DateHelper.formatDate(enterInfo.getCreateTime(), DateHelper.DATE_STRING));
					TbBuild tbBuild = (TbBuild) propertyManager.getTbBuildById(Integer.parseInt(enterInfo.getOrgId()));
					map.put("buildName", tbBuild == null ? "" : tbBuild.getName());
					map.put("applyName", enterInfo.getApplyName());
				}
				mapList.add(map);
			}
		}
		return mapList;
	}


	@Override
	@Transactional
	public EnterpriseAudit saveEnterAudit(String reason, String userId, String enterId, String resonType, String type, String signingTime, String contExpireTime) throws Exception {
		EnterpriseAudit audit = new EnterpriseAudit();
		try {
			audit.setContent(reason);
			audit.setCreateTime(new Date());
			audit.setCreator(Integer.parseInt(userId));
			audit.setType(type);
			audit.setReasonType(Integer.parseInt(resonType));
			audit.setSourseId(Integer.parseInt(enterId));
			audit = enterpriseAuditDao.save(audit);
			if (audit != null) {
				EnterpriseInfo enterInfo = enterpriseDao.get(Integer.parseInt(enterId));
				/*if(audit.getReasonType()==1){
					enterInfo.setStatus("3");
				}else if (audit.getReasonType()==0){
					enterInfo.setStatus("4");
				}*/
				enterInfo.setSigningTime(signingTime);
				enterInfo.setContExpireTime(contExpireTime);
				enterInfo.setStatus(audit.getReasonType() + "");
				enterInfo.setModifier(Integer.parseInt(userId));
				enterInfo.setModifyTime(new Date());
				enterpriseDao.updateObj(enterInfo);
				if ("2".equals(enterInfo.getStatus()) && "1".equals(type)) {//通过就把企业入驻的信息保存到企业表中
					VirtualArchitecture virInfo = saveVirInfo(enterInfo, userId, reason);
					if (virInfo != null) {
						enterInfo.setVirId(virInfo.getId());
						enterpriseDao.updateObj(enterInfo);
					}
				} else if ("2".equals(enterInfo.getStatus()) && "2".equals(type)) {//通过就把企业信息修改为迁出
					VirtualArchitecture virInfo = virtualArchDao.get(enterInfo.getVirId());
					if (virInfo != null) {
						virInfo.setLeaseStatus(0);
						User user = userDao.get(Long.parseLong(userId));
						virInfo.setModifier(user.getUsername());
						virInfo.setModifyTime(new Date());
						virtualArchDao.updateObj(virInfo);
						enterpriseDao.updateObj(enterInfo);
					}
				}
			}

		} catch (Exception e) {
			throw new Exception(e);
		}
		return audit;
	}

	@Transactional
	public VirtualArchitecture saveVirInfo(EnterpriseInfo enterInfo, String userId, String reason) throws Exception {
		String userName = "";
		if (StringUtils.isNotEmpty(userId)) {
			User user = userDao.get(Long.parseLong(userId));
			userName = user.getUsername();
		}
		VirtualArchitecture virInfo = new VirtualArchitecture();
		virInfo.setName(enterInfo.getVirName());
		virInfo.setType("1");                //1-表示企业，2-表示部门
		virInfo.setPhone(enterInfo.getRemanTel1());
		virInfo.setContacts(enterInfo.getRemanName1());
		TbBuild tbBuild = propertyManager.getTbBuildById(Integer.parseInt(enterInfo.getOrgId()));
		virInfo.setOrganizationId(tbBuild.getOrganizationId());        //项目ID
		virInfo.setBuildId(Integer.parseInt(enterInfo.getOrgId()));//楼宇id
		virInfo.setCustomerType("0");        //客户类型（1-VIP客户，0-普通客户）
		virInfo.setContractStatus("1");        //签约状态（1-已签约，0-未签约）
		virInfo.setStatus("1");                //企业状态（0-待审核，1-通过，2-不通过）
		virInfo.setReviewRemark(reason);        //审核信息说明
		virInfo.setWxUserId(enterInfo.getCreator());//申请人的微信信息ID-------------是创建人还是申请人？？
		virInfo.setCreateTime(new Date());
		virInfo.setCreator(userId);
		virInfo.setIsEnabled("1");
		virInfo.setFloorIds(enterInfo.getFloorIds());
		virInfo.setRoomIds(enterInfo.getRoomIds());
		virInfo.setFloorAndNames(getFloorAndRooms(enterInfo));//楼层房间号组合
		virInfo.setBusinessImageUrl(enterInfo.getBusinessImageUrl());
		virInfo.setPowerAttorneyImageUrl(enterInfo.getPowerAttorneyImageUrl());
		virInfo.setPowerFaceImageUrl(enterInfo.getPowerFaceImageUrl());
		virInfo.setPowerNationImageUrl(enterInfo.getPowerNationImageUrl());
		virInfo.setLeaseStatus(1);
		virInfo.setIsEmail(enterInfo.getIsEmail());
		virInfo.setIsWechat(enterInfo.getIsWechat());
		virInfo.setIsMessage(enterInfo.getIsMessage());
		virInfo.setFloorNames(enterInfo.getFloorNames());
		virInfo.setRoomNames(enterInfo.getRoomNames());
		virInfo.setAddress(enterInfo.getAddress());
		virInfo.setSigningTime(enterInfo.getSigningTime());
		virInfo.setContExpireTime(enterInfo.getContExpireTime());
//		TbOrganization orgInfo=organizationDao.getOrganizationById(Integer.parseInt(enterInfo.getOrgId()));
//		String orgName=orgInfo.getName();
//		String address=orgName+getFloorAndRooms(enterInfo);
//		virInfo.setAddress(address);
		virInfo = virtualArchDao.save(virInfo);
		/*if(virInfo!=null){
			if(StringUtils.isNotEmpty(enterInfo.getRemanTel1())){//负责人1不为空
				AppUser appUser=appUserDao.getAppUsersByPhone(enterInfo.getRemanTel1());
				if(appUser==null){
					appUser=new AppUser();
				}
				appUser.setUserName(enterInfo.getRemanName1());
				appUser.setEmail(enterInfo.getRemanEmail1());
				appUser.setIsPushPower(enterInfo.getIsPushPower1());
				appUser.setRoleType("1");
				appUser.setIsReleasePower(enterInfo.getIsReleasePower1());
				appUser.setIsResponsible(1);
				appUser.setUserMobile(enterInfo.getRemanTel1());
				appUser.setIsEnabled("1");
				appUser.setReOrder(1);
				appUser.setOrganizationId(Integer.parseInt(enterInfo.getOrgId()));
				appUser.setVirtualArchId(virInfo.getId());
				if(appUser!=null&&appUser.getId()!=null){
					appUser.setModifier(userName);
					appUser.setModifyTime(new Date());
					appUserDao.updateObj(appUser);
				}else{
					appUser.setCreator(userName);
					appUser.setCreateTime(new Date());
					appUser=appUserDao.save(appUser);
				}
				//保存企业-用户（负责人2信息）中间表2
				VirtUserInfo vuInfo=new VirtUserInfo();
				vuInfo.setReorder(appUser.getReOrder());
				vuInfo.setVirId(virInfo.getId());
				vuInfo.setUserId(appUser.getId());
				virtUserDao.save(vuInfo);
			}
			if(StringUtils.isNotEmpty(enterInfo.getRemanTel2())){//负责人2不为空
				AppUser appUser=appUserDao.getAppUsersByPhone(enterInfo.getRemanTel2());
				if(appUser==null){
					appUser=new AppUser();
				}
				appUser.setUserName(enterInfo.getRemanName2());
				appUser.setEmail(enterInfo.getRemanEmail2());
				appUser.setIsPushPower(enterInfo.getIsPushPower2());
				appUser.setRoleType("1");
				appUser.setIsReleasePower(enterInfo.getIsReleasePower2());
				appUser.setIsResponsible(1);
				appUser.setIsEnabled("1");
				appUser.setUserMobile(enterInfo.getRemanTel2());
				appUser.setReOrder(2);
				appUser.setOrganizationId(Integer.parseInt(enterInfo.getOrgId()));
				appUser.setVirtualArchId(virInfo.getId());
				if(appUser!=null&&appUser.getId()!=null){
					appUser.setModifier(userName);
					appUser.setModifyTime(new Date());
					appUserDao.updateObj(appUser);
				}else{
					appUser.setCreator(userName);
					appUser.setCreateTime(new Date());
					appUser=appUserDao.save(appUser);
				}
				//保存企业-用户（负责人2信息）中间表2
				VirtUserInfo vuInfo=new VirtUserInfo();
				vuInfo.setReorder(appUser.getReOrder());
				vuInfo.setVirId(virInfo.getId());
				vuInfo.setUserId(appUser.getId());
				virtUserDao.save(vuInfo);
			}
		}*/
		return virInfo;
	}

	/**
	 * 推送消息
	 *
	 * @param entInfo
	 * @throws Exception
	 */
	@Async
	public String sendUpdateEnterMessage(EnterpriseInfo entInfo, String pesonId) throws Exception {
		String status  = entInfo.getStatus();
		String state   = entInfo.getState();
		String content = "";
		String title   = "";
		try {
			if ("1".equals(state) && "1".equals(status)) {//企业入驻推送给跟进客服
				content = "选择跟进工程，处理入驻单。";
				title = "有新入驻单待处理.";
			} else if ("1".equals(state) && "2".equals(status)) {//企业入驻推送给跟进工程人员
				content = "有新入驻单待处理。";
				title = "有新入驻单待处理.";
			} else if ("2".equals(state) && "1".equals(status)) {//企业迁出推送给跟进客服
				content = "选择跟进工程，处理迁出单。";
				title = "有新迁出单待处理.";
			} else if ("2".equals(state) && "2".equals(status)) {//企业迁出推送给跟进工程人员
				content = "有新迁出单待处理。";
				title = "有新迁出单待处理.";
			}
			List<User> userList = new ArrayList<User>();
			User       user     = new User();
			if (StringUtils.isNotEmpty(pesonId)) {
				boolean bool = userDao.exists(Long.parseLong(pesonId));
				if (bool) {
					user = userDao.get(Long.valueOf(pesonId));
					userList.add(user);
				}
			}

			String id   = entInfo.getId().toString();
			String code = "";
			if ("1".equals(entInfo.getState())) {
				code = CodeConstants.ENTER_PUSH_CODE;
			} else if ("2".equals(entInfo.getState())) {
				code = CodeConstants.EMIG_PUSH_CODE;
			}
			PushMessageHelper helper=new PushMessageHelper();
			helper.pushMessage(Long.parseLong(id), code, userList, title, content);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new Exception(e);
		}

		return "";

	}

	/**
	 * 保存企业入驻
	 *
	 * @param entInfo
	 * @throws Exception
	 */
	@Override
	@Transactional
	public AppResultDto saveEnterInfo(EnterpriseInfo entInfo, int userId) throws Exception {
		if (entInfo != null) {
			entInfo.setCreateTime(new Date());
			entInfo.setIsEnabled("1");
			entInfo.setStatus("1");
			entInfo.setState("1");
			entInfo.setCreator(userId);
			entInfo.setCreateTime(new Date());
//			TbOrganization orgInfo=virtualArchDao.getBuild().get(0);
//			entInfo.setOrgId(String.valueOf(orgInfo.getId()));
			entInfo.setEnterNumber(CodeGenerateUtils.generate(QYRZ));
			entInfo = enterpriseDao.save(entInfo);
			return AppResultUtil.createSuccesDto(entInfo);
		} else {
			return AppResultUtil.createErrorDto("100", "企业入驻申请信息获取失败");
		}
	}


	@Async
	public String sendMessageByCusService(EnterpriseInfo entInfo) throws Exception {
//		String floorIds=entInfo.getFloorIds();
//		List<Map<String, Object>> list=enterpriseDao.getPower(floorIds, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
		//依据项目查询有操作权限的人
		int                       orgId   = propertyManager.getTbBuildById(Integer.parseInt(entInfo.getOrgId())).getOrganizationId();
		String                    title   = "";
		String                    content = "";
		List<Map<String, Object>> list    = new ArrayList<Map<String, Object>>();

		if (entInfo.getState() == "1") {//入驻
			//查询此项目下有入驻审批权限的用户
			list = enterpriseDao.getPowerByOrg(orgId, Integer.parseInt(CodeConstants.ENTERAPPROVE_PERMISSION));
			content = "申请人姓名:" + entInfo.getApplyName() + ",申请企业:" + entInfo.getVirName();
			title = "有新入驻单待处理";
		} else if (entInfo.getState() == "2") {//迁出
			//查询此项目下有迁出审批权限的用户
			list = enterpriseDao.getPowerByOrg(orgId, Integer.parseInt(CodeConstants.EMIGAPPROVE_PERMISSION));
			content = "申请人姓名:" + entInfo.getApplyName() + ",申请企业:" + entInfo.getVirName();
			title = "有迁出单待处理";
		}

		String result = "fail";
		int    count  = 0;
		String id     = entInfo.getId().toString();
		String code   = "";
		if ("1".equals(entInfo.getState())) {//企业入驻
			code = CodeConstants.ENTER_PUSH_CODE;
		} else if ("2".equals(entInfo.getState())) {//企业迁出
			code = CodeConstants.EMIG_PUSH_CODE;
		}
		try {
			List<User> userList = new ArrayList<User>();
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> map = list.get(i);
					if (map.get("usId") != null && StringUtils.isNotEmpty(map.get("usId").toString())) {
						boolean bool = userDao.exists(Long.parseLong(map.get("usId").toString()));
						if (bool) {
							User user = userDao.get(Long.parseLong(map.get("usId").toString()));
							userList.add(user);
						}
					}
				}

			}
			if (userList != null && userList.size() > 0) {
				PushMessageHelper helper=new PushMessageHelper();
				helper.pushMessage(Long.parseLong(id), code, userList, title, content);
			}
			if (count == 0) {
				result = "success";
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "fail";
			log.error(e.getMessage());
			throw new Exception(e);
		}
		return result;
	}


	/**
	 * 推送微信消息
	 */
	@Async
	public String sendWechat(String virName, String floorAndRoom, String reason, int state, int status, String wxUserId) throws Exception {
//		List<WxtemplateMessageTypeModel> templateList=replayContentDao.getWxTemplateByTempId(0, "KlRZryc99rR8oHAlQ9e6gIrzMHSKOgLTyGNsF4K7KZ4");
		String code = "fail";
		//根据state判断审批类型是企业入驻的还是企业迁出的
		//根据status判断是拒绝还是通过
		String type   = "";
		String result = "";
		String title  = "";
		String remark = "";
		if (state == 1) {
			type = "企业入驻";
			if (status == 1) {
				result = "审核已通过";
				title = "还好没放弃，终于等到您！请在客服人员的协助下办理入驻手续喔！";
				remark = "我们在这里热忱地欢迎您的入驻，祝您生活愉快！生意兴隆！";
			} else {
				result = "审核已拒绝";
				title = "您的申请已被拒绝，请尽快处理相关拒绝原因，再重新提交申请！";
				remark = "我们在这里等着您，盼您早日归来！";
			}
		} else {
			type = "企业迁出";
			if (status == 1) {
				result = "审核已通过";
				title = "您的迁出申通已受理，请在客服人员的协助下办理迁出手续！";
				remark = "欢迎您能再次回家！";
			} else {
				result = "审核已拒绝";
				title = "您的申请已被拒绝，请尽快处理相关拒绝原因，再重新提交申请！";
				remark = "欢迎您能再次回家！";
			}
		}

		String templateId = auditResultTempleteId;

		if (StringUtils.isNotEmpty(templateId)) {

			Map<String, String> paramMap = new HashMap<String, String>();
			if (StringUtils.isNotEmpty(wxUserId)) {
				String[] strL = wxUserId.split(",");
				if (strL.length > 1) {
					for (int i = 0; i < strL.length; i++) {
						boolean bool = scWxuserManager.exists(Integer.parseInt(strL[i]));
						if (bool) {
							WxUser wxUser = scWxuserManager.get(Integer.parseInt(strL[i]));
							paramMap.put("developId", wxUser.getDevelopId());
							paramMap.put("openId", wxUser.getOpenId());
							paramMap.put("templateId", templateId);
							paramMap.put("url", "");
							paramMap.put("first", title);
							paramMap.put("keyword1", type);//审核类型
							paramMap.put("keyword2", result);//审核结果
							paramMap.put("keyword3", "房间号为：" + floorAndRoom + "的企业：" + virName + "的审核意见为：" + reason);//审核原因
							paramMap.put("remark", remark);
							weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, "", Integer.parseInt(strL[i]), paramMap);
						}
					}
				} else {
					boolean bool = scWxuserManager.exists(Integer.parseInt(wxUserId));
					if (bool) {
						WxUser wxUser = scWxuserManager.get(Integer.parseInt(wxUserId));
						paramMap.put("developId", wxUser.getDevelopId());
						paramMap.put("openId", wxUser.getOpenId());
						paramMap.put("templateId", templateId);
						paramMap.put("url", "");
						paramMap.put("first", title);
						paramMap.put("keyword1", type);//审核类型
						paramMap.put("keyword2", result);//审核结果
						paramMap.put("keyword3", "房间号为：" + floorAndRoom + "的企业：" + virName + "的审核意见为：" + reason);//审核原因
						paramMap.put("remark", remark);
						weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, "", Integer.parseInt(wxUserId), paramMap);
					}
				}
			}
		}
		return code;
	}


	@Override
	public List<Map<String, Object>> getRepairNumberList(String repairNumbers)
			throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (StringUtils.isNotEmpty(repairNumbers)) {
			String[] str       = repairNumbers.split(";");
			String   numberStr = "";
			for (int i = 0; i < str.length; i++) {
				numberStr = numberStr + "'" + str[i] + "',";
			}
			if (StringUtils.isNotEmpty(numberStr)) {
				numberStr = numberStr.substring(0, numberStr.length() - 1);
				list = enterpriseDao.getRepairNumberList(numberStr);
			}
		}
		return list;
	}


	@Override
	public AppResultDto getWateSizeListByRooms(String rooms, EnterpriseInfo enterInfo) throws Exception {
		Map<String, Object>       objMap = new HashMap<String, Object>();
		List<Map<String, Object>> list   = new ArrayList<Map<String, Object>>();
		try {
			String[] str = rooms.split(";");
			for (int i = 0; i < str.length; i++) {
				Map<String, Object> map       = new HashMap<String, Object>();
				RoomInfo            roomInfo  = roomInfoDao.get(Integer.parseInt(str[i]));
				FloorInfo           floorInfo = floorInfoDao.get(Integer.parseInt(String.valueOf(roomInfo.getFloorId())));
				map.put("sourseId", enterInfo.getId());
				map.put("enterType", enterInfo.getState());
				map.put("roomId", str[i]);
				map.put("floorId", floorInfo.getId());
				map.put("floorAndRoom", floorInfo.getName() + "楼" + roomInfo.getName());
				list.add(map);
			}
			objMap.put("wateList", list);
			TbOrganization orgInfo = organizationDao.getOrganizationById(Integer.parseInt(enterInfo.getOrgId()));
			objMap.put("orgName", orgInfo.getName());
			objMap.put("floorAndRoom", getFloorAndRooms(enterInfo));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取房间水电表信息失败：" + e.getMessage());
		}

		return AppResultUtil.createSuccesDto(objMap);
	}

	@Override
	public Page getEnterListByType(String type, String userId, String virName, int pageSize, int pageNo, int isHisList) throws Exception {
		if ("1".equals(type)) {//企业入驻
			String isSupervisor  = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
			String isCustService = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
			String isProgramme   = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERENG_PERMISSION));

			//havePower:1代表三种权限都包含;2代表有客服主管和客服权限；3代表客服主管和工程人员；4代表客服和工程人员；5客服主管；6客服；7工程人员
			if ("1".equals(isSupervisor) && "1".equals(isCustService) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 1);
				return page;
			} else if ("1".equals(isSupervisor) && "1".equals(isCustService)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 2);
				return page;
			} else if ("1".equals(isSupervisor) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 3);
				return page;
			} else if ("1".equals(isCustService) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 4);
				return page;
			} else if ("1".equals(isSupervisor)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 5);
				return page;
			} else if ("1".equals(isCustService)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 6);
				return page;
			} else if ("1".equals(isProgramme)) {
//				String floorIds=getPowerFloor(Integer.parseInt(userId),Integer.parseInt(CodeConstants.ENTERENG_PERMISSION));
				String floorIds = getEngProFloor();
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 1, isHisList, 7);
				return page;
			}

		} else if ("2".equals(type)) {//企业迁出
			String isSupervisor  = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
			String isCustService = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));
			String isProgramme   = enterpriseDao.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGENG_PERMISSION));
			//havePower:1代表三种权限都包含;2代表有客服主管和客服权限；3代表客服主管和工程人员；4代表客服和工程人员；5客服主管；6客服；7工程人员
			if ("1".equals(isSupervisor) && "1".equals(isCustService) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 1);
				return page;
			} else if ("1".equals(isSupervisor) && "1".equals(isCustService)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 2);
				return page;
			} else if ("1".equals(isSupervisor) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 3);
				return page;
			} else if ("1".equals(isCustService) && "1".equals(isProgramme)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 4);
				return page;
			} else if ("1".equals(isSupervisor)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 5);
				return page;
			} else if ("1".equals(isCustService)) {
				String floorIds = getPowerFloor(Integer.parseInt(userId), Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 6);
				return page;
			} else if ("1".equals(isProgramme)) {
//				String floorIds=getPowerFloor(Integer.parseInt(userId),Integer.parseInt(CodeConstants.EMIGENG_PERMISSION));
				String floorIds = getEngProFloor();
				Page   page     = getEnterListByUser(virName, Integer.parseInt(userId), floorIds, pageSize, pageNo, 2, isHisList, 7);
				return page;
			}
		}
		Page page = getEnterListByUser(virName, Integer.parseInt(userId), "", pageSize, pageNo, 2, isHisList, 8);
		return page;
	}


	@Override
	public EnterPcOutPutDto getEnterInfoByPC(int enterId) {
		if (enterpriseDao.exists(enterId)) {
			EnterpriseInfo enterInfo = enterpriseDao.get(enterId);
			if (enterInfo != null) {
				FileUploadUtils fileUploadUtils = new FileUploadUtils();
				fileUploadUtils.init();
				String businesUrl = "";
				if (StringUtils.isNotEmpty(enterInfo.getBusinessImageUrl())) {
					businesUrl = fileUploadUtils.fullVisitPath(enterInfo.getBusinessImageUrl());
				}
				String attorneyUrl = "";
				if (StringUtils.isNotEmpty(enterInfo.getPowerAttorneyImageUrl())) {
					attorneyUrl = fileUploadUtils.fullVisitPath(enterInfo.getPowerAttorneyImageUrl());
				}
				String faceUrl = "";
				if (StringUtils.isNotEmpty(enterInfo.getPowerFaceImageUrl())) {
					faceUrl = fileUploadUtils.fullVisitPath(enterInfo.getPowerFaceImageUrl());
				}
				String nationUrl = "";
				if (StringUtils.isNotEmpty(enterInfo.getPowerNationImageUrl())) {
					nationUrl = fileUploadUtils.fullVisitPath(enterInfo.getPowerNationImageUrl());
				}

				EnterPcOutPutDto dto = new EnterPcOutPutDto(enterInfo.getId(), enterInfo.getRemanName1()
						, enterInfo.getRemanTel1(), enterInfo.getRemanEmail1(), enterInfo.getIsPushPower1()
						, enterInfo.getIsReleasePower1(), enterInfo.getRemanName2(), enterInfo.getRemanTel2()
						, enterInfo.getRemanEmail2(), enterInfo.getIsPushPower2()
						, enterInfo.getIsReleasePower2(), enterInfo.getIsWechat(), enterInfo.getIsMessage()
						, enterInfo.getIsEmail()
						, businesUrl, attorneyUrl
						, faceUrl, nationUrl
						, enterInfo.getOtherRecord());
				return dto;
			}
		}
		return null;
	}


	/**
	 *
	 */
	@Async
	public String sendWechatByOk(EnterpriseInfo enterInfo, String wxUserId)
			throws Exception {
		String templateId = enterEvaluateTempleteId;
		if (StringUtils.isNotEmpty(templateId)) {
			Map<String, String> paramMap = new HashMap<String, String>();
			boolean             bool     = scWxuserManager.exists(Integer.parseInt(wxUserId));
			if (bool) {
				WxUser wxUser = scWxuserManager.get(Integer.parseInt(wxUserId));
				paramMap.put("developId", wxUser.getDevelopId());
				paramMap.put("openId", wxUser.getOpenId());
				paramMap.put("templateId", templateId);
				String url = hostUrl + wxEnterEvaluateUrl.replace("@id", enterInfo.getId().toString());
				paramMap.put("url", url);
				paramMap.put("first", "您的企业入驻已成功办理");
				paramMap.put("keyword1", enterInfo.getEnterNumber() == null ? "" : enterInfo.getEnterNumber());//订单号
				String floorAndRoom = getFloorAndRooms(enterInfo);
				if (StringUtils.isNotEmpty(floorAndRoom)) {
					floorAndRoom = floorAndRoom.substring(0, floorAndRoom.length() - 1);
				}
				paramMap.put("keyword2", "入驻地址是" + floorAndRoom);//订单内容
				paramMap.put("keyword3", DateHelper.formatDate(new Date(), DateHelper.DATE_STRING));//完成时间
				paramMap.put("remark", "请您为此次的入驻流程进行评价");
				weChatApiManager.sendTemplateWithOpenId(wxUser.getDevelopId(), templateId, url, Integer.parseInt(wxUserId), paramMap);
			}
		}
		return null;
	}


	@Transactional
	public String setEvaluate(String enterId, String evaluate)
			throws Exception {
		EnterpriseInfo enterInfo = enterpriseDao.get(Integer.parseInt(enterId));
		if (enterInfo != null) {
			enterInfo.setEvaluate(evaluate);
			enterpriseDao.updateObj(enterInfo);
		}
		return null;
	}


	@Override
	public EnterEvaluateDto getEnterEvaluateInfo(String enterId, List<Element> eleList) throws Exception {
		EnterpriseInfo enterInfo = enterpriseDao.get(Integer.parseInt(enterId));
		String         orgId     = enterInfo.getOrgId();
		String         orgName   = "";
		if (StringUtils.isNotBlank(orgId)) {
			TbOrganization orgInfo = organizationDao.getOrganizationById(Integer.parseInt(orgId));
			orgName = orgInfo.getName();
		}

		String floorAndRoom = getFloorAndRooms(enterInfo);
		if (StringUtils.isNotEmpty(floorAndRoom)) {
			floorAndRoom = floorAndRoom.substring(0, floorAndRoom.length() - 1);
		}
		String virAddress = orgName + floorAndRoom;
		String rePower1   = "";
		if (enterInfo.getIsPushPower1() == 1 && enterInfo.getIsReleasePower1() == 1) {
			rePower1 = "账单推送、物品放行";
		} else if (enterInfo.getIsPushPower1() == 1) {
			rePower1 = "账单推送";
		} else if (enterInfo.getIsReleasePower1() == 1) {
			rePower1 = "物品放行";
		}
		String rePower2 = "";
		if (enterInfo.getIsPushPower2() == 1 && enterInfo.getIsReleasePower2() == 1) {
			rePower2 = "账单推送、物品放行";
		} else if (enterInfo.getIsPushPower2() == 1) {
			rePower2 = "账单推送";
		} else if (enterInfo.getIsReleasePower2() == 1) {
			rePower2 = "物品放行";
		}
		String pushWay = "";
		if (enterInfo.getIsEmail() == 1 && enterInfo.getIsWechat() == 1 && enterInfo.getIsMessage() == 1) {
			pushWay = "邮件推送、微信推送、短信推送";
		} else if (enterInfo.getIsEmail() == 1 && enterInfo.getIsMessage() == 1) {
			pushWay = "邮件推送、短信推送";
		} else if (enterInfo.getIsEmail() == 1 && enterInfo.getIsWechat() == 1) {
			pushWay = "邮件推送、微信推送";
		} else if (enterInfo.getIsWechat() == 1 && enterInfo.getIsMessage() == 1) {
			pushWay = "微信推送、短信推送";
		} else if (enterInfo.getIsMessage() == 1) {
			pushWay = "短信推送";
		} else if (enterInfo.getIsWechat() == 1) {
			pushWay = "微信推送";
		} else if (enterInfo.getIsEmail() == 1) {
			pushWay = "邮件推送";
		}
		String evaluate   = "";
		String isEvaluate = "2";//未评价
		if (StringUtils.isNotEmpty(enterInfo.getEvaluate())) {
			if (eleList != null) {
				for (int i = 0; i < eleList.size(); i++) {
					Element ele = eleList.get(i);
					if (ele.getItemcode().equals(enterInfo.getEvaluate())) {
						evaluate = ele.getItemname();
					}
				}
			}
			isEvaluate = "1";//已评价
		}

		EnterEvaluateDto dto = new EnterEvaluateDto(enterInfo.getId()
				, enterInfo.getEnterNumber(), virAddress, enterInfo.getVirName()
				, enterInfo.getApplyName(), enterInfo.getApplyTel(), enterInfo.getStatus()
				, enterInfo.getRemanName1(), enterInfo.getRemanName2(), enterInfo.getRemanTel1()
				, enterInfo.getRemanTel2(), enterInfo.getRemanEmail1(), enterInfo.getRemanEmail2()
				, rePower1, rePower2, pushWay
				, evaluate, isEvaluate);
		return dto;
	}


	@Override
	public EnterEvaluateDto getEnterEvaluateInfo(String enterId, String type) throws Exception {
		EnterpriseInfo   enterInfo = enterpriseDao.get(Integer.parseInt(enterId));
		EnterEvaluateDto dto       = new EnterEvaluateDto();
		if (enterInfo != null) {
			dto.setId(Integer.parseInt(enterId));//企业待处理ID
			dto.setVirName(enterInfo.getVirName());//企业名称

			TbBuild tbBuild = (TbBuild) propertyManager.getTbBuildById(Integer.parseInt(enterInfo.getOrgId()));
			dto.setBuildName(tbBuild.getName());//入驻楼宇

			String floorAndRooms = getFloorAndRooms(enterInfo);//楼层房间拼接
			dto.setFloorAndRooms(floorAndRooms);
			dto.setFloors(enterInfo.getFloorNames());//楼层
			dto.setRooms(enterInfo.getRoomNames());//房号
			dto.setApplyName(enterInfo.getApplyName());//申请人
			dto.setApplyTel(enterInfo.getApplyTel());//申请人电话
			dto.setCreateTimeStr(enterInfo.getCreateTime());//申请时间
			dto.setCreateTime(DateHelper.toDateTimeString(enterInfo.getCreateTime()));//申请时间格式化后

			dto.setStatus(enterInfo.getStatus());//状态
			dto.setEnterNumber(enterInfo.getEnterNumber());//单号

			//签约时间
			dto.setSigningTime(enterInfo.getSigningTime());
			//合同到期时间
			dto.setContExpireTime(enterInfo.getContExpireTime());
			dto.setEmail(enterInfo.getEmail());
			dto.setAddress(enterInfo.getAddress());

			List<EnterpriseAudit> auditList = enterpriseAuditDao.getEnterAuditList(type, enterInfo.getId());//2代表企业迁出
			if (auditList != null && auditList.size() > 0) {
				EnterpriseAudit audit = auditList.get(0);
				dto.setOpinion(audit.getContent());//审核意见
				dto.setOpinionTimeStr(audit.getCreateTime());//审核时间
				dto.setOpinionTime(DateHelper.toDateTimeString(audit.getCreateTime()));//审核时间格式化后
				User user = appFunctionManager.getUserById(audit.getCreator());
				if (null != user) {
					dto.setOpinionUser(user.getFullName());//审核人
				}
			}
			dto.setFloorAndRooms(getFloorAndRooms(enterInfo));
		}
		return dto;
	}

	@Override
	public List<Map<String, Object>> getPower(int sysCode) throws Exception {
		return enterpriseDao.getPower(sysCode);
	}

	@Override
	public VirArchModel uploadFile(InputStream stream, String fileExt, String fileName, String type, String orgId) {
		FileUploadUtils fileUploadUtils = new FileUploadUtils();
		fileUploadUtils.init();
		String url = fileUploadUtils.uploadFile(stream, fileExt);
//		String coverUrl = fileUploadUtils.fullVisitPath(url);

		VirArchModel virArchModel = new VirArchModel();
		virArchModel.setType(Integer.parseInt(type));
		virArchModel.setFileName(fileName);
		virArchModel.setFileUrl(url);
		virArchModel.setCreateTime(new Date());
		virArchModel.setIsEnabled("1");
		virArchModel.setOrgId(Integer.parseInt(orgId));
		return virArchModelDao.save(virArchModel);
	}

	@Override
	public List<Map<String, Object>> getFileList(String type, String orgId, String fileIds) {
		List<Map<String, Object>> list = enterpriseDao.getFileList(type, orgId, fileIds);
		return list;
	}

	@Override
	public Page getEnterList(Map map, int pageNo, int pageSize) throws Exception {

		Page         page = enterpriseDao.getEnterList(map, pageNo, pageSize);
		List<Object> list = page.getItems();
		for (int i = 0; i < list.size(); i++) {
			Map<Object, Object> obj     = (Map<Object, Object>) list.get(i);
			int                 entId   = Integer.parseInt(obj.get("id").toString());
			EnterpriseInfo      entInfo = enterpriseDao.get(entId);
			if (null != entInfo) {
				String floorAndRooms = getFloorAndRooms(entInfo);
				obj.put("floorAndRooms", floorAndRooms);
			}
		}
		return page;
	}

	@Override
	public void optionEnterpriseInfo(EnterpriseInfo enterpriseInfo) {
		if (enterpriseInfo.getStatus() == "2") {
			//审核通过,插入新的企业信息
			VirtualArchitecture virtualArchitecture = new VirtualArchitecture();

		}
		enterpriseDao.save(enterpriseInfo);
	}

	@Override
	public Integer getEnterprisePendingNum(int state, String orgIds) {
		return enterpriseDao.getEnterprisePendingNum(state, orgIds);
	}
}
