package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.model.FloorInfo;
import com.palmnest.model.RoomInfo;
import com.palmnest.model.User;
import com.palmnest.model.property.TbBuild;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.FloorInfoManager;
import com.palmnest.service.estateserve.RoomInfoManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.property.PropertyManager;
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.ModelAttribute;
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.text.DecimalFormat;
import java.util.*;

/**
 * 楼层控制器
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping(value = "/admin/floor/*")
public class FloorInfoController extends BaseFormController {


	@Autowired
	private FloorInfoManager   floorInfoManager;
	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private RoomInfoManager    roomInfoManager;
	@Autowired
	private VirtualArchManager virtualArchManager;
	@Autowired
	private AppUserService     appUserService;
	@Autowired
	private PropertyManager    propertyManager;


	/**
	 * 新增修改楼层
	 *
	 * @param floorInfo
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateFloor")
	public void saveUpdateFloor(@ModelAttribute("floorInfo") FloorInfo floorInfo, HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject          json = new JSONObject();
		String              flId = "";
		Map<String, Object> map  = new HashMap<String, Object>();
		User                user = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		if (StringUtils.isEmpty(request.getParameter("buildId"))) {
			json.put("code", "100");
			json.put("data", "");
			json.put("msg", "楼宇为必选项.");
			StringUtil.charSet(json, request, response);
		} else {
			Long    buildId   = Long.parseLong(request.getParameter("buildId"));
			String  floorName = request.getParameter("floorName");
			String  floorId   = request.getParameter("floorId");
			int     roomCount = Integer.parseInt(request.getParameter("roomCount"));
			TbBuild buildInfo = propertyManager.getTbBuildById(Integer.parseInt(String.valueOf(buildId)));
			if (StringUtils.isNotEmpty(floorId)) {//如果楼层ID不为空，则修改
				floorInfo = floorInfoManager.get(Integer.parseInt(floorId));
				if (floorName.equals(floorInfo.getName())) {
					floorInfo.setName(floorName);
					floorInfo.setBuildId(buildId);
					floorInfo.setOrganizationId(Long.parseLong(buildInfo.getOrganizationId().toString()));
					floorInfo.setIsHaveMeeting(request.getParameter("isHaveMeeting"));
					floorInfo.setIsEnabled(1);
					floorInfo.setModifyTime(new Date());
					floorInfo.setModifier(user.getId());
					try {
						floorInfoManager.updateModel(floorInfo);
						json.put("code", "200");
						json.put("data", floorInfo);
						json.put("msg", "");
						StringUtil.charSet(json, request, response);
					} catch (Exception e) {
						log.error(e.getMessage());
						json.put("code", "100");
						json.put("data", "");
						json.put("msg", e.getMessage());
						StringUtil.charSet(json, request, response);
						throw new Exception(e);
					}
				} else {
					List<FloorInfo> list = floorInfoManager.getFloorListByName(floorName, buildId.toString());
					if (list != null && list.size() > 0) {
						json.put("code", "100");
						json.put("data", "");
						json.put("msg", "楼层名称已存在");
						StringUtil.charSet(json, request, response);
					} else {
						floorInfo.setName(floorName);
						floorInfo.setBuildId(buildId);
						floorInfo.setOrganizationId(Long.parseLong(buildInfo.getOrganizationId().toString()));
						floorInfo.setIsEnabled(1);
						floorInfo.setIsHaveMeeting(request.getParameter("isHaveMeeting"));
						floorInfo.setModifyTime(new Date());
						floorInfo.setModifier(user.getId());//----------联调时需放开注释
						try {
							floorInfoManager.updateModel(floorInfo);
							json.put("code", "200");
							json.put("data", floorInfo);
							json.put("msg", "");
							StringUtil.charSet(json, request, response);
						} catch (Exception e) {
							log.error(e.getMessage());
							json.put("code", "100");
							json.put("data", "");
							json.put("msg", e.getMessage());
							StringUtil.charSet(json, request, response);
							throw new Exception(e);
						}
					}
				}

			} else {
				List<FloorInfo> list = floorInfoManager.getFloorListByName(floorName, buildId.toString());
				if (list != null && list.size() > 0) {
					json.put("code", "100");
					json.put("data", "");
					json.put("msg", "楼层名称已存在");
					StringUtil.charSet(json, request, response);
				} else {
					floorInfo.setName(floorName);
					floorInfo.setBuildId(buildId);
					floorInfo.setIsEnabled(1);
					floorInfo.setIsHaveMeeting(request.getParameter("isHaveMeeting"));
					floorInfo.setOrganizationId(Long.parseLong(buildInfo.getOrganizationId().toString()));
					floorInfo.setCreateTime(new Date());
					floorInfo.setCreator(user.getId());//----------联调时需放开注释
					floorInfo.setModifyTime(new Date());
					floorInfo.setModifier(user.getId());
					try {
						FloorInfo flInfo = floorInfoManager.save(floorInfo);
						if (flInfo != null) {//当增加的楼层不为空并且所填的房间个数大于0时，增加房间号
							flId = flInfo.getId().toString();//楼层Id
							List<Object> roomList = new ArrayList<Object>();
							if (roomCount > 0) {

								for (int i = 1; i < roomCount + 1; i++) {
									Map<String, String> roomMap  = new HashMap<String, String>();
									RoomInfo            roomInfo = new RoomInfo();
									roomInfo.setCreateTime(new Date());
									roomInfo.setCreator(user.getId());//----------联调时需放开注释
									if (i < 10) {//101,109
										roomInfo.setName(floorName + "0" + i);
									} else {//110
										roomInfo.setName(floorName + i);
									}
									roomInfo.setFloorId(Long.parseLong(flId));
									roomInfo.setIsEnabled(1);
									roomInfo = roomInfoManager.save(roomInfo);
									if (roomInfo != null) {
										roomMap.put("roomId", roomInfo.getId().toString());
										roomMap.put("roomName", roomInfo.getName());
										roomList.add(roomMap);
									}
								}
							}
							map.put("roomList", roomList == null ? "" : roomList);//房间列表
							map.put("floor", flInfo == null ? "" : flInfo);//楼层信息
							json.put("code", "200");
							json.put("data", map);
							json.put("msg", "");
							StringUtil.charSet(json, request, response);

						}
					} catch (Exception e) {
						log.error(e.getMessage());
						json.put("code", "100");
						json.put("data", "");
						json.put("msg", e.getMessage());
						StringUtil.charSet(json, request, response);
						throw new Exception(e);
					}
				}
			}
		}
	}

	@RequestMapping(value = "/jumpFloorAndRoomList")
	public ModelAndView jumpFloorAndRoomList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model         model = new ExtendedModelMap();
		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);
		return new ModelAndView("admin/manage/roomSetting", model.asMap());
	}

	/**
	 * 根据项目获取楼宇
	 *
	 * @param orgId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getBuildByOrg")
	@ResponseBody
	public AppResultDto getBuildByOrg(String orgId, HttpServletRequest request, HttpServletResponse response) {
		User         user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
		if (StringUtils.isEmpty(orgId) || "0".equals(orgId)) {
			if (dtos != null && dtos.size() > 0) {
				orgId = "";
				for (int i = 0; i < dtos.size(); i++) {
					OrgDto dto = dtos.get(i);
					orgId = orgId + dto.getId() + ";";
				}
			}
		}
		List<TbBuild> list = floorInfoManager.getTbBuildListByOrgaid(orgId);
		return AppResultUtil.createSuccesDto(list);

	}

	/**
	 * 获取楼层房间号列表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getFloorAndRoomList")
	public void getFloorAndRoomList(HttpServletRequest request, HttpServletResponse response) throws Exception {

		DecimalFormat df4 = new DecimalFormat();
		df4.applyPattern("0.00");

		JSONObject json = new JSONObject();
		try {
			String build   = request.getParameter("buildId");
			int    buildId = 0;
			if (StringUtils.isNotEmpty(build)) {
				buildId = Integer.parseInt(request.getParameter("buildId"));
			}
			List<FloorInfo> flList = floorInfoManager.getFloorInfoByBuildId(buildId);
			List<Map>       floorL = new ArrayList<Map>();
			for (int i = 0; i < flList.size(); i++) {
				Map<String, Object> mapList   = new HashMap<String, Object>();
				FloorInfo           floorInfo = flList.get(i);
				List<RoomInfo>      roomList  = roomInfoManager.getRoomInfoByfloorId(floorInfo.getId());
				mapList.put("buildId", floorInfo.getBuildId().toString());
				if (StringUtils.isNotEmpty(floorInfo.getBuildId().toString())) {
					TbBuild buildInfo = propertyManager.getTbBuildById(Integer.parseInt(floorInfo.getBuildId().toString()));
					mapList.put("buildName", buildInfo.getName());
				}
				mapList.put("floorId", floorInfo.getId().toString());
				mapList.put("floorName", floorInfo.getName());
				mapList.put("orgId", floorInfo.getOrganizationId() == null ? "" : floorInfo.getOrganizationId().toString());
				if (StringUtils.isNotEmpty(floorInfo.getIsHaveMeeting())) {
					mapList.put("isHaveMeeting", floorInfo.getIsHaveMeeting());
				} else {
					mapList.put("isHaveMeeting", "0");
				}
				List<Map> roomL = new ArrayList<Map>();
				for (int j = 0; j < roomList.size(); j++) {
					Map<String, String> map  = new HashMap<String, String>();
					RoomInfo            room = roomList.get(j);
					map.put("roomId", room.getId().toString());
					map.put("roomName", room.getName());

					if (null != room.getArea()) {
						map.put("area", df4.format(room.getArea().setScale(2)));
					} else {
						map.put("area", "");
					}

					roomL.add(map);
				}
				mapList.put("roomList", roomL);
				floorL.add(mapList);
			}
			json.put("code", "200");
			json.put("data", floorL);
			json.put("count", floorL == null ? 0 : floorL.size());
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			log.error(e.getMessage());
			json.put("code", "100");
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
		}

	}

	/**
	 * 删除楼层及该楼层相应的房间
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteFloor")
	public void deleteFloor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject     json      = new JSONObject();
		String         isSuccess = "fail";
		int            floorId   = Integer.parseInt(request.getParameter("floorId"));
		FloorInfo      floorInfo = floorInfoManager.get(floorId);
		List<RoomInfo> roomList  = roomInfoManager.getRoomInfoByfloorId(floorId);
		try {
			if (floorInfo != null) {
				if (roomList != null && roomList.size() > 0) {
					for (int i = 0; i < roomList.size(); i++) {
						RoomInfo room = roomList.get(i);
						if (room != null) {
							roomInfoManager.remove(room);
						}
					}
				}
				floorInfoManager.remove(floorInfo);
				json.put("code", "200");
				json.put("data", "");
				json.put("msg", "");
				StringUtil.charSet(json, request, response);
			} else {
				json.put("code", "100");
				json.put("data", "");
				json.put("msg", "楼层信息为空");
				StringUtil.charSet(json, request, response);
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			json.put("code", "100");
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
			throw new Exception(e);
		}

	}

	/**
	 * 删除房间
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteRoom")
	public void deleteRoom(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json      = new JSONObject();
		String     isSuccess = "fail";
		int        roomId    = Integer.parseInt(request.getParameter("roomId"));
		RoomInfo   roomInfo  = roomInfoManager.get(roomId);
		if (roomInfo != null) {
			try {
				roomInfoManager.remove(roomInfo);
				json.put("code", "200");
				json.put("data", "");
				json.put("msg", "");
				StringUtil.charSet(json, request, response);
			} catch (Exception e) {
				json.put("code", "100");
				json.put("data", "");
				json.put("msg", e.getMessage());
				StringUtil.charSet(json, request, response);
				throw new Exception(e);
			}
		}

	}

	/**
	 * 获取楼层接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getFloorList")
	public void getFloorList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		try {
			String build   = request.getParameter("buildId");
			int    buildId = 0;
			if (StringUtils.isNotEmpty(build)) {
				buildId = Integer.parseInt(request.getParameter("buildId"));
			}
			List<FloorInfo> floorList = floorInfoManager.getFloorInfoByBuildId(buildId);//---------------楼栋
			json.put("code", "200");
			json.put("data", floorList);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			json.put("code", "100");
			json.put("data", "");
			json.put("msg", e.getMessage());
			StringUtil.charSet(json, request, response);
		}

	}

	/**
	 * 根据楼层名字查询楼层，如果存在有这个名字的楼层，不允许再添加
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getFloorByName")
	public void getFloorByName(HttpServletRequest request, HttpServletResponse response) throws Exception {
	}
}
