/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.hr.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.hr.entity.UserInfo;
import com.jeeplus.modules.hr.service.UserInfoService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 人员基本信息Controller
 * @author fgy
 * @version 2017-12-06
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/hr/userInfo")
public class UserInfoController extends BaseController {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserofficeService userofficeService;
	@Autowired
	private UserService userService;
	
	@ModelAttribute
	public UserInfo get(@RequestParam(value ="id", required=false) String id,
						@RequestParam(value = "userOfficeId", required = false)String userOfficeId ,
						@RequestParam(value = "userId", required = false)String userId,
						@RequestParam(value = "companyId", required = false)String companyId) {
		UserInfo userInfo = new UserInfo();
		Useroffice useroffice = new Useroffice();
		User user = new User();
		if (StringUtils.isNotBlank(id)){
			userInfo = userInfoService.get(id);
		}else{
			if(StringUtils.isNotBlank(userOfficeId)){
				useroffice = userofficeService.get(userOfficeId);
				userInfo.setUserOffice(useroffice);
			}
			if(StringUtils.isNotBlank(userId)){
				user = userService.get(userId);
				userInfo.setUserId(userId);
				userInfo.setUser(user);
			}
			if(StringUtils.isNotBlank(companyId)){
				userInfo.setCompanyId(companyId);
			}
		}
		if(StringUtils.isBlank(userInfo.getGender())){
			userInfo.setGender(user.getSex());
		}
		if(StringUtils.isBlank(userInfo.getName())){
			userInfo.setName(user.getName());
		}
		if(StringUtils.isBlank(userInfo.getMobilePhone())){
			userInfo.setMobilePhone(user.getMobile());
		}
		return userInfo;
	}
	
	/**
	 * 人员基本信息列表页面
	 */
	@RequiresPermissions("hr:userInfo:list")
	@RequestMapping(value = {"list", ""})
	public String list(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<UserInfo> page = userInfoService.findPage(new Page<UserInfo>(request, response), userInfo); 
		model.addAttribute("page", page);

		User user = UserUtils.getUser();
		if(UserUtils.isManager()){
			return "modules/hr/userInfoList";
		}
		return "modules/hr/userInfoListSimple";

	}
	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"hr:userInfo:view","hr:userInfo:add","hr:userInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(UserInfo userInfo, Model model,HttpServletRequest request) {
		model.addAttribute("userInfo", userInfo);

		if("edit".equals(request.getParameter("dialog"))){
			return "modules/hr/userInfoForm";
		}
		if("view".equals(request.getParameter("dialog"))){
			return "modules/hr/userInfoView";
		}

		return "modules/hr/userInfoView";
	}

	/**
	 * 保存人员基本信息
	 */
	@RequiresPermissions(value={"hr:userInfo:add","hr:userInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(UserInfo userInfo, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, userInfo)){
			return form(userInfo, model,null);
		}
		if(!userInfo.getIsNewRecord()){//编辑表单保存
			UserInfo t = userInfoService.get(userInfo.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(userInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			userInfoService.save(t);//保存
		}else{//新增表单保存
			userInfoService.save(userInfo);//保存
		}
		addMessage(redirectAttributes, "保存人员基本信息成功");
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
	}
	
	/**
	 * 删除人员基本信息
	 */
	@RequiresPermissions("hr:userInfo:del")
	@RequestMapping(value = "delete")
	public String delete(UserInfo userInfo, RedirectAttributes redirectAttributes) {
		userInfoService.delete(userInfo);
		addMessage(redirectAttributes, "删除人员基本信息成功");
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
	}
	
	/**
	 * 批量删除人员基本信息
	 */
	@RequiresPermissions("hr:userInfo:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			userInfoService.delete(userInfoService.get(id));
		}
		addMessage(redirectAttributes, "删除人员基本信息成功");
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("hr:userInfo:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "人员基本信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<UserInfo> page = userInfoService.findPage(new Page<UserInfo>(request, response, -1), userInfo);
    		new ExportExcel("人员基本信息", UserInfo.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出人员基本信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("hr:userInfo:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<UserInfo> list = ei.getDataList(UserInfo.class);
			for (UserInfo userInfo : list){
				try{
					userInfoService.save(userInfo);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条人员基本信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条人员基本信息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入人员基本信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
    }
	
	/**
	 * 下载导入人员基本信息数据模板
	 */
	@RequiresPermissions("hr:userInfo:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "人员基本信息数据导入模板.xlsx";
    		List<UserInfo> list = Lists.newArrayList(); 
    		new ExportExcel("人员基本信息数据", UserInfo.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/hr/userInfo/?repage";
    }
	
	
	

}