package com.palmnest.webapp.controller.api;

import com.alibaba.fastjson.JSON;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.PushMessageHelper;
import com.palmnest.application.dto.CommonDto;
import com.palmnest.application.dto.output.EnterEvaluateDto;
import com.palmnest.application.dto.output.WatermenterDto;
import com.palmnest.model.EnterpriseAudit;
import com.palmnest.model.EnterpriseInfo;
import com.palmnest.model.User;
import com.palmnest.model.WatermeterInfo;
import com.palmnest.model.emig.BillOperationRecodes;
import com.palmnest.model.emig.EmigrationSettle;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.repair.RepairBillService;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业入驻app端控制器
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping(value = "/api/enter/*")
public class ApiEnterpriseController extends BaseFormController {


	@Autowired
	private EnterpriseManager           enterpriseManager;
	@Autowired
	private WatermeterManager           watermeterManager;
	@Autowired
	private UserManager                 userManager;
	@Autowired
	private EnterpriseAuditManager      enterpriseAuditManager;
	@Autowired
	private BaseRedisService            baseRedisService;
	@Autowired
	private ElementGroupManager         elementGroupManager;
	@Autowired
	private RepairBillService           repairBillService;
	@Autowired
	private OrganizationManager         organizationManager;
	@Autowired
	private EmigrationManager           emigrationManager;
	@Autowired
	private VirtUserManager             virtUserManager;
	@Autowired
	private ScWxuserManager             scWxuserManager;
	@Autowired
	private VirtualArchManager          virtualArchManager;
	@Autowired
	private BillOperationRecodesManager billOperationRecodesManager;
	@Autowired
	private WeChatApiManager            weChatApiManager;

