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

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

import com.google.common.collect.Maps;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.ossutil.OssClient;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.service.RoleService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysimportinfo.entity.SysImportInfo;
import com.jeeplus.modules.sysimportinfo.service.SysImportInfoService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workrelationship.entity.WorkRelationship;
import com.jeeplus.modules.workstaff.entity.WorkStaffRewards;
import com.jeeplus.modules.workstaffachiveslog.dao.WorkStaffAchivesLogDao;
import com.jeeplus.modules.workstaffachiveslog.entity.WorkStaffAchivesLog;
import com.jeeplus.modules.workstaffachiveslog.service.WorkStaffAchivesLogService;
import net.sf.json.JSONObject;
import netscape.security.UserTarget;
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.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
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.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;

/**
 * 员工基本信息Controller
 * @author ssrh
 * @version 2018-07-26
 */
@Controller
@RequestMapping(value = "${adminPath}/workstaff/workStaffBasicInfo")
public class WorkStaffBasicInfoController extends BaseController {

	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private WorkStaffAchivesLogService workStaffAchivesLogService;
	@Autowired
	private WorkStaffAchivesLogDao workStaffAchivesLogDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private SysImportInfoService sysImportInfoService;
    @Autowired
    private  RoleService roleService;

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

	/**
	 * 查看，增加，编辑员工信息表单页面
	 */
	@RequiresPermissions(value={"workstaff:workStaffBasicInfo:add","workstaff:workStaffBasicInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
        if(StringUtils.isBlank(workStaffBasicInfo.getId())&&StringUtils.isNotBlank(workStaffBasicInfo.getAchiveId())) {
            workStaffBasicInfo = workStaffBasicInfoService.getByAchiveId(workStaffBasicInfo);
        }
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
		    workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
        }else {
		    workStaffBasicInfo.setTs("0");
		    workStaffBasicInfo.setPolitics("普通居民");
		    workStaffBasicInfo.setExSoldier("0");
		    workStaffBasicInfo.setMarriage("未婚");
		    workStaffBasicInfo.setNation(DictUtils.getDictValue("汉族","nation_type",""));
        }
        workStaffBasicInfo.setRoleId(roleService.getRoleIdByUserId(workStaffBasicInfo.getUserId()));
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
			model.addAttribute("updateFlag","1");
		}
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
        String view = "modules/workstaff/workStaffBasicInfoForm";
        if(UserUtils.getUser().getId().equals(workStaffBasicInfo.getUserId())){
            view = "modules/workstaff/workStaffBasicDetailForm";
        }
		return view;
	}

	/**
	 * 查看，增加，编辑员工信息表单页面
	 */
	@RequiresPermissions(value={"workstaff:workStaffAchiveInfo:add","workstaff:workStaffAchiveInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "achiveForm")
	public String achiveForm(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
        workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
		    workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
        }
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffAchiveInfoForm";
	}
	//人员信息库用
	@RequiresPermissions(value={"workstaff:workStaffAchiveInfo:add","workstaff:workStaffAchiveInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "achiveForms")
	public String achiveForms(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
		workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
			workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
		}
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffAchiveInfoForms";
	}
    /**
     * 查看，增加，编辑员工信息表单页面
     */
    @RequiresPermissions(value={"workstaff:workStaffBasicInfo:add","workstaff:workStaffBasicInfo:edit"},logical=Logical.OR)
    @RequestMapping(value = "reform")
    public String reform(WorkStaffBasicInfo workStaffBasicInfo, Model model) {
        workStaffBasicInfo = workStaffBasicInfoService.queryAchive(workStaffBasicInfo);
        workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
        if(StringUtils.isNotBlank(workStaffBasicInfo.getAchiveId())&&!workStaffBasicInfo.getId().equals(workStaffBasicInfo.getAchiveId())) {
            //读取当前分公司劳务信息
            workStaffBasicInfo.setId(workStaffBasicInfo.getAchiveId());
            workStaffBasicInfoService.queryRelationShips(workStaffBasicInfo);
        }else if(StringUtils.isBlank(workStaffBasicInfo.getAchiveId())){
            //当前分公司没有档案记录
            workStaffBasicInfo.setLabourList(new ArrayList<WorkRelationship>());
        }
        workStaffBasicInfo.setId(null);
        workStaffBasicInfo.setOffice(null);
        workStaffBasicInfo.setJobGrade(null);
        workStaffBasicInfo.setSalary(null);
        workStaffBasicInfo.setStatus(null);
        workStaffBasicInfo.setEntryDate(null);
        workStaffBasicInfo.setDimissionDate(null);
        workStaffBasicInfo.setWorkEndDate(null);
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
        return "modules/workstaff/workStaffBasicInfoForm";
    }

	/**
	 * 查看，增加，编辑员工信息表单页面
	 */
	@RequestMapping(value = "view")
	public String view(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
            workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
        }
		Role role = roleService.get(roleService.getRoleIdByUserId(workStaffBasicInfo.getUserId()));
		workStaffBasicInfo.setRoleId(role.getId());
		workStaffBasicInfo.setRoleName(role.getName());
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffBasicInfoView";
	}

	@RequestMapping(value = "addressbookview")
	public String addressbookview(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
//		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
//			workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
//		}
		Role role = roleService.get(roleService.getRoleIdByUserId(workStaffBasicInfo.getUserId()));
		workStaffBasicInfo.setRoleId(role.getId());
		workStaffBasicInfo.setRoleName(role.getName());
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workAddressBookView";
	}

	/**
	 * 查看，增加，编辑员工信息表单页面
	 */
	@RequestMapping(value = "achiveView")
	public String achiveView(WorkStaffBasicInfo workStaffBasicInfo, Model model,boolean reFlag) {
        workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
        workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
            workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
        }
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffBasicInfoView";
	}

	/**
	 * 保存员工信息
	 */
	@RequestMapping(value = "save")
	public String save(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		MultipartFile pictureFile = workStaffBasicInfo.getPictureFile();
		if(pictureFile != null && pictureFile.getSize()>0){
			String path = new StringBuilder("employeeImg/")
			.append(workStaffBasicInfo.getName()+System.currentTimeMillis()).append(".png").toString();
			InputStream inputStream = pictureFile.getInputStream();
			OssClient ossClient = new OssClient();
			String url = ossClient.uploadFileToOss(inputStream,path);
            workStaffBasicInfo.setPicture(url);
		}else{
			workStaffBasicInfo.setPicture("");
		}

		if(!workStaffBasicInfo.getIsNewRecord()){//编辑表单保存
			WorkStaffBasicInfo t = workStaffBasicInfoService.get(workStaffBasicInfo.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workStaffBasicInfoService.save(t,request);//保存
		}else{//新增表单保存
			workStaffBasicInfoService.save(workStaffBasicInfo,request);//保存
		}
		addMessage(redirectAttributes, "保存员工信息成功");
        if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/?repage";
	}

	/**
	 * 保存员工信息
	 */
	@RequestMapping(value = "saveAchive")
	public String saveAchive(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		if(!workStaffBasicInfo.getIsNewRecord()){//编辑表单保存
            WorkStaffBasicInfo select = new WorkStaffBasicInfo();
            select.setAchiveId(workStaffBasicInfo.getId());
			WorkStaffBasicInfo t = workStaffBasicInfoService.getAchive(select);//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workStaffBasicInfoService.saveAchive(t,request);//保存
		}else{//新增表单保存
			workStaffBasicInfoService.saveAchive(workStaffBasicInfo,request);//保存
		}
		addMessage(redirectAttributes, "保存员工档案信息成功");
        if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/achivelist?repage";
	}
	//人员信息库用
	@RequestMapping(value = "saveAchives")
	public String saveAchives(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		if(!workStaffBasicInfo.getIsNewRecord()){//编辑表单保存
			WorkStaffBasicInfo select = new WorkStaffBasicInfo();
			select.setAchiveId(workStaffBasicInfo.getId());
			WorkStaffBasicInfo t = workStaffBasicInfoService.getAchive(select);//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workStaffBasicInfoService.saveAchive(t,request);//保存
		}else{//新增表单保存
			workStaffBasicInfoService.saveAchive(workStaffBasicInfo,request);//保存
		}
		addMessage(redirectAttributes, "保存员工档案信息成功");
		if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}
		return "redirect:"+Global.getAdminPath()+"/workperson/workPerson/list?repage";
	}
	/**
	 * 删除员工信息
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:del")
	@RequestMapping(value = "delete")
	public String delete(WorkStaffBasicInfo workStaffBasicInfo, RedirectAttributes redirectAttributes) {
		workStaffBasicInfoService.delete(workStaffBasicInfo);
		addMessage(redirectAttributes, "删除员工信息成功");
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/?repage";
	}
	
	/**
	 * 批量删除员工信息
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workStaffBasicInfoService.delete(workStaffBasicInfoService.get(id));
		}
		addMessage(redirectAttributes, "删除员工信息成功");
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:achiveExport")
    @RequestMapping(value = "exportAchive", method=RequestMethod.POST)
    public String exportFile(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkStaffBasicInfo> page = workStaffBasicInfoService.findAchivePage(new Page<WorkStaffBasicInfo>(request, response, -1), workStaffBasicInfo);
    		new ExportExcel(true,"员工信息", WorkStaffBasicInfo.class,1).setDataList(page.getList()).write(response, fileName).dispose();
            addMessage(redirectAttributes, "导出员工信息记录成功！");
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出员工信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/achivelist?repage";
    }

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:achiveImport")
    @RequestMapping(value = "importAchive", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			String userName = UserUtils.getUser().getName();
            String date = DateUtils.getDate("yyyyMMddHHmmss");
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkStaffBasicInfo> list = ei.getDataList(WorkStaffBasicInfo.class);
            List<WorkStaffBasicInfo> errlist = new ArrayList<>();
			for (WorkStaffBasicInfo workStaffBasicInfo : list){
				try{
				    StringBuilder errInfo = new StringBuilder();
				    if(workStaffBasicInfoService.validateStaff(workStaffBasicInfo,errInfo)) {
                        workStaffBasicInfoService.saveAchive(workStaffBasicInfo, request);
                        successNum++;
                    }else {
				        failureNum++;
				        workStaffBasicInfo.setNowDate(date);
				        workStaffBasicInfo.setErrInfo(errInfo.toString());
				        workStaffBasicInfo.setUserName(userName);
				        errlist.add(workStaffBasicInfo);
                    }
				}catch (Exception ex) {
				    logger.error("解析导入数据失败：",ex);
					failureNum++;
                    workStaffBasicInfo.setNowDate(date);
                    workStaffBasicInfo.setErrInfo(ex.getMessage());
                    workStaffBasicInfo.setUserName(userName);
                    errlist.add(workStaffBasicInfo);
				}
			}

            SysImportInfo sysImportInfo = new SysImportInfo();
            sysImportInfo.setCompanyId(UserUtils.getSelectCompany().getId());
            sysImportInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            sysImportInfo.setModular("人员档案");
            if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 个错误信息记录。");
                ExportExcel exportExcel= new ExportExcel(false,"员工信息", WorkStaffBasicInfo.class, 1).setDataList(errlist);
                OSSClientUtil ossUtil = new OSSClientUtil();

                String fileName=date+"人员档案信息错误导入日志.xlsx";
                String fileDir = "importInfo/workStaffBasicInfoImport/";
                fileDir = fileDir+System.nanoTime()+"/";
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    exportExcel.write(os);
                    byte[] content = os.toByteArray();
                    InputStream inputStream = new ByteArrayInputStream(content);
                    ossUtil.uploadFile2OSS(inputStream,fileDir, fileName);
                }catch (Exception e1){
                    logger.error("人员档案信息错误导入日志文件上传失败！",e1);
                }

                String name = Global.getAliyunUrl()+"/"+fileDir+fileName;
                logger.info("name:"+name);
                sysImportInfo.setUrl(name);
                sysImportInfo.setFileName(fileName);
                sysImportInfo.setErrCount(failureNum+"");
                sysImportInfo.setIsTrue("0");
            }else {
                sysImportInfo.setIsTrue("1");
                sysImportInfo.setErrCount("0");
            }
            String info = "已成功导入 "+successNum+" 条人员档案信息记录，失败 "+failureNum+" 个错误信息记录。";
            sysImportInfo.setErrInfo(info);
            sysImportInfoService.save(sysImportInfo);

			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条人员档案信息记录"+failureMsg);
		} catch (Exception e) {
		    logger.error("导入人员档案信息失败！",e);
			addMessage(redirectAttributes, "导入人员档案信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/achivelist?repage";
    }
	
	/**
	 * 下载导入员工信息数据模板
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:achiveImport")
    @RequestMapping(value = "importAchive/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工档案信息导入模板.xlsx";
    		List<WorkStaffBasicInfo> list = Lists.newArrayList(); 
    		new ExportExcel(true,"员工档案信息", WorkStaffBasicInfo.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/achivelist?repage";
    }

    @RequestMapping("idCard")
    @ResponseBody
	public AjaxJson idCard(String idCard){
	    AjaxJson ajaxJson = new AjaxJson();
	    WorkStaffBasicInfo obj = workStaffBasicInfoService.findByIdCardAndCom(idCard);
	    if(obj==null){
	        ajaxJson.getBody().put("exist",false);
        }else {
	        ajaxJson.getBody().put("exist",true);
            ajaxJson.getBody().put("id",obj.getId());
            if("离职".equals(obj.getStatus())||"退休".equals(obj.getStatus())){
	            ajaxJson.getBody().put("onJob",false);
            }else {
                ajaxJson.getBody().put("onJob",true);
            }
        }
	    return ajaxJson;
    }

    /**
     * 员工档案列表页面
     */
    @RequiresPermissions("workstaff:workStaffBasicInfo:achivelist")
    @RequestMapping(value = {"achivelist"})
    public String achivelist(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WorkStaffBasicInfo> page = workStaffBasicInfoService.findAchivePage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        model.addAttribute("page", page);
        return "modules/workstaff/workStaffAchivesList";
    }

    /**
     * 批量删除员工信息
     */
    @RequiresPermissions("workstaff:workStaffBasicInfo:achivelist")
    @RequestMapping(value = "complete")
    public String complete(String achiveIds, RedirectAttributes redirectAttributes) {
        workStaffBasicInfoService.complete(achiveIds);
        addMessage(redirectAttributes, "通知员工成功");
        return "redirect:"+Global.getAdminPath()+"/workstaff/workStaffBasicInfo/achivelist?repage";
    }

	@RequestMapping(value = "applyEdit")
	public String applyEdit(Model model) {
		WorkStaffBasicInfo workStaffBasicInfo=new WorkStaffBasicInfo();
		workStaffBasicInfo.setAchiveId(UserUtils.getBasicInfo().getId());
		workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
		workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
			workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
		}
		workStaffBasicInfo.setHome("home");
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffBasicDetailModify";
	}

	@RequestMapping(value = "applyEditDirectly")
	public String applyEditDirectly(Model model) {
		WorkStaffBasicInfo workStaffBasicInfo=new WorkStaffBasicInfo();
		workStaffBasicInfo.setAchiveId(UserUtils.getBasicInfo().getId());
		workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
		workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
		Role role = roleService.getRoleByUserId(workStaffBasicInfo.getUserId());
		workStaffBasicInfo.setRoleId(role.getId());
		workStaffBasicInfo.setRoleName(role.getName());
		if(StringUtils.isNotBlank(workStaffBasicInfo.getId())){
			workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
		}
		workStaffBasicInfo.setHome("home");
		model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
		return "modules/workstaff/workStaffBasicDetailModifyDirectly";
	}

	/**
	 * 保存员工信息
	 */
	@RequestMapping(value = "saveAchiveBack")
	public String saveAchiveBack(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workStaffBasicInfo.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);
		}
		if (workStaffBasicInfo.getPictureFile() == null || workStaffBasicInfo.getPictureFile().getSize() < 0) {
			workStaffBasicInfo.setPicture("");
		}
		workStaffBasicInfoService.completeApply(workStaffBasicInfo.getId());
		workStaffBasicInfoService.saveLog(workStaffBasicInfo);
		addMessage(redirectAttributes, "申请员工档案信息成功");
		return "redirect:" + Global.getAdminPath() + "/home/?repage";
	}

	/**
	 * 保存员工信息
	 */
	@RequestMapping(value = "saveAchiveModify")
	public String saveAchiveModify(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workStaffBasicInfo.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);
		}
		workStaffBasicInfoService.completeApply(workStaffBasicInfo.getId());
		workStaffBasicInfoService.saveLog(workStaffBasicInfo);
		addMessage(redirectAttributes, "申请员工档案信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/user/info?repage";
	}

	/**
	 * 我的信息-直接修改员工信息
	 */
	@RequestMapping(value = "saveAchiveModifyDirectly")
	public String saveAchiveModifyDirectly(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
        MultipartFile pictureFile = workStaffBasicInfo.getPictureFile();
        if(pictureFile != null && pictureFile.getSize()>0){
            String path = new StringBuilder("employeeImg/")
                    .append(workStaffBasicInfo.getName()+System.currentTimeMillis()).append(".png").toString();
            InputStream inputStream = pictureFile.getInputStream();
			OssClient ossClient = new OssClient();
			String url = ossClient.uploadFileToOss(inputStream,path);
            workStaffBasicInfo.setPicture(url);
        }

		String achieveId = workStaffBasicInfo.getId();
		WorkStaffBasicInfo t = workStaffBasicInfoService.getBasicInfoByAchiveId(workStaffBasicInfo.getId());//从数据库取出记录的值
		String staffId = t.getId();
		MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.setAchiveId(achieveId);
		t.setId(staffId);
		workStaffBasicInfoService.updateAchieveDirectly(t,request);
		addMessage(redirectAttributes, "保存员工档案信息成功");

		return "redirect:"+Global.getAdminPath()+"/sys/user/info?repage";
	}

	@RequestMapping("getChange")
	@ResponseBody
	public WorkStaffAchivesLog
	getChange(String name,String achiveId) throws ParseException {
		Map<String,String> map=new HashMap<>();
		WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
		workStaffAchivesLog.setStaffId(achiveId);
		workStaffAchivesLog.setModule("基本信息");
		workStaffAchivesLog.setFields(name);
		workStaffAchivesLog.setState("1");
		String value="";
		WorkStaffAchivesLog log=new WorkStaffAchivesLog();
		if(name!=null&&!name.equals("")){
			List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
			if(logs!=null&&logs.size()>0){
				log.setNewValue(logs.get(0).getNewValue());
				log.setNewKey(logs.get(0).getNewKey());
			}
		}
		return  log;
	}
	@RequestMapping("getEdu")
	@ResponseBody
	public boolean getEdu(String id,String achiveId,String module) throws ParseException {
		boolean falt=false;
		WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
		workStaffAchivesLog.setStaffId(achiveId);
		workStaffAchivesLog.setModule(module);
		workStaffAchivesLog.setSonId(id);
		workStaffAchivesLog.setState("1");
		List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
			if(logs!=null&&logs.size()>0){
				falt=true;
			}
		return  falt;
	}
	@RequestMapping("getApply")
	@ResponseBody
	public boolean getApply() throws ParseException {
		boolean falt=false;
		WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
		workStaffAchivesLog.setStaffId(UserUtils.getBasicInfo().getId());
		workStaffAchivesLog.setState("1");
		List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
		if(logs!=null&&logs.size()>0){
			falt=true;
		}
		return  falt;
	}
	/**
	 * 保存员工信息
	 */
	@RequestMapping(value = "pass")
	public String pass(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workStaffBasicInfo)){
			return form(workStaffBasicInfo, model,false);
		}
		WorkStaffBasicInfo basicInfo = workStaffBasicInfoService.getBasicInfoByAchiveId(workStaffBasicInfo.getId());
		WorkStaffBasicInfo select = new WorkStaffBasicInfo();
		select.setAchiveId(workStaffBasicInfo.getId());
		WorkStaffBasicInfo t = workStaffBasicInfoService.getAchive(select);//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		workStaffBasicInfoService.saveAchiveApply(t, request);//保存
		t.setId(basicInfo.getId());
		workStaffBasicInfoService.save(t);
		addMessage(redirectAttributes, "保存员工档案信息成功");
		return "redirect:" + Global.getAdminPath() + "/home/?repage";
	}
	@RequestMapping(value = "back")
	public String back(WorkStaffBasicInfo workStaffBasicInfo, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workStaffBasicInfo.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);
		}
		workStaffBasicInfoService.complete(workStaffBasicInfo.getId());
		workStaffAchivesLogDao.deleteBack(workStaffBasicInfo.getId());
		addMessage(redirectAttributes, "驳回成功");
		return "redirect:" + Global.getAdminPath() + "/home/?repage";
	}

    /**
     * 查看导入客户管理数据信息
     */
    //@RequiresPermissions("importInfo:importInfo:importInfoErr")
    @RequestMapping(value = "importInfoErr")
    public String importInfoErr(SysImportInfo sysImportInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
        SysImportInfo importInfo = new SysImportInfo();
        importInfo.setModular("人员档案");
        Page<SysImportInfo> page = sysImportInfoService.findPage(new Page<SysImportInfo>(request, response), importInfo);
        model.addAttribute("page", page);
        model.addAttribute("modular", "人员档案");
        return "modules/sysimportinfo/sysimportinfoList";
    }

	/**
	 * 手机号验证
	 */
	@ResponseBody
	@RequestMapping(value = "checkMobile")
	public String checkMoblie(WorkStaffBasicInfo workStaffBasicInfo) {
		List<WorkStaffBasicInfo> workStaffBasicInfos = workStaffBasicInfoService.findByMob(workStaffBasicInfo);
		if(workStaffBasicInfos != null && workStaffBasicInfos.size()>0){
			return "false";
		}
		return "true";
	}

	/**
	 * 重名跳转
	 */
	@RequestMapping(value = "repeatName")
	public String repeatName(String name,Model model) throws UnsupportedEncodingException {
		String name1 = URLDecoder.decode(name, "utf8");
		List<WorkStaffBasicInfo> list = workStaffBasicInfoService.findByName(name1);
		model.addAttribute("list",list);
		return "modules/workstaff/infoList";
	}

	/**
	 *员工通讯录展示
	 */
	@RequiresPermissions("workstaff:workStaffBasicInfo:addressbook")
	@RequestMapping(value = "addressbook")
	public String addressBook(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkStaffBasicInfo> page = workStaffBasicInfoService.findAddressBook(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
		model.addAttribute("page", page);
		return "modules/workstaff/workAddressBookList";
	}
}