package com.palmnest.webapp.controller.api;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.dto.CommonDto;
import com.palmnest.application.dto.input.EmigrationInputDto;
import com.palmnest.application.dto.output.EmigSettleOutPutDto;
import com.palmnest.application.dto.output.EmigSumIndexDto;
import com.palmnest.application.dto.output.EmigrationDto;
import com.palmnest.model.Element;
import com.palmnest.model.EnterpriseInfo;
import com.palmnest.model.User;
import com.palmnest.model.emig.EmigrationSettle;
import com.palmnest.model.property.TbBuild;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.redis.BaseRedisService;
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.ModelAttribute;
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.util.*;

/**
 * 企业迁出app端控制器
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping(value = "/api/emig/*")
public class ApiEmigrationController extends BaseFormController {


	@Autowired
	private BaseRedisService    baseRedisService;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private EnterpriseManager   enterpriseManager;
	@Autowired
	private EmigrationManager   emigrationManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private WatermeterManager   watermeterManager;
	@Autowired
	private VirtualArchManager  virtualArchManager;
	@Autowired
	private FloorInfoManager    floorInfoManager;

	/**
	 * 根据登录用户获取该用户负责的楼层下的企业列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getFloorVirList")
	@ResponseBody
	public AppResultDto getFloorVirList(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 orgId = request.getParameter("orgId");
		try {
			String isCustService = enterpriseManager.isHavePower(String.valueOf(user.getId()), 3000);
			if ("1".equals(isCustService)) {//有迁出工程分配权限的用户才有企业数据
				String floorIds = enterpriseManager.getPowerFloors(Integer.parseInt(String.valueOf(user.getId())), 3000, orgId);//查询客服负责的楼层
				//根据楼层获取该楼层下的企业
				AppResultDto dto = emigrationManager.getFloorVirList(floorIds);
				return dto;
			}
		} catch (Exception e) {
			return AppResultUtil.createErrorDto("100", "获取楼层企业失败:" + e.getMessage());
		}
		return AppResultUtil.createCommonDto("100", "没有权限", null);
	}

	/**
	 * 根据登录用户获取该用户负责的楼宇下的企业列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getBuildVirList")
	@ResponseBody
	public AppResultDto getBuildVirList(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 buildId = request.getParameter("buildId");
		String virName = request.getParameter("virName");
		try {
			AppResultDto dto = virtualArchManager.getVirListByBuildId(buildId, virName);
			return dto;
		} catch (Exception e) {
			return AppResultUtil.createErrorDto("100", "获取楼层企业失败:" + e.getMessage());
		}
	}

	/**
	 * 保存企业迁出
	 *
	 * @param enterInputDto
	 * @return
	 */
	@RequestMapping(value = "saveEmigration")
	@ResponseBody
	public AppResultDto saveEmigration(@ModelAttribute("emigInputDto") EmigrationInputDto emigInputDto, HttpServletRequest request, HttpServletResponse response) throws Exception {

		//校验该企业是否已经发起过迁出,如果有则拒绝再次请求
		boolean b = emigrationManager.checkHasUnhandleOrder(emigInputDto.getVirId());
		if (b) {
			return AppResultUtil.createErrorDto("100", "该企业已发起过迁出申请");
		}

		//根据传过来的企业ID，找到对应的企业，然后将企业中的值放到对应的企业迁出值中
		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());
		try {
			EnterpriseInfo enterInfo = emigrationManager.saveEnterInfo(emigInputDto, Integer.parseInt(userId), "2");
			if (enterInfo != null) {
				AppResultDto dto = AppResultUtil.createSuccesDto(enterInfo.getId());
				if ("200".equals(dto.getCode())) {
					enterpriseManager.sendMessageByCusService(enterInfo);
				}
				return dto;
			}
		} catch (Exception e) {
			log.error("保存企业迁出失败：" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "保存企业迁出失败：" + e.getMessage());
		}
		return AppResultUtil.createSuccesDto("没有权限", null);
	}

	/**
	 * 根据企业ID获取企业位置，负责人，楼栋信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getEmigInfoByVirId")
	@ResponseBody
	public AppResultDto getEmigInfoByVirId(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String virId = request.getParameter("virId");
		if (StringUtils.isNotEmpty(virId)) {
			try {
				Map<String, Object> map = emigrationManager.getEmigInfoByVirId(virId);
				return AppResultUtil.createSuccesDto(map);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", "获取企业相关信息失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createErrorDto("100", "传输的数据异常");
	}

	/**
	 * @param request
	 * @return 获取迁出原因
	 */
	@RequestMapping(value = "getEmigrationReason")
	@ResponseBody
	public AppResultDto getEmigrationReason() {
		List<Element> emigrationReason = elementGroupManager.getElementsByGroupName("emigrationReason");
		return AppResultUtil.createSuccesDto(elementGroupManager.convert(emigrationReason));
	}

	/**
	 * 获取迁出类型
	 *
	 * @return
	 */
	@RequestMapping(value = "getEmigrationType")
	@ResponseBody
	public AppResultDto getEmigrationType() {
		List<Element> emigrationType = elementGroupManager.getElementsByGroupName("emigrationType");
		return AppResultUtil.createSuccesDto(elementGroupManager.convert(emigrationType));
	}
//	/**
//	 * 获取企业迁出待处理列表
//	 * @return
//	 */
//	@RequestMapping(value="getEmigInfoIngList")
//	@ResponseBody
//	public AppResultDto getEmigInfoIngList(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);
//		
//		int pageSize=Integer.parseInt(request.getParameter("pageSize"));
//		int pageNo=Integer.parseInt(request.getParameter("pageNo"));
//		
//		String virName=request.getParameter("virName");
//		User userInfo=userManager.get(user.getId());
//		//如果该用户是没有权限的就返回空
//		//如果该用户有权限并且是客服主管的，显示全部数据（客服主管负责的楼层的全部数据）
//		//如果该用户有权限是客服、工程人员，显示分配给他的入驻单
//		if(userInfo==null){
//			return AppResultUtil.createErrorDto("100","获取用户失败");
//		}
//		try {
//			String isSupervisor=enterpriseManager.isHavePower(String.valueOf(user.getId()),3001);
//			String isCustService=enterpriseManager.isHavePower(String.valueOf(user.getId()),3002);
//			
//			if("1".equals(isSupervisor)){//如果有客服主管的权限，则显示他负责楼层的全部企业入驻待处理数据
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(String.valueOf(user.getId())),3001);//查询客服主管
//				Page page=enterpriseManager.getEnterListByUser(virName,0,Integer.parseInt(String.valueOf(user.getId())),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}
//			if("1".equals(isCustService)){//如果有客服的权限，则显示企业入驻选中他为跟进客服的待处理数据
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(String.valueOf(user.getId())),3002);//查询客服主管
//				Page page=enterpriseManager.getEnterListByUser(virName,1,Integer.parseInt(String.valueOf(user.getId())),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}
//			
//			String isProgramme=enterpriseManager.isHavePower(String.valueOf(user.getId()),3003);
//			if("1".equals(isProgramme)){
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(String.valueOf(user.getId())),3003);//查询客服主管
//				Page page=enterpriseManager.getEnterListByUser(virName,2,Integer.parseInt(String.valueOf(user.getId())),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}
//			return AppResultUtil.createSuccesDto();
//		} catch (Exception e) {
//			log.error(e.getMessage());
//			return AppResultUtil.createErrorDto("100","获取企业迁出待处理列表界面失败："+e.getMessage());
//		}
//	}
//	
//	/**
//	 * 获取企业迁出历史列表
//	 * @return
//	 */
//	@RequestMapping(value="getEmigInfoHisList")
//	@ResponseBody
//	public AppResultDto getEmigInfoHisList(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=String.valueOf(user.getId());
//		int pageSize=Integer.parseInt(request.getParameter("pageSize"));
//		int pageNo=Integer.parseInt(request.getParameter("pageNo"));
////		String userId=request.getParameter("userId");
//		
//		String virName=request.getParameter("virName");
//		try {
//			String isSupervisor=enterpriseManager.isHavePower(userId,3001);
//			String isCustService=enterpriseManager.isHavePower(userId,3002);
//			String isProgramme=enterpriseManager.isHavePower(userId,3003);
//			if("1".equals(isSupervisor)){//如果有客服主管的权限，则显示他负责楼层的全部企业入驻待处理数据
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(userId),3001);//查询客服主管
//				Page page=enterpriseManager.getEnterHisListByUser(virName,0,Integer.parseInt(userId),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}else if("1".equals(isCustService)){//如果有客服的权限，则显示企业入驻选中他为跟进客服的待处理数据
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(userId),3002);//查询客服主管
//				Page page=enterpriseManager.getEnterHisListByUser(virName,1,Integer.parseInt(userId),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}else if("1".equals(isProgramme)){
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(userId),3003);//查询客服主管
//				Page page=enterpriseManager.getEnterHisListByUser(virName,2,Integer.parseInt(userId),floorIds,pageSize,pageNo,2);
//				return AppResultUtil.createSuccesDto(page);
//			}
//			return AppResultUtil.createSuccesDto();
//		} catch (Exception e) {
//			log.error(e.getMessage());
//			return AppResultUtil.createErrorDto("100","获取企业入驻历史列表失败："+e.getMessage());
//		}
//	}

	/**
	 * 获取企业入驻详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getEmigInfo")
	@ResponseBody
	public AppResultDto getEmigInfo(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 = String.valueOf(user.getId());
		int                 emigId = Integer.parseInt(request.getParameter("emigId"));
		Map<String, Object> map    = new HashMap<String, Object>();
		try {
			EnterpriseInfo enterInfo = enterpriseManager.get(emigId);
			if (enterInfo != null) {
				EmigrationDto dto = emigrationManager.getEnterInfo(emigId, userId);
				return AppResultUtil.createSuccesDto(dto);
			} else {
				return AppResultUtil.createErrorDto("100", "获取企业迁出单据失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业迁出失败：" + e.getMessage());
		}
	}

	/**
	 * 修改企业迁出的其他记录
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateEmigByOtherRecord")
	@ResponseBody
	public AppResultDto updateEmigByOtherRecord(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      = String.valueOf(user.getId());
		int    emigId      = Integer.parseInt(request.getParameter("emigId"));
		String otherRecord = request.getParameter("otherRecord");
		try {
			EnterpriseInfo enterInfo = enterpriseManager.get(emigId);
			enterInfo.setOtherRecord(otherRecord);
			enterInfo.setModifier(Integer.parseInt(userId));
			enterInfo.setModifyTime(new Date());
			emigrationManager.updateModel(enterInfo);
			return AppResultUtil.createSuccesDto(enterInfo.getId());
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "修改企业迁出其他记录失败：" + e.getMessage());
		}

	}

	/**
	 * 修改企业迁出的结算表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "updateEmigBySettle")
	@ResponseBody
	public AppResultDto updateEmigBySettle(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          = String.valueOf(user.getId());
		String          emigId          = request.getParameter("emigId");
		FileUploadUtils fileUploadUtils = new FileUploadUtils();
		double          amount          = 0;
		try {
			if (StringUtils.isNotEmpty(request.getParameter("amount"))) {
				amount = Double.parseDouble(request.getParameter("amount"));
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "修改企业迁出结算表失败：" + e.getMessage());
		}

		String fileUrl = request.getParameter("fileUrl");//短地址
		if (StringUtils.isNotEmpty(emigId)) {
			EnterpriseInfo enterInfo = enterpriseManager.get(Integer.parseInt(emigId));
			String         custUser  = enterInfo.getCustomerService();
			if (!userId.equals(custUser)) {
				return AppResultUtil.createErrorDto("100", "您不是跟进客服，无法操作");
			}
		} else {
			return AppResultUtil.createErrorDto("100", "企业迁出id传输异常");
		}


		if (StringUtils.isNotEmpty(fileUrl)) {//修改
			try {
				EmigSettleOutPutDto dto    = emigrationManager.updateSettle(Integer.parseInt(emigId), amount, userId, fileUrl);
				AppResultDto        appDto = AppResultUtil.createSuccesDto(dto);
				if ("200".equals(appDto.getCode())) {
					emigrationManager.sendWechat(emigId, dto);
				}
				return appDto;
			} catch (Exception e) {
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", "修改企业迁出结算表失败：" + e.getMessage());
			}

		} else {
			Map<String, Object> data = new HashMap<String, Object>();
			try {
				try {
					data = enterpriseManager.uploadImage(request);
				} catch (Exception e) {
					log.error(e.getMessage());
					return AppResultUtil.createErrorDto("100", "上传图片失败：" + e.getMessage());
				}
				if (data != null && StringUtils.isNotEmpty(data.get("url").toString())) {
					String settleImage = data.get("url").toString();
					String image       = "";
					if (StringUtils.isNotEmpty(settleImage)) {
						image = fileUploadUtils.fullVisitPath(settleImage);
					}
					EmigrationSettle esInfo = emigrationManager.saveEmigraSettle(amount, settleImage, emigId, userId);
					if (esInfo != null) {
						EmigSettleOutPutDto dto    = new EmigSettleOutPutDto(esInfo.getId(), image, esInfo.getEnterId(), esInfo.getAmount(), settleImage);
						AppResultDto        appDto = AppResultUtil.createSuccesDto(dto);
						if ("200".equals(appDto.getCode())) {
							emigrationManager.sendWechat(emigId, dto);
						}
						return appDto;
					}
					return AppResultUtil.createSuccesDto();
				} 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 = "sendWaterMessage")
	@ResponseBody
	public AppResultDto sendWaterMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return AppResultUtil.createErrorDto("100", "推送水电表信息失败");
	}

	/**
	 * 获取企业迁出结算表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getEmigEmigSettle")
	@ResponseBody
	public AppResultDto getEmigEmigSettle(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		String emigId = request.getParameter("emigId");
		try {
			EmigrationSettle esInfo = emigrationManager.getEmigrationSettle(Integer.parseInt(emigId));
			if (esInfo != null) {
				FileUploadUtils fileUploadUtils = new FileUploadUtils();
				String          settleImage     = esInfo.getSettlementImageUrl();
				String          image           = "";
				if (StringUtils.isNotEmpty(settleImage)) {
					image = fileUploadUtils.fullVisitPath(settleImage);
				}
				EmigSettleOutPutDto dto = new EmigSettleOutPutDto(esInfo.getId(), image, esInfo.getEnterId(), esInfo.getAmount(), settleImage);
				return AppResultUtil.createSuccesDto(dto);
			} else {
				return AppResultUtil.createSuccesDto();
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业迁出结算表失败：" + e.getMessage());
		}
	}

	/**
	 * 获取楼栋接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getBuildList")
	@ResponseBody
	public AppResultDto getBuildList(HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		try {
//			List<TbOrganization> orgList=virtualArchManager.getBuild();
			User            user           = userManager.getUserByUsername2(userName);
			String          organizationId = getUserManageOrgIds(user);
			List<TbBuild>   buildList      = floorInfoManager.getTbBuildListByOrgaid(organizationId);
			List<CommonDto> listDto        = new ArrayList<CommonDto>();
			if (buildList != null && buildList.size() > 0) {
				for (int i = 0; i < buildList.size(); i++) {
					TbBuild   buildInfo = buildList.get(i);
					CommonDto dto       = new CommonDto();
					String    id        = String.valueOf(buildInfo.getId());
					dto.setId(Long.parseLong(id));
					dto.setName(buildInfo.getName());
					listDto.add(dto);
				}
			}
			return AppResultUtil.createSuccesDto(listDto);
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业迁出结算表失败：" + e.getMessage());
		}
	}

	/**
	 * 获取角标
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "indexTotal")
	@ResponseBody
	public AppResultDto indexTotal(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);
		if (user != null) {
			String          userId = String.valueOf(user.getId());
			EmigSumIndexDto dto    = emigrationManager.findIndex(userId, "");
			return AppResultUtil.createSuccesDto(dto);
		}
		return AppResultUtil.createSuccesDto();
	}

}