	/**
	 * 获取企业入驻待处理列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getEnterpriseList")
	@ResponseBody
	public AppResultDto getEnterpriseList(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		Map<String, Object> params   = new HashMap<String, Object>();
		User                user     = userManager.getUserByUsername2(userName);
		int                 pageSize = 20;
		if (StringUtils.isNotEmpty(request.getParameter("pageSize"))) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		int pageNo = 1;
		if (StringUtils.isNotEmpty(request.getParameter("pageNo"))) {
			pageNo = Integer.parseInt(request.getParameter("pageNo"));
		}
		String virName = request.getParameter("virName");
		if (StringUtils.isNotEmpty(virName)) {
			virName = virName.trim();
			params.put("virName", virName);
		}
		String isHisList = request.getParameter("isHisList");
		if (StringUtils.isNotBlank(isHisList)) {
			params.put("isHisList", isHisList);
		}
		//企业入驻
		String type = request.getParameter("type");
		if (StringUtils.isNotBlank(type)) {
			params.put("type", type);
		}

		try {
			Page page = new Page();

			String orgId = getUserManageOrgIds(user);
			if (StringUtils.isNotBlank(orgId)) {
				params.put("orgId", orgId);
			}
			//要根据usertype去过滤   如果是项目管理员及以上权限则查看所有  否则只需查看自己操作过的记录
			if (user.getUserType() > Constants.USER_TYPE_PROJECT_MANAGE) {
				params.put("userId", user.getId());
			}
			page = enterpriseManager.getEnterList(params, pageNo, pageSize);
			return AppResultUtil.createSuccesDto(page);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业入驻待处理列表界面失败：" + e.getMessage());
		}
	}

	/**
	 * 获取企业入驻详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getEnterpriseInfo")
	@ResponseBody
	public AppResultDto getEnterpriseInfo(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user   = userManager.getUserByUsername2(userName);
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		int                 enterId = Integer.parseInt(request.getParameter("enterId"));
		String              type    = request.getParameter("type");
		Map<String, Object> map     = new HashMap<String, Object>();
		try {
//			EnterpriseInfo enterInfo=enterpriseManager.get(enterId);
			EnterEvaluateDto enterInfo = enterpriseManager.getEnterEvaluateInfo(enterId + "", type);
			if (enterInfo != null) {
//				EnterpriseDto  dto=enterpriseManager.getEnterInfo(enterId,userId);
				return AppResultUtil.createSuccesDto(enterInfo);
			} else {
				return AppResultUtil.createErrorDto("100", "获取企业入驻单据失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业入驻详情失败：" + e.getMessage());
		}
	}

	/**
	 * 提交水电表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitWater")
	@ResponseBody
	public AppResultDto submitWater(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String userName = baseRedisService.get(request.getHeader("token"));
			if (userName == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
			}
			User                 user        = userManager.getUserByUsername2(userName);
			String               userId      = String.valueOf(user.getId());
			String               code        = "";
			String               enterId     = request.getParameter("enterId");
			String               wateDtoList = request.getParameter("wateDtoList");
			List<WatermenterDto> wateList    = new ArrayList<WatermenterDto>();
			if (StringUtils.isNotEmpty(wateDtoList)) {
				wateList = JSON.parseArray(wateDtoList, WatermenterDto.class);
				code = watermeterManager.saveWaterInfo(wateList, Integer.parseInt(enterId), Integer.parseInt(userId));
			}
			if ("200".equals(code)) {
				AppResultDto dto = AppResultUtil.createSuccesDto();
				if ("200".equals(dto.getCode())) {
					//推送水电表信息给微信用户
//					String str=watermeterManager.sendWechat(enterId,wateList);//推送给微信发起人
//					log.error("推送给微信发起人:"+str);
					watermeterManager.sendAppMessage(enterId);//推送给跟进客服
					EnterpriseInfo info     = enterpriseManager.get(Integer.parseInt(enterId));
					String         describe = "";
					Integer        type     = 0;
					if (info != null) {
						if ("1".equals(info.getState())) {
							type = CodeConstants.ENTER;
							describe = "提交企业入驻水电表信息";
						} else if ("2".equals(info.getState())) {
							type = CodeConstants.EMIG;
							describe = "提交企业迁出水电表信息";
						}
					}
					billOperationRecodesManager.saveRecode(Long.parseLong(enterId), type, CodeConstants.SUBMIT_WATER, Long.parseLong(userId), "提交水电表", describe);
				}
				return dto;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "提交水电表信息失败：" + e.getMessage());
		}
		return AppResultUtil.createErrorDto("100", "提交水电表信息失败");


	}

	/**
	 * 根据企业入驻单获取水电表信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getWaterList")
	@ResponseBody
	public AppResultDto getWaterList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		Map<String, Object>  map       = new HashMap<String, Object>();
		List<WatermenterDto> waterList = new ArrayList<WatermenterDto>();
		int                  sourseId  = Integer.parseInt(request.getParameter("enterId"));//获取来源单据ID(企业入驻单据ID)
		try {
			//根据企业入驻单据ID查询水电表信息，1代表企业入驻，2代表企业迁出，
			//floorId,roomId为空代表直接查询这个企业入驻单据下所有的水电表信息,如果有值代表查单个的楼层或者房间的水电表信息
			EnterpriseInfo enterInfo = enterpriseManager.get(sourseId);
			if (enterInfo != null && StringUtils.isNotEmpty(enterInfo.getState())) {
				int state = Integer.parseInt(enterInfo.getState());
				waterList = watermeterManager.getWatermeterList(sourseId, state, "", "");
			}
			map.put("wateList", waterList);
			TbOrganization orgInfo = organizationManager.getOrganizationById(Integer.parseInt(enterInfo.getOrgId()));
			map.put("orgName", orgInfo.getName());
			map.put("floorAndRoom", enterpriseManager.getFloorAndRooms(enterInfo));
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业入驻历史列表失败：" + e.getMessage());
		}
	}

	/**
	 * 上传图片，返回地址
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "uploadImage")
	@ResponseBody
	public AppResultDto uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			data = enterpriseManager.uploadImage(request);
			return AppResultUtil.createSuccesDto(data);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "上传图片失败：" + e.getMessage());
		}


	}

	/**
	 * 获取客服人员
	 * 获取管理该楼层下的客服人员(有入驻工程分配权限的)
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getCustomerService")
	@ResponseBody
	public AppResultDto getCustomerService(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		Map<String, Object>       map         = new HashMap<String, Object>();
		String                    enterId     = request.getParameter("enterId");
		String                    type        = request.getParameter("type");
		List<Map<String, Object>> list        = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> custlist    = new ArrayList<Map<String, Object>>();
		EnterpriseInfo            enterInfo   = enterpriseManager.get(Integer.parseInt(enterId));
		String                    floorId     = enterInfo.getFloorIds();
		List<CommonDto>           serviceDto  = new ArrayList<CommonDto>();
		List<CommonDto>           customerDto = new ArrayList<CommonDto>();
		try {
			if ("1".equals(enterInfo.getState())) {//企业入驻
				if ("0".equals(type)) {
					list = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));//查询客服主管
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> cusMap = list.get(i);
						serviceDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
					custlist = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));//查询客服
					for (int i = 0; i < custlist.size(); i++) {
						Map<String, Object> cusMap = custlist.get(i);
						customerDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				} else if ("1".equals(type)) {
					list = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));//查询客服主管
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> cusMap = list.get(i);
						serviceDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				} else if ("2".equals(type)) {
					custlist = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));//查询客服
					for (int i = 0; i < custlist.size(); i++) {
						Map<String, Object> cusMap = custlist.get(i);
						customerDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				}
			} else if ("2".equals(enterInfo.getState())) {//企业迁出
				if ("0".equals(type)) {
					list = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));//查询客服主管
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> cusMap = list.get(i);
						serviceDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
					custlist = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));//查询客服
					for (int i = 0; i < custlist.size(); i++) {
						Map<String, Object> cusMap = custlist.get(i);
						customerDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				} else if ("1".equals(type)) {
					list = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));//查询客服主管
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> cusMap = list.get(i);
						serviceDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				} else if ("2".equals(type)) {
					custlist = enterpriseManager.getPower(floorId, Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));//查询客服
					for (int i = 0; i < custlist.size(); i++) {
						Map<String, Object> cusMap = custlist.get(i);
						customerDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
					}
				}
			}

			map.put("custlist", customerDto);
			map.put("list", serviceDto);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败：" + e.getMessage());
		}

	}


	/**
	 * 企业入驻待处理单审核
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value = "optionEnterpriseOrder")
	@ResponseBody
	public AppResultDto optionEnterpriseOrder(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user      = userManager.getUserByUsername2(userName);
		String enterId   = request.getParameter("enterId");
		String userId    = user.getId() + "";//审核人
		String optionMsg = request.getParameter("optionMsg");//审核信息
		String status    = request.getParameter("status");//2-通过 3-不通过

		EnterpriseInfo enterpriseInfo = enterpriseManager.get(Integer.parseInt(enterId));
		enterpriseInfo.setModifier(Integer.parseInt(userId));
		enterpriseInfo.setRemark(optionMsg);
		enterpriseInfo.setStatus(status);

		try {
			enterpriseManager.optionEnterpriseInfo(enterpriseInfo);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业入驻详情失败：" + e.getMessage());
		}
	}


	/**
	 * 企业 入驻/迁出审核 操作
	 *
	 * @param request
	 * @param response
	 * @return
	 */
//	@RequestMapping(value="setEnterReason")
	@RequestMapping(value = "optionEnterpriseOrder")
	@ResponseBody
	public AppResultDto setEnterReason(HttpServletRequest request, HttpServletResponse response) {
		String reason = request.getParameter("optionMsg");//审核信息
//		String userId=request.getParameter("userId");
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user      = userManager.getUserByUsername2(userName);
		String userId    = String.valueOf(user.getId());
		String enterId   = request.getParameter("enterId");
		String resonType = request.getParameter("status");//2-通过 3-拒绝
		String type      = request.getParameter("type");//1入驻 2迁出

		String signingTime    = request.getParameter("signingTime");//签约日期
		String contExpireTime = request.getParameter("contExpireTime");//合同到期日期

		EnterpriseAudit audit = new EnterpriseAudit();
		try {
			EnterpriseInfo enterInfo     = enterpriseManager.get(Integer.parseInt(enterId));
			int            operationType = 0;
			if ("3".equals(resonType)) {//拒绝
				operationType = CodeConstants.BREAK;
			} else if ("2".equals(resonType)) {//通过
				operationType = CodeConstants.PASS;
			}
			BillOperationRecodes billRecodes = billOperationRecodesManager.getRecodeBySourId(Long.parseLong(enterInfo.getId().toString()), Integer.parseInt(enterInfo.getState()), operationType);
			if (billRecodes != null && billRecodes.getId() != null) {
				return AppResultUtil.createCommonDto(CodeConstants.USEED_CODE, "该单据已有用户操作.", enterInfo.getId().toString());
			}

			List<VirtualArchitecture> virList = virtualArchManager.getVirByRoomId(enterInfo.getRoomIds());
			if (virList != null && virList.size() > 0 && "1".equals(enterInfo.getState())) {
				return AppResultUtil.createErrorDto(AppConstants.BILL_EXISTENT, "单据已被操作，不允许再操作");
			}
			audit = enterpriseManager.saveEnterAudit(reason, userId, enterId, resonType, type, signingTime, contExpireTime);
			AppResultDto dto = AppResultUtil.createSuccesDto(audit);
			try {
				if (audit != null) {
					if ("200".equals(dto.getCode())) {
						String virName      = enterInfo.getVirName();
						String floorAndRoom = enterpriseManager.getFloorAndRooms(enterInfo);
						if (StringUtils.isNotEmpty(floorAndRoom)) {
							floorAndRoom = floorAndRoom.substring(0, floorAndRoom.length() - 1);
						}
						int    type2     = 0;
						int    code      = 0;
						String operation = "";
						String describe  = "";

						String content = "";

						String enter = "enter";
						if ("1".equals(enterInfo.getState())) {//企业入驻
							type2 = CodeConstants.ENTER;
							if ("3".equals(resonType)) {//拒绝
								code = CodeConstants.BREAK;
								operation = "拒绝";
								describe = "该企业入驻单据被拒绝";
								content = "抱歉，你的" + virName + "入驻申请未通过，未通过原因为" + audit.getContent() + "！";
							} else if ("2".equals(resonType)) {//通过
								code = CodeConstants.PASS;
								operation = "通过";
								describe = "该企业入驻单据被通过";
								content = "恭喜，你的" + virName + "入驻申请已经通过啦！";
							}
						} else if ("2".equals(enterInfo.getState())) {//企业迁出
							type2 = CodeConstants.EMIG;
							enter = "emig";
							if ("3".equals(resonType)) {//拒绝
								code = CodeConstants.BREAK;
								operation = "拒绝";
								describe = "该企业迁出被拒绝";
								content = "抱歉，你的" + virName + "迁出申请未通过，未通过原因为" + audit.getContent() + "！";
							} else if ("2".equals(resonType)) {//通过
								code = CodeConstants.PASS;
								operation = "通过";
								describe = "该企业迁出单据被通过";
								content = "你好，你的" + virName + "迁出申请已通过审核！";
							}
						}

						String host           = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
						String wxVirDetailUrl = PropertiesKit.readPropertiesValue("wxVirDetailUrl", "wechat.properties");
						String url            = host + wxVirDetailUrl.replaceAll("@id", enterId).replaceAll("enter", enter);

						billOperationRecodesManager.saveRecode(Long.parseLong(enterId), type2, code, Long.parseLong(userId), operation, describe);
						String wxUserId = String.valueOf(enterInfo.getCreator());

						if ("2".equals(enterInfo.getState()) && "2".equals(enterInfo.getEmigNewWay())) {
							//如果是app端发起的迁出申请 审核成功后进行app推送
							List<User> users       = new ArrayList<User>();
							User       creatorUser = userManager.getUser(enterInfo.getCreator() + "");
							users.add(creatorUser);
							//如果是app端发起的迁出申请 审核成功后进行app推送
							PushMessageHelper helper=new PushMessageHelper();
							helper.pushMessage(Long.parseLong(enterId), CodeConstants.EMIG_PUSH_CODE, users, "企业迁出审核结果通知", content);
						} else {
							content += "<a href=\"" + url + "\">查看详情>></a>";
							WxUser wxUser = scWxuserManager.getScWxuserByWxUserId(enterInfo.getCreator());
							if (wxUser != null) {
								//微信客服消息推送
								weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), Integer.parseInt(wxUserId), content);
							}
						}
					/*if("2".equals(enterInfo.getEmigNewWay())){//如果是app端发起的，需要给企业负责人发消息
						List<VirtUserInfo> virUserList=virtUserManager.getVirtUserByVirtId(enterInfo.getVirId());
						if(virUserList!=null&&virUserList.size()>0){
							for(int i=0;i<virUserList.size();i++){
								VirtUserInfo virUser=virUserList.get(i);
								int virUserId=virUser.getUserId();
								WxUser wxUser=scWxuserManager.getScWxuserByUserId(virUserId);
								if(wxUser!=null){
									wxUserId=wxUserId+wxUser.getId()+",";
								}
							}
						}
					}else{
						wxUserId=String.valueOf(enterInfo.getCreator());
					}*/
//					enterpriseManager.sendWechat(virName, floorAndRoom, reason, Integer.parseInt(enterInfo.getState()),Integer.parseInt(resonType), wxUserId);
					/*enterInfo=enterpriseManager.get(Integer.parseInt(enterId));
					if("1".equals(enterInfo.getState())){//企业入驻
						if(StringUtils.isNotBlank(enterInfo.getStatus())){//如果通过了，推送微信模板给发起人推送评价模板
							if("3".equals(enterInfo.getStatus())){
								enterpriseManager.sendWechatByOk(enterInfo,wxUserId);
							}
						}
					}*/
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("消息推送失败!" + e.getMessage());
			}
			return dto;
//			return AppResultUtil.createErrorDto("100","操作失败");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败" + e.getMessage());
		}
	}

	/**
	 * 企业入驻通过或拒绝成功后推送消息给微信发起人
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "senRsultMessage")
	@ResponseBody
	public AppResultDto senRsultMessage(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String           enterId   = request.getParameter("enterId");
		String           resonType = request.getParameter("resonType");//1通过0拒绝
		String           wxUserId  = "";
		SimpleDateFormat sdf       = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String           result    = "";
		try {
			if (StringUtils.isNotEmpty(enterId)) {
				EnterpriseInfo enterInfo = enterpriseManager.get(Integer.parseInt(enterId));
				if (enterInfo != null) {
					wxUserId = String.valueOf(enterInfo.getCreator());
					if (StringUtils.isNotEmpty(wxUserId)) {
						String floorAndRoom = enterpriseManager.getFloorAndRooms(enterInfo);
						String virName      = enterInfo.getVirName();
						String time         = sdf.format(enterInfo.getCreateTime());
						if ("1".equals(resonType)) {
//							result=enterpriseManager.sendWechat(wxUserId, "成功", floorAndRoom, virName, time, "成功");
						} else {
//							result=enterpriseManager.sendWechat(wxUserId, "拒绝", floorAndRoom, virName, time, "拒绝");
						}
						if ("success".equals(result)) {
							return AppResultUtil.createSuccesDto();
						}

					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败" + e.getMessage());
		}

		return AppResultUtil.createSuccesDto("没有要推送的数据", null);
	}

	/**
	 * 判断该单据的按钮是是否允许操作
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "isPowerButton")
	@ResponseBody
	public AppResultDto isPowerButton(HttpServletRequest request, HttpServletResponse response) {
//		String userId=request.getParameter("userId");
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user    = userManager.getUserByUsername2(userName);
		String userId  = String.valueOf(user.getId());
		String enterId = request.getParameter("enterId");
		String type    = request.getParameter("type");//1通过0拒绝

		try {
			EnterpriseInfo enter = enterpriseManager.get(Integer.parseInt(enterId));
			if ("1".equals(enter.getState())) {
				if ("1".equals(type)) {//当点击通过按钮的时候判断按钮是否允许操作()
					String isCustService = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
					if ("1".equals(isCustService)) {//有客服权限

						if ("".equals(enter.getCustomerService())) {
							return AppResultUtil.createCommonDto("100", "跟进客服不允许为空.", "2");
						}
						if ("".equals(enter.getEngPerson())) {
							return AppResultUtil.createCommonDto("100", "跟进工程人员不允许为空.", "2");
						}
						List<WatermeterInfo> wateList = watermeterManager.getWatermeterLists(enter.getId(), 1, "", "");
						if (wateList == null || wateList.size() <= 0) {
							return AppResultUtil.createCommonDto("100", "水电表信息不允许为空.", "2");
						}
						if (!userId.equals(enter.getCustomerService())) {
							return AppResultUtil.createCommonDto("100", "您不是跟进客服，无法操作.", "2");
						}
						return AppResultUtil.createSuccesDto("1");//有权限
					} else {
						return AppResultUtil.createCommonDto("100", "没有分配客服权限.", "2");//没权限
					}
				} else {//当点击拒绝按钮的时候判断按钮是否允许操作
					String isCustService = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUS_PERMISSION));
					String isSupervisor  = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.ENTERCUSMANAGE_PERMISSION));
					if ("1".equals(isCustService) || "".equals(isSupervisor)) {//有客服权限
						return AppResultUtil.createSuccesDto("1");
					} else {
						return AppResultUtil.createCommonDto("100", "您没有该操作的权限.", "2");
					}
				}
			} else if ("2".equals(enter.getState())) {
				if ("1".equals(type)) {//当点击通过按钮的时候判断按钮是否允许操作()
					String isCustService = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));
					if ("1".equals(isCustService)) {//有客服权限

						if ("".equals(enter.getCustomerService())) {
							return AppResultUtil.createCommonDto("100", "跟进客服不允许为空.", "2");
						}
						if ("".equals(enter.getEngPerson())) {
							return AppResultUtil.createCommonDto("100", "跟进工程人员不允许为空.", "2");
						}
						List<WatermeterInfo> wateList = watermeterManager.getWatermeterLists(enter.getId(), 2, "", "");
						if (wateList == null || wateList.size() <= 0) {
							return AppResultUtil.createCommonDto("100", "水电表信息不允许为空.", "2");
						}
						EmigrationSettle esInfo = emigrationManager.getEmigrationSettle(enter.getId());
						if (esInfo == null) {
							return AppResultUtil.createCommonDto("100", "结算表不允许为空.", "2");
						}
						if (!userId.equals(enter.getCustomerService())) {
							return AppResultUtil.createCommonDto("100", "您不是跟进客服，无法操作.", "2");
						}
						return AppResultUtil.createSuccesDto("1");//有权限
					} else {
						return AppResultUtil.createCommonDto("100", "没有分配客服权限.", "2");//没权限
					}
				} else {//当点击拒绝按钮的时候判断按钮是否允许操作
					String isCustService = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGCUS_PERMISSION));
					String isSupervisor  = enterpriseManager.isHavePower(userId, Integer.parseInt(CodeConstants.EMIGCUSMANAGE_PERMISSION));
					if ("1".equals(isCustService) || "".equals(isSupervisor)) {//有客服权限
						return AppResultUtil.createSuccesDto("1");
					} else {
						return AppResultUtil.createCommonDto("100", "您没有该操作的权限.", "2");
					}
				}
			}
			return AppResultUtil.createSuccesDto("0");//无权限

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败：" + e.getMessage());
		}

	}


	/**
	 * @param request
	 * @return 查找对应维修类型下的人员
	 */
	@RequestMapping(value = "/getRepairTypeUser")
	@ResponseBody
	public AppResultDto getRepairTypeUser(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String                    enterId       = request.getParameter("enterId");
		List<Map<String, Object>> engPersonList = new ArrayList<Map<String, Object>>();
		List<CommonDto>           engPsersonDto = new ArrayList<CommonDto>();
		try {
			EnterpriseInfo enterInfo = enterpriseManager.get(Integer.parseInt(enterId));
			if (enterInfo != null) {
				String floorIds = enterInfo.getFloorIds();
				if ("1".equals(enterInfo.getState())) {//企业入驻
					engPersonList = enterpriseManager.getPower(Integer.parseInt(CodeConstants.ENTERENG_PERMISSION));
				} else if ("2".equals(enterInfo.getState())) {//企业迁出
					engPersonList = enterpriseManager.getPower(Integer.parseInt(CodeConstants.EMIGENG_PERMISSION));
				}
				for (int i = 0; i < engPersonList.size(); i++) {
					Map<String, Object> cusMap = engPersonList.get(i);
					engPsersonDto.add(new CommonDto(Long.valueOf(cusMap.get("usId").toString()), cusMap.get("userName").toString()));
				}
			}
			return AppResultUtil.createSuccesDto(engPsersonDto);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取工程人员失败：" + e.getMessage());
		}

	}

	/**
	 * @param request
	 * @return 根据维修单编码获取维修列表
	 */
	@RequestMapping(value = "/getRepairNumberList")
	@ResponseBody
	public AppResultDto getRepairNumberList(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String enterId      = request.getParameter("enterId");
		String repairNumber = "";
		if (StringUtils.isNotEmpty(enterId)) {
			EnterpriseInfo enterInfo = enterpriseManager.get(Integer.parseInt(enterId));
			repairNumber = enterInfo.getRepairNumber();
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (StringUtils.isNotEmpty(repairNumber)) {
			try {
				list = enterpriseManager.getRepairNumberList(repairNumber);
				if (list != null && list.size() > 0) {
					return AppResultUtil.createSuccesDto(list);
				} else {
					return AppResultUtil.createSuccesDto("维修单为空", list);
				}

			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", "获取维修列表失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createSuccesDto("维修单为空", list);
	}


	/**
	 * @param request
	 * @return 修改维修单编码
	 */
	@RequestMapping(value = "/updateEnterRpairCode")
	@ResponseBody
	public AppResultDto updateEnterRpairCode(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user         = userManager.getUserByUsername2(userName);
		String repairNumber = request.getParameter("repairCode");
		String enterId      = request.getParameter("enterId");
		if (StringUtils.isNotEmpty(enterId)) {
			try {
				EnterpriseInfo info = enterpriseManager.get(Integer.parseInt(enterId));
				info.setRepairNumber(repairNumber);
				enterpriseManager.updateModel(info);
				int    type     = 0;
				String describe = "";
				if ("1".equals(info.getState())) {
					type = CodeConstants.ENTER;
					describe = "企业入驻发起维修单";
				} else if ("2".equals(info.getState())) {
					type = CodeConstants.EMIG;
					describe = "企业迁出发起维修单";
				}
				billOperationRecodesManager.saveRecode(Long.parseLong(enterId), type, CodeConstants.SUBMIT_REPIAR, Long.parseLong(user.getId().toString()), "发起维修单", describe);
				return AppResultUtil.createSuccesDto();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", " 修改企业入驻单的维修单编码失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createErrorDto("100", "修改企业入驻单的维修单编码失败");
	}

	/**
	 * @param request
	 * @return 修改客服及工程
	 */
	@RequestMapping(value = "/updateEnterPeson")
	@ResponseBody
	public AppResultDto updateEnterPeson(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User   user    = userManager.getUserByUsername2(userName);
		String type    = request.getParameter("type");
		String pesonId = request.getParameter("pesonId");
		String enterId = request.getParameter("enterId");
		if (StringUtils.isNotEmpty(enterId)) {
			try {
				String         userId = user.getId().toString();
				EnterpriseInfo info   = enterpriseManager.get(Integer.parseInt(enterId));
				if ("1".equals(type)) {//跟进客服
					BillOperationRecodes bill = billOperationRecodesManager.getRecodeBySourId(Long.parseLong(info.getId().toString()), Integer.parseInt(info.getState()), CodeConstants.SUBMIT_CUS);
					if (bill.getId() == null || userId.equals(info.getCustomerService())) {
						if (userId.equals(info.getCustomerService())) {
							User userInfo = userManager.get(Long.parseLong(pesonId));
							bill.setRemark(user.getUsername() + "将跟进客服改为：" + userInfo.getUsername());
							billOperationRecodesManager.updateModel(bill);
						}
						info.setCustomerService(pesonId);
						info.setStatus("1");
					} else {
						return AppResultUtil.createCommonDto(CodeConstants.USEED_CODE, "您无法操作该单据.", enterId);
					}

				} else if ("2".equals(type)) {//跟进工程人员
					if (StringUtils.isNotEmpty(info.getCustomerService())) {
						BillOperationRecodes bill = billOperationRecodesManager.getRecodeBySourId(Long.parseLong(info.getId().toString()), Integer.parseInt(info.getState()), CodeConstants.SUBMIT_ENG);
						if (bill.getId() == null || userId.equals(info.getEngPerson()) || userId.equals(info.getCustomerService())) {//跟进客服和跟进工程人员都可以修改跟进工程人员
							if (userId.equals(info.getEngPerson()) || userId.equals(info.getCustomerService())) {
								User userInfo = userManager.get(Long.parseLong(pesonId));
								bill.setRemark(user.getUsername() + "将跟进工程改为：" + userInfo.getUsername());
								billOperationRecodesManager.updateModel(bill);
							}
							info.setEngPerson(pesonId);
							info.setStatus("2");
						} else {
							return AppResultUtil.createCommonDto(CodeConstants.USEED_CODE, "您无法操作该单据.", enterId);
						}
					} else {
						return AppResultUtil.createErrorDto("100", "跟进客服不允许为空");
					}
				}
				enterpriseManager.updateModel(info);
				AppResultDto dto = AppResultUtil.createSuccesDto();
				if ("200".equals(dto.getCode())) {
					int    type1     = 0;
					int    code      = 0;
					String operation = "";
					String describe  = "";
					if ("1".equals(type)) {//跟进客服
						code = CodeConstants.SUBMIT_CUS;
						operation = "修改跟进客服";
						if ("1".equals(info.getState())) {
							type1 = CodeConstants.ENTER;
							describe = "企业入驻修改跟进客服";
						} else if ("2".equals(info.getState())) {
							type1 = CodeConstants.EMIG;
							describe = "企业迁出修改跟进客服";
						}
					} else if ("2".equals(type)) {//跟进工程
						code = CodeConstants.SUBMIT_ENG;
						operation = "修改跟进工程";
						if ("1".equals(info.getState())) {
							type1 = CodeConstants.ENTER;
							describe = "企业入驻修改跟进工程";
						} else if ("2".equals(info.getState())) {
							type1 = CodeConstants.EMIG;
							describe = "企业迁出修改跟进工程";
						}
					}

					billOperationRecodesManager.saveRecode(Long.parseLong(enterId), type1, code, Long.parseLong(user.getId().toString()), operation, describe);

					enterpriseManager.sendUpdateEnterMessage(info, pesonId);
				}
				return dto;
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", "修改企业入驻单的跟进客服或跟进工程人员失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createErrorDto("100", "修改企业入驻单的跟进客服或跟进工程人员失败");
	}


	/**
	 * 企业入驻提交水电表时入口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getWateSizeList")
	@ResponseBody
	public AppResultDto getWateSizeList(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String enterId = request.getParameter("enterId");
		try {
			if (StringUtils.isNotEmpty(enterId)) {
				EnterpriseInfo info    = enterpriseManager.get(Integer.parseInt(enterId));
				String         roomIds = info.getRoomIds();
				if (StringUtils.isNotEmpty(roomIds)) {
					AppResultDto dto = enterpriseManager.getWateSizeListByRooms(roomIds, info);
					return dto;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取水电表信息失败：" + e.getMessage());
		}
		return AppResultUtil.createErrorDto("100", "获取水电表信息失败");
	}

}
