package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.model.User;
import com.palmnest.model.property.*;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.FloorInfoManager;
import com.palmnest.service.outer.KafkaOuterService;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.virtProject.VirtualArchService;
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.PathVariable;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 企业客户信息资料管理
 *
 * @author yubing
 * @since 2017-06-14
 */
@Slf4j
@Controller
@RequestMapping("/admin/virtualArch/*")
public class VirtualArchWebController extends BaseFormController {


	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private AppUserService     appUserService;
	@Autowired
	private FloorInfoManager   floorInfoManager;
	@Autowired
	private VirtualArchService virtualArchService;
	@Autowired
	private KafkaOuterService  kafkaOuterService;

	public void init(Model model) {
		model.addAttribute("contractStatusGroup", this.getElementGroupManager().getElementsByGroupName("contractStatusGroup"));
		model.addAttribute("vipGroup", this.getElementGroupManager().getElementsByGroupName("vipGroup"));
		model.addAttribute("reviewStatusGroup", this.getElementGroupManager().getElementsByGroupName("reviewStatusGroup"));
	}

	/**
	 * 企业信息列表查询
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) {
		initFunctionOperate(request);

		Model                model            = new ExtendedModelMap();
		List<TbOrganization> organizationList = getUserRelationOrgList(request);

		model.addAttribute("organizationList", organizationList);
		User          user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto>  dtos = appUserService.getUserOrgs(user.getId());
		List<TbBuild> list = new ArrayList<TbBuild>();
		if (dtos != null && dtos.size() > 0) {
			OrgDto org = dtos.get(0);
			list = floorInfoManager.getTbBuildListByOrgaid(org.getId().toString());
		}

		initPageOrgInfo(request, model);
		model.addAttribute("buildList", list);
		model.addAttribute("orgs", dtos);
		init(model);
		return new ModelAndView("admin/virtualArch/virtualArcList", model.asMap());
	}

	/**
	 * 获取企业资料信息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/virList")
	@ResponseBody
	public WebPageResultDto virList(HttpServletRequest request, HttpServletResponse response) {

		User user = (User) request.getSession().getAttribute("UserCache");

		String pageNo                = request.getParameter("pageNo");
		String pageSize              = request.getParameter("pageSize");
		String organizationId        = request.getParameter("orgId");
		String virtualArchitectureId = request.getParameter("virtualId");
		String customerType          = request.getParameter("customerType");
		String keyWord               = request.getParameter("keyWord");
		String contractStatus        = request.getParameter("contractStatus");
		String agentName             = request.getParameter("agentName");

		String orgStr = getUserManageOrgIds(user);
		if (StringUtils.isNotBlank(organizationId)) {
			orgStr = organizationId;
		}

		StringBuffer strSQL = new StringBuffer();
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}

		if (StringUtils.isNotBlank(orgStr)) {
			strSQL.append(" and t1.organizationId in(" + orgStr + ")");
		}

		if (StringUtils.isNotBlank(agentName)) {
			strSQL.append(" and t5.`name` like '%" + agentName + "%'");
		}
		if (user.getUserType().equals(Constants.USER_TYPE_GENERAL_USER)) {
			if (StringUtils.isNotBlank(virtualArchitectureId)) {
				Map<String, Object> map = propertyManager.getVirtualArchitectureMap(virtualArchitectureId);
				if (map != null) {
					String relation_id = null;
					if (map.get("relation_id") != null) {
						relation_id = map.get("relation_id").toString();
					}

					if (StringUtils.isNotBlank(relation_id)) {
						relation_id += "," + virtualArchitectureId;
					} else {
						relation_id = virtualArchitectureId;
					}
					strSQL.append(" and t1.id IN (" + relation_id + ")");
				} else {
					strSQL.append(" and t1.id IN (" + virtualArchitectureId + ")");
				}
			}
		} else {
			if (StringUtils.isNotBlank(virtualArchitectureId)) {
				strSQL.append(" and t1.id IN (" + virtualArchitectureId + ")");
			}
		}

		if (StringUtils.isNotBlank(customerType)) {
			strSQL.append(" and t1.customerType='" + customerType + "'");
		}
		if (StringUtils.isNotBlank(contractStatus)) {
			strSQL.append(" and t1.contractStatus='" + contractStatus + "'");
		}

		if (StringUtils.isNotBlank(keyWord)) {
			strSQL.append(" and (t1.name like '%" + keyWord + "%' or t1.customerNumber like '%" + keyWord + "%' or t1.phone like '%" + keyWord + "%' or t1.address like '%" + keyWord + "%' or t1.codeNumber like '%" + keyWord + "%' )");
		}
		//合同到期时间
		String contExpireBeginTime = request.getParameter("beginTime");
		String contExpireEndTime   = request.getParameter("endTime");
		if (StringUtil.isNotEmpty(contExpireBeginTime)) {
			String beginTime = contExpireBeginTime + " 00:00:00 ";
			if (StringUtils.isNotEmpty(contExpireEndTime)) {
				String endTime = contExpireEndTime + " 23:59:59 ";
				strSQL.append(" and (t1.contExpireTime>='" + beginTime + "' and t1.contExpireTime<='" + endTime + "' ) ");
			} else {
				strSQL.append(" and  t1.contExpireTime>='" + beginTime + "' ");
			}
		} else if (StringUtil.isNotEmpty(contExpireEndTime)) {
			String endTime = contExpireEndTime + " 23:59:59 ";
			strSQL.append(" and t1.contExpireTime<='" + endTime + "'  ");
		}

		try {
			Page                      page = propertyManager.getVirtualArchitecturePage(Integer.parseInt(pageSize), Integer.parseInt(pageNo), strSQL.toString());
			List<Map<String, Object>> list = getVirList(page.getItems());
			WebPageResultDto          dto  = new WebPageResultDto("200", "成功", list);
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询企业资料信息列表失败 virList ===>" + e.getMessage());
			e.printStackTrace();
		}

		return new WebPageResultDto("100", "查询企业资料信息列表失败", null);
	}

	/**
	 * 设置合同到期天数
	 *
	 * @param list
	 * @return
	 */
	private List<Map<String, Object>> getVirList(List<Map<String, Object>> list) {
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				if (map.containsKey("contExpireTime") && map.get("contExpireTime") != null && StringUtils.isNotEmpty(map.get("contExpireTime").toString().trim())) {
					String contExpireTime = map.get("contExpireTime").toString();
					//相差天数
					long num = DateHelper.getDateDiff(DateHelper.getNow(), DateHelper.parseToDate(contExpireTime), 4);
					if (num <= 30 && num >= 0) {
						//合同即将到期
						map.put("leaseStatus", 5);
					} else if (num < 0) {
						//合同已到期
						map.put("leaseStatus", 6);
					}
				}
			}
		}
		return list;
	}

	/**
	 * 企业信息编辑保存
	 */
	@RequestMapping(value = "/virtualArchForm")
	public ModelAndView virtualArchForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		if ("save".equals(actType)) {
			String virtualId      = request.getParameter("virtualId");
			String organizationId = request.getParameter("organizationId");
			String virtualName    = request.getParameter("virtualName");
			String address        = request.getParameter("address");
			String codeNumber     = request.getParameter("codeNumber");
			String customerNumber = request.getParameter("customerNumber");
			String contacts       = request.getParameter("contacts");
			String phone          = request.getParameter("phone");
			String employees      = request.getParameter("employees");
			String customerType   = request.getParameter("customerType");
			String status         = request.getParameter("status");
			String reviewRemark   = request.getParameter("reviewRemark");
			String buildId        = request.getParameter("buildId");

			String floorIds      = request.getParameter("floorIds");
			String roomIds       = request.getParameter("roomIds");
			String floorNames    = request.getParameter("floorNames");
			String roomNames     = request.getParameter("roomNames");
			String floorAndNames = request.getParameter("floorAndNames");
			//签约时间
			String signingTime = request.getParameter("signingTime");
			//合同到期时间
			String contExpireTime = request.getParameter("contExpireTime");
			//联系人邮箱
			String email = request.getParameter("email");
			//20190423 dz add
			String meal_card = request.getParameter("meal_card");
			//级别
			String level = request.getParameter("level");
			//代理企业
			String agent_id = request.getParameter("agent_id");
			//范围
			String range_id = request.getParameter("range_id");
			//关联企业
			String relation_id = request.getParameter("relation_id");

			String[] rangeId = null;
			if (StringUtils.isNotEmpty(range_id)) {
				rangeId = range_id.split(",");
			}
			String[] relationId = null;
			if (StringUtils.isNotEmpty(relation_id)) {
				relationId = relation_id.split(",");
			}

			VirtualArchitecture virtualArchitecture = null;
			//编辑
			if (StringUtils.isNotBlank(virtualId)) {
				virtualArchitecture = propertyManager.getVirtualArchitectureById(Integer.parseInt(virtualId));
				virtualArchitecture.setModifier(request.getRemoteUser());
				virtualArchitecture.setModifyTime(new Date());
			}
			//新增
			else {
				virtualArchitecture = new VirtualArchitecture();
				virtualArchitecture.setCreator(request.getRemoteUser());
				virtualArchitecture.setCreateTime(new Date());
				virtualArchitecture.setContractStatus("0");
			}
			virtualArchitecture.setMeal_card(meal_card);
			virtualArchitecture.setEmail(email);
			//合同到期时间
			virtualArchitecture.setContExpireTime(contExpireTime);
			//合同签约时间
			virtualArchitecture.setSigningTime(signingTime);

			virtualArchitecture.setFloorIds(floorIds);
			virtualArchitecture.setFloorNames(floorNames);
			virtualArchitecture.setRoomIds(roomIds);
			virtualArchitecture.setRoomNames(roomNames);
			if (StringUtils.isEmpty(floorAndNames) && StringUtils.isNotEmpty(roomIds)) {
				floorAndNames = virtualArchService.getFloorAndRoom(roomIds);
			}
			virtualArchitecture.setLeaseStatus(1);
			virtualArchitecture.setFloorAndNames(floorAndNames);
			virtualArchitecture.setName(virtualName);
			virtualArchitecture.setOrganizationId(Integer.parseInt(organizationId));
			virtualArchitecture.setAddress(address);
			virtualArchitecture.setCodeNumber(codeNumber);
			virtualArchitecture.setCustomerNumber(customerNumber);
			virtualArchitecture.setContacts(contacts);
			virtualArchitecture.setPhone(phone);
//			virtualArchitecture.setEmployees(Integer.parseInt(employees));
			virtualArchitecture.setCustomerType(customerType);
			virtualArchitecture.setIsEnabled("1");
			virtualArchitecture.setType("1"); //企业信息
			virtualArchitecture.setReviewRemark(reviewRemark);
			virtualArchitecture.setBuildId(Integer.parseInt(buildId));//绑定楼宇
			if (StringUtils.isEmpty(level)) {
				level = "1";
			}
			virtualArchitecture.setLevel(Integer.parseInt(level));

			if (virtualArchitecture.getId() != null && virtualArchitecture.getLevel() != null) {
				if (level.equals("1")) {
					propertyManager.deleteVirtualArchAgentById(virtualArchitecture.getId());
					if (StringUtils.isNotEmpty(agent_id)) {
						VirtualArchitectureAgent virtualArchitectureAgent = new VirtualArchitectureAgent();
						virtualArchitectureAgent.setId(virtualArchitecture.getId());
						virtualArchitectureAgent.setAgent_id(Integer.parseInt(agent_id));
						propertyManager.saveVirtualArchAgent(virtualArchitectureAgent);
					}
					//删除代理企业的相关资料
					propertyManager.deleteVirtualArchRangeById(virtualArchitecture.getId());
					propertyManager.deleteVirtualArchAgentByAgentId(virtualArchitecture.getId());
				} else {
					//先删再加
					propertyManager.deleteVirtualArchRangeById(virtualArchitecture.getId());
					propertyManager.deleteVirtualArchAgentByAgentId(virtualArchitecture.getId());
					if (relationId != null && relationId.length > 0) {
						for (String id : relationId) {
							VirtualArchitectureAgent virtualArchitectureAgent = new VirtualArchitectureAgent();
							virtualArchitectureAgent.setId(Integer.parseInt(id));
							virtualArchitectureAgent.setAgent_id(virtualArchitecture.getId());
							propertyManager.saveVirtualArchAgent(virtualArchitectureAgent);
						}
					}
					if (rangeId != null && rangeId.length > 0) {
						for (String id : rangeId) {
							VirtualArchitectureRange virtualArchitectureRange = new VirtualArchitectureRange();
							virtualArchitectureRange.setId(virtualArchitecture.getId());
							virtualArchitectureRange.setRoom_id(Integer.parseInt(id));
							propertyManager.saveVirtualArchRange(virtualArchitectureRange);
						}
					}
					propertyManager.deleteVirtualArchAgentById(virtualArchitecture.getId());
				}
			}

			//保存或者更新企业资料信息
			Map<String, String> retMap = propertyManager.saveOrUpdateVirtualArch(virtualArchitecture, status, agent_id, relationId, rangeId);

			//发送到消息通道，同步到子系统
			kafkaOuterService.syncVirtualarchitecture(virtualArchitecture);

			model.addAllAttributes(retMap);
			model.addAttribute("model", virtualArchitecture);
		} else {
			String virtualId = request.getParameter("virtualId");
			if (StringUtils.isNotEmpty(virtualId)) {
				VirtualArchitecture virtual = propertyManager.getVirtualArchitectureById(Integer.parseInt(virtualId));
				if (StringUtils.isNotEmpty(virtual.getRoomIds())) {
					model.addAttribute("floorAndRoomList", floorInfoManager.getFloorAndRoomList(virtual.getRoomIds()));
				}

				Map<String, Object> map = propertyManager.getVirtualArchitectureMap(virtualId);
				model.addAttribute("agentAndRange", map);
				model.addAttribute("model", virtual);
			}
		}
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		model.addAttribute("organizationList", organizationList);
		model.addAttribute("funcid", request.getParameter("funcid"));
		User          user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto>  dtos = appUserService.getUserOrgs(user.getId());
		List<TbBuild> list = new ArrayList<TbBuild>();
		if (dtos != null && dtos.size() > 0) {
			OrgDto org = dtos.get(0);
			list = floorInfoManager.getTbBuildListByOrgaid(org.getId().toString());
		}
		model.addAttribute("buildList", list);
		model.addAttribute("orgs", dtos);
		model.addAttribute("isAdmin", user.isAdmin());
		model.addAttribute("isAdminAndProjectAdmin", user.isAdminAndProjectAdmin());
		init(model);
		return new ModelAndView("admin/virtualArch/virtualArchForm", model.asMap());
	}

	/**
	 * 删除企业资料信息
	 */
	@RequestMapping(value = "/delete/{id}&{funcid}")
	public String delete(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		log.info("id:" + id);
		VirtualArchitecture virtual = propertyManager.getVirtualArchitectureById(id);
		if (virtual != null) {
			virtual.setIsEnabled(ElementConstant.YESORNO_0);
			virtual.setModifier(request.getRemoteUser());
			virtual.setModifyTime(new Date());
			propertyManager.deleteVirtualArch(virtual);

			//发送到消息通道，同步到子系统
//            ObjectMapper objectMapper = new ObjectMapper();
			try {
				kafkaOuterService.syncVirtualarchitecture(virtual);
//				kafkaOuterService.sendMessage(shoppingTopic, "addOrUpdateVirtualarchitecture", objectMapper.writeValueAsString(virtual));
			} catch (Exception e) {
				log.info("VirtualArchWebController delete 企业资料信息删除失败(kafka)=====>:" + e.getMessage());
				e.printStackTrace();
			}
		}
		return "redirect:/admin/virtualArch/list?funcid=" + funcid;
	}

}
