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.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.VirtualInputDto;
import com.palmnest.model.User;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.AppUserService;
import com.palmnest.service.estateserve.FloorInfoManager;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

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


@Slf4j
@Controller
@RequestMapping("/admin/virtual/*")
public class VirtualArchProjectController extends BaseFormController {


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

	/**
	 * 跳转企业配置管理界面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/jumpVirProList")
	public ModelAndView jumpVirProList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/manage/enterpriseSetting", model.asMap());
	}

	/**
	 * 删除企业帐号
	 *
	 * @param virId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/deleteAccount")
	@ResponseBody
	public AppResultDto deleteAccount(String virId, String isEnable, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = user.getId().toString();
		}
		String res = virtualArchService.deleteAccount(virId, isEnable, userId);
		if ("SUCCESS".equals(res)) {
			return AppResultUtil.createSuccesDto();
		} else {
			return AppResultUtil.createErrorDto("100", res);
		}
	}

	/**
	 * 获取账号密码
	 *
	 * @param id企业id
	 * @param type   1获取账号及密码2获取密码
	 *               企业编码+加三位随时数(字母+数字)
	 * @return
	 */
	@RequestMapping(value = "/getAccount")
	@ResponseBody
	public AppResultDto getAccount(String id, int type) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isEmpty(id)) {
			return AppResultUtil.createErrorDto("100", "企业ID不能为空");
		}
		if (map.get("msg") != null && StringUtils.isNotEmpty(map.get("msg").toString())) {
			return AppResultUtil.createErrorDto("100", map.get("msg").toString());
		} else {
			map = virtualArchService.getAccount(Integer.parseInt(id), type);
			return AppResultUtil.createSuccesDto(map);
		}
	}

	/**
	 * 更新企业账号信息
	 * 保存账号和密码
	 *
	 * @param id
	 * @param account
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/saveAccount")
	@ResponseBody
	public AppResultDto saveAccount(String id, String account, String password, String orgId, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		if (StringUtils.isEmpty(id)) {
			return AppResultUtil.createErrorDto("100", "企业ID不能为空");
		}
		//chang dz 0622
		if (appUserService.checkUserExists(account)) {
			return AppResultUtil.createErrorDto("100", "用户名重复，请重新设置。");
		}


		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
		if (StringUtils.isEmpty(orgId) || "0".equals(orgId)) {
			VirtualArchitecture vir = virtualArchService.findById(Integer.parseInt(id));
			if (vir != null && vir.getOrganizationId() != null) {
				orgId = vir.getOrganizationId().toString();
			} else {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
//			if(dtos!=null&&dtos.size()>0){
//				orgId=dtos.get(0).getId().toString();
//			}else{
//				return AppResultUtil.createErrorDto("100", "项目不允许为空");
//			}
		}
		String msg = virtualArchService.saveAccount(orgId, Integer.parseInt(id), account, password, userId);
		if ("SUCCESS".equals(msg)) {
			return AppResultUtil.createSuccesDto();
		}
		return AppResultUtil.createErrorDto("100", msg);
	}

//	/**
//	 * 保存账号和密码
//	 * @param id
//	 * @param account
//	 * @param password
//	 * @param request
//	 * @param response
//	 * @return
//	 */
//	@RequestMapping(value="/saveAccount")
//	@ResponseBody
//	public AppResultDto saveAccount(VirUserAccountInputDto virUserDto,HttpServletRequest request,HttpServletResponse response){
//		User user = (User) request.getSession().getAttribute("UserCache");
//		String userId="";
//		if(user!=null){
//			userId=String.valueOf(user.getId());
//		}
//		if(StringUtils.isEmpty(virUserDto.getId())){
//			return AppResultUtil.createErrorDto("100","企业ID不能为空");
//		}
//		String msg=virtualArchService.saveAccount(virUserDto, userId);
//		if("SUCCESS".equals(msg)){
//			return AppResultUtil.createSuccesDto();
//		}
//		return AppResultUtil.createErrorDto("100",msg);
//	}

	/**
	 * 更新企业账号信息(编辑其它)
	 *
	 * @param id
	 * @param settleType
	 * @param freeLenTime
	 * @param remainderTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateVirFreeTime")
	@ResponseBody
	public AppResultDto updateVirFreeTime(String id, String settleType, String freeLenTime, String remainderTime, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		if (StringUtils.isEmpty(id)) {
			return AppResultUtil.createErrorDto("100", "企业ID不能为空");
		}
		String virPermId = request.getParameter("virPermId");
		String msg       = virtualArchService.updateVirFreeTime(Integer.parseInt(id), settleType, freeLenTime, remainderTime, userId, virPermId);
		if ("SUCCESS".equals(msg)) {
			return AppResultUtil.createSuccesDto();
		}
		return AppResultUtil.createErrorDto("100", msg);
	}

	/**
	 * 导入企业信息接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importVirtualInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	@ResponseBody
	public AppResultDto importVirtualInfo(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		String              buildId = request.getParameter("buildId");
		String              pre_id  = request.getParameter("pre_id");
		Map<String, Object> retMap  = null;
		if (StringUtils.isEmpty(buildId)) {
			return AppResultUtil.createErrorDto("100", "必须选择楼宇");
		}
		try {
			retMap = virtualArchService.importVirtualInfo(excelFile.getInputStream(), buildId);
			int bugCount = Integer.parseInt(retMap.get("bugCount").toString());
			if (bugCount > 0) {
				return AppResultUtil.createErrorDto("100", retMap.get("bugStr").toString());
			} else {
				try {
					List<VirtualInputDto> list = (List<VirtualInputDto>) retMap.get("list");
					String                res  = virtualArchService.saveImpVirtualInfo(list, userId, pre_id);
					if ("SUCCESS".equals(res)) {
						return AppResultUtil.createSuccesDto();
					} else {
						return AppResultUtil.createErrorDto("100", "导入企业信息异常");
					}
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
					return AppResultUtil.createErrorDto("100", "导入企业信息异常：" + e.getMessage());
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导入企业信息异常：" + e.getMessage());
		}
	}

	@RequestMapping(value = "/getFloorAndRoomList")
	@ResponseBody
	public AppResultDto getFloorAndRoomList(String virId) {
		try {
			if (StringUtils.isNotEmpty(virId)) {
				VirtualArchitecture       virtual = propertyManager.getVirtualArchitectureById(Integer.parseInt(virId));
				List<Map<String, Object>> list    = new ArrayList<Map<String, Object>>();
				if (StringUtils.isNotEmpty(virtual.getRoomIds())) {
					list = floorInfoManager.getFloorAndRoomList(virtual.getRoomIds());
				}
				return AppResultUtil.createSuccesDto(list);
			} else {
				return AppResultUtil.createErrorDto("100", "企业id不允许为空");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取楼层房间号失败：" + e.getMessage());
		}
	}

	/**
	 * 企业数据统计
	 *
	 * @param orgId
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	@RequestMapping(value = "getVirtualStatistics")
	@ResponseBody
	public WebPageResultDto getVirtualStatistics(String orgId, Integer dateType, String date, String endDate, int pageSize, int pageNo) {
		if (dateType == 2 && StringUtil.isNotEmpty(date)) {
			//当类型为季度时
			Map<String, String> map = getQuarter(date);
			if (map != null) {
				date = map.get("year");
				endDate = map.get("quarter");
			}
		}
		return virtualArchService.getVirtualDataByInfo(orgId, dateType, date, endDate, pageSize, pageNo);
	}

	/**
	 * 代理企业统计
	 *
	 * @return
	 */
	@RequestMapping(value = "getVirtualArchAgent")
	@ResponseBody
	public WebPageResultDto getVirtualArchAgent(int pageSize, int pageNo) {
		return virtualArchService.getVirtualArchAgent(pageSize, pageNo);
	}

	/**
	 * 导出企业数据统计报表
	 *
	 * @param orgId
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	@RequestMapping(value = "exportPlatformStatistics")
	@ResponseBody
	public AppResultDto exportVirtualStatistics(String orgId, Integer dateType, String date, String endDate) {
		if (dateType == 2 && StringUtil.isNotEmpty(date)) {
			//当类型为季度时
			Map<String, String> map = getQuarter(date);
			if (map != null) {
				date = map.get("year");
				endDate = map.get("quarter");
			}
		}
		return virtualArchService.exportVirtualStatistics(orgId, dateType, date, endDate);
	}

	/**
	 * 跳转到通行管理界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "companyStatistic")
	public ModelAndView visitorStatistic(HttpServletRequest request,
										 HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		System.out.println();
		return new ModelAndView("admin/dataStatistic/companyStatistic", model.asMap());
	}

	/**
	 * 跳转到通行管理界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "agStatistic")
	public ModelAndView agantStatistic(HttpServletRequest request,
									   HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		System.out.println();
		return new ModelAndView("admin/dataStatistic/agStatistic", model.asMap());
	}
}
