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

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workperson.entity.WorkPerson;
import com.jeeplus.modules.workperson.service.WorkPersonService;

/**
 * 人员信息Controller
 * @author ssrh
 * @version 2018-08-21
 */
@Controller
@RequestMapping(value = "${adminPath}/workperson/workPerson")
public class WorkPersonController extends BaseController {

	@Autowired
	private WorkPersonService workPersonService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;

	@ModelAttribute
	public WorkPerson get(@RequestParam(required=false) String id) {
		WorkPerson entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workPersonService.get(id);
		}
		if (entity == null){
			entity = new WorkPerson();
		}
		return entity;
	}
	
	/**
	 * 人员信息列表页面
	 */
	@RequiresPermissions("workperson:workPerson:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkPerson workPerson, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkPerson> page = workPersonService.findPage(new Page<WorkPerson>(request, response), workPerson);
		model.addAttribute("page", page);
		return "modules/workperson/workPersonList";
	}

	/**
	 * 查看，增加，编辑人员信息表单页面
	 */
	@RequiresPermissions(value={"workperson:workPerson:view","workperson:workPerson:add","workperson:workPerson:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkPerson workPerson, Model model) {
		model.addAttribute("workPerson", workPerson);
		return "modules/workperson/workPersonForm";
	}

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workperson:workPerson: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<WorkPerson> list = ei.getDataList(WorkPerson.class);
			for (WorkPerson workPerson : list){
				try{
					workPersonService.save(workPerson);
					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()+"/workperson/workPerson/?repage";
    }
	
	/**
	 * 下载导入人员信息数据模板
	 */
	@RequiresPermissions("workperson:workPerson:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "人员信息数据导入模板.xlsx";
    		List<WorkPerson> list = Lists.newArrayList(); 
    		new ExportExcel("人员信息数据", WorkPerson.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workperson/workPerson/?repage";
    }


	@RequestMapping(value = "assignUserIds")
	@ResponseBody
	public AjaxJson assignUserIds(String userIds, RedirectAttributes redirectAttributes) {
		AjaxJson ajaxJson = new AjaxJson();
		if(Global.isDemoMode()){
			ajaxJson.setSuccess(false);
			return ajaxJson;
		}
		try {
			String[] userIdArr = userIds.split(",");
			StringBuilder msg = new StringBuilder();
			//int newNum = 0;
			for (String id:userIdArr){
				if(StringUtils.isNotBlank(id)){
					WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(id);
					WorkPerson workPerson = new WorkPerson();
					workPerson.setBasicId(id);
					workPerson.setCompanyId(workStaffBasicInfo.getCompany().getId());
					workPerson.setOfficeId(workStaffBasicInfo.getOffice().getId());
					workPersonService.save(workPerson);
				}
			}
			addMessage(redirectAttributes, ""+msg);
			ajaxJson.setMsg("引用成功");
		}catch (Exception e){
			ajaxJson.setMsg("引用失败");
		}

		return ajaxJson;
	}

}