package com.palmnest.webapp.controller.backstage;

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.output.EmigSettleOutPutDto;
import com.palmnest.application.dto.output.EmigrationDto;
import com.palmnest.model.EnterpriseInfo;
import com.palmnest.model.User;
import com.palmnest.model.emig.EmigrationSettle;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
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.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 企业迁出控制器
 */
@Slf4j
@Controller
@RequestMapping(value = "/admin/emig/*")
public class EmigrationController extends BaseFormController {


	@Autowired
	private VirArchModelManager    virArchModelManager;
	@Autowired
	private EnterpriseManager      enterpriseManager;
	@Autowired
	private WatermeterManager      watermeterManager;
	@Autowired
	private UserManager            userManager;
	@Autowired
	private EnterpriseAuditManager enterpriseAuditManager;
	@Autowired
	private OrganizationManager    organizationManager;
	@Autowired
	private EmigrationManager      emigrationManager;

	/**
	 * 访问企业迁出配置模板
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "jumpVirModel")
	public ModelAndView jumpVirModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model                model            = new ExtendedModelMap();
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("orgs", organizationList);
		return new ModelAndView("admin/moveOut/templateSetting", model.asMap());
	}

	/**
	 * 跳转企业迁出待处理列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "jumpEnterpriseList")
	public ModelAndView jumpEnterpriseList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView("admin/moveOut/moveOutHandle");
	}

	/**
	 * 跳转企业入驻历史列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "jumpEnterList")
	public ModelAndView jumpEnterList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model                model            = new ExtendedModelMap();
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("orgs", organizationList);
		return new ModelAndView("admin/moveOut/entryApplication", model.asMap());//entryApplication
	}

//	/**
//	 * 获取企业迁出待处理列表
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "getEnterpriseList")
//	@ResponseBody
//	public WebPageResultDto getEnterpriseList(HttpServletRequest request,HttpServletResponse response){
//		int pageNo=1;
//		if(StringUtils.isNotBlank(request.getParameter("page"))){
//			pageNo=Integer.parseInt(request.getParameter("page"));
//		}
//		int pageSize=10;
//		if(StringUtils.isNotBlank(request.getParameter("limit"))){
//			pageSize=Integer.parseInt(request.getParameter("limit"));
//		}
//		User user = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
//		String userId=String.valueOf(user.getId());//app用户id
//		String virName=request.getParameter("virName");
//		
//		try {
////			Page page=enterpriseManager.getEnterpriseListByStatus(0,pageSize,pageNo);//0代表获取待处理的数据
//			User userInfo=userManager.get(Long.parseLong(userId));
//			//如果该用户是没有权限的就返回空
//			//如果该用户有权限并且是客服主管的，显示全部数据（客服主管负责的楼层的全部数据）
//			//如果该用户有权限是客服、工程人员，显示分配给他的入驻单
//			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.getEnterListByUser(virName,0,Integer.parseInt(userId),floorIds,pageSize,pageNo,2,1);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}else if("1".equals(isCustService)){//如果有客服的权限，则显示企业入驻选中他为跟进客服的待处理数据
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(userId),3002);//查询客服主管
//				Page page=enterpriseManager.getEnterListByUser(virName,1,Integer.parseInt(userId),floorIds,pageSize,pageNo,2,1);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}else if("1".equals(isProgramme)){
//				String floorIds=enterpriseManager.getPowerFloor(Integer.parseInt(userId),3003);//查询客服主管
//				Page page=enterpriseManager.getEnterListByUser(virName,2,Integer.parseInt(userId),floorIds,pageSize,pageNo,2,1);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}else{
//				return new WebPageResultDto("100", "没有权限",null);
//			}
//			
//		} catch (Exception e) {
//			log.error(e.getMessage());
//			return new WebPageResultDto("100", "查询列表失败:"+e.getMessage(),null);
//		}
//	}

//	/**
//	 * 获取企业迁出历史列表
//	 * @param request
//	 * @param response
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "getEnterList")
//	@ResponseBody
//	public WebPageResultDto getEnterList(HttpServletRequest request,HttpServletResponse response) throws Exception{
//		JSONObject json=new JSONObject();
//		int pageNo=1;
//		if(StringUtils.isNotBlank(request.getParameter("page"))){
//			pageNo=Integer.parseInt(request.getParameter("page"));
//		}
//		int pageSize=10;
//		if(StringUtils.isNotBlank(request.getParameter("limit"))){
//			pageSize=Integer.parseInt(request.getParameter("limit"));
//		}
//		String floorId=request.getParameter("floorId");
//		String roomId=request.getParameter("roomId");
//		String virName=request.getParameter("virName");
//		User user = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
//		String userId=String.valueOf(user.getId());//app用户id
//		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);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}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);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}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);
//				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
//				dto.setCount(page.getTotalCount());
//				return dto;
//			}else{
//				return new WebPageResultDto("100", "没有权限",null);
//			}
//			
//		} catch (Exception e) {
//			log.error(e.getMessage());
//			return new WebPageResultDto("100", "查询列表失败:"+e.getMessage(),null);
//		}
//	}


	/**
	 * 获取企业入驻待处理单详情
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getEnterpriseInfo")
	@ResponseBody
	public AppResultDto getEnterpriseInfo(HttpServletRequest request, HttpServletResponse response) {
		User                user   = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		String              userId = String.valueOf(user.getId());//app用户id
		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 = "updateEmigBySettle")
	@ResponseBody
	public AppResultDto updateEmigBySettle(HttpServletRequest request, HttpServletResponse response) {
		User            user            = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		String          userId          = String.valueOf(user.getId());//app用户id
		String          emigId          = request.getParameter("emigId");
		FileUploadUtils fileUploadUtils = new FileUploadUtils();
		double          amount          = 0;
		if (StringUtils.isNotEmpty(request.getParameter("amount"))) {
			amount = Double.parseDouble(request.getParameter("amount"));
		}
		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) && StringUtils.isNotEmpty(emigId)) {
			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);
					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;
				} 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 emigId = request.getParameter("emigId");
		try {
			EmigrationSettle esInfo = emigrationManager.getEmigrationSettle(Integer.parseInt(emigId));
			if (esInfo != null) {
				String          settleImage     = esInfo.getSettlementImageUrl();
				FileUploadUtils fileUploadUtils = new FileUploadUtils();
				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());
		}
	}

}
