package com.palmnest.webapp.controller.dorm;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.DormRoomerListDto;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.dorm.service.DormRoomerService;
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.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.List;


@Slf4j
@Controller
@RequestMapping("/admin/dorm/*")
public class DormRoomerController {


	@Autowired
	private AppUserService    appUserService;
	@Autowired
	private DormRoomerService dormRoomerService;

	/**
	 * 跳转到条约配置界面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "jumpTreatyAllocation")
	public ModelAndView jumpTreatyAllocation(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);
		return new ModelAndView("admin/dormitoryManage/treatyAllocation", model.asMap());
	}

	/**
	 * 跳转到宿舍信息管理界面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "jumpDormitoryInfor")
	public ModelAndView jumpDormitoryInfor(HttpServletRequest request,
										   HttpServletResponse response) {

		Model model = new ExtendedModelMap();
		User  user  = (User) request.getSession().getAttribute("UserCache");

		// 错误代码 可以删除
//		if(null == user) {
//			user = (User) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
//		}
		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());

		model.addAttribute("orgs", dtos);

		return new ModelAndView("admin/dormitoryManage/dormitoryInfor", model.asMap());
	}

	/**
	 * 跳转到退宿审核管理界面
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "jumpRetreatAudit")
	public ModelAndView jumpRetreatAudit(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);
		return new ModelAndView("admin/dormitoryManage/retreatAudit", model.asMap());
	}

	/**
	 * 获取宿舍信息管理列表
	 *
	 * @param dormDto  查询参数
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getDormRoomerList")
	@ResponseBody
	public WebPageResultDto getDormRoomerList(DormRoomerListDto dormDto, int page, int limit, HttpServletRequest request, HttpServletResponse response) throws Exception {

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

		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());

		String orgIds = "";

		try {
			//判断传过来的项目存不存在？如果存在就直接用传过来的参数，如果没有就用登录用户所管辖的项目
			if (StringUtils.isEmpty(dormDto.getOrgId()) || "0".equals(dormDto.getOrgId())) {
				if (dtos != null && dtos.size() > 0) {
					for (int i = 0; i < dtos.size(); i++) {
						OrgDto dto = dtos.get(i);
						orgIds = orgIds + dto.getId() + ",";
					}
				}
			}

			//多个项目id，以逗号分隔，用于sql中查询对应的项目下的数据 org in (1,2,3)
			if (StringUtils.isNotEmpty(orgIds)) {
				//去除最后面一个逗号
				orgIds = orgIds.substring(0, orgIds.length() - 1);
				dormDto.setOrgId(orgIds);
			}

			Page dormPage = dormRoomerService.findList(dormDto, page, limit);

			//PC端列表界面返回WebPageResultDto格式的数据
			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", dormPage.getItems());

			dto.setCount(dormPage.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto("100", "查询列表失败:" + e.getMessage(), null);
		}
	}

	/**
	 * 导入员工入宿信息
	 *
	 * @param excelFile
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "importDormRoomer")
	@ResponseBody
	public AppResultDto importDormRoomer(@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());
		}

		// 获取当前项目
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		String       orgId = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			if (dtos != null && dtos.size() > 0) {
				orgId = dtos.get(0).getId().toString();
			}
		}

		// 导入数据，然后根据每条的数据类型进行数据操作
		AppResultDto dto = dormRoomerService.importDormRoomer(excelFile.getInputStream(), userId, orgId);
		return dto;
	}
}