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

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.AreaDao;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workrelationship.dao.WorkRelationshipDao;
import com.jeeplus.modules.workrelationship.entity.WorkRelationship;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffEducation;
import com.jeeplus.modules.workstaffachiveslog.dao.WorkStaffAchivesLogDao;
import com.jeeplus.modules.workstaffachiveslog.entity.WorkStaffAchivesLog;
import com.jeeplus.modules.workstaffachiveslog.service.WorkStaffAchivesLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.dao.WorkStaffBasicInfoDao;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 员工基本信息Service
 * @author ssrh
 * @version 2018-07-26
 */
@Service
@Transactional(readOnly = true)
public class WorkStaffBasicInfoService extends CrudService<WorkStaffBasicInfoDao, WorkStaffBasicInfo> {

    @Autowired
    private WorkStaffAchievementService achievementService;
    @Autowired
    private WorkStaffCertificateService certificateService;
    @Autowired
    private WorkStaffEducationService educationService;
    @Autowired
    private WorkStaffExperienceService experienceService;
    @Autowired
    private WorkStaffFamilyService familyService;
    @Autowired
    private WorkStaffLanguagesService languagesService;
    @Autowired
    private WorkStaffRecordService recordService;
    @Autowired
    private WorkStaffRewardsService rewardsService;
    @Autowired
    private WorkStaffSocialPositionService socialPositionService;
    @Autowired
    private WorkStaffTitleService titleService;
    @Autowired
    private WorkStaffTrainingService trainingService;
    @Autowired
    private UserService userService;
    @Autowired
    private WorkStaffBasicInfoDao workStaffBasicInfoDao;
    @Autowired
    private WorkRelationshipDao workRelationshipDao;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private WorkStaffAchivesDao workStaffAchivesDao;
    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private UserofficeService userofficeService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private WorkStaffAchivesLogDao workStaffAchivesLogDao;
    @Autowired
    private WorkStaffAchivesLogService workStaffAchivesLogService;
    @Autowired
    private AreaDao areaDao;

	public WorkStaffBasicInfo get(String id) {
		return super.get(id);
	}
	public Integer getByCompany(WorkStaffBasicInfo workStaffBasicInfo) {
	  return workStaffAchivesDao.getByCompany(workStaffBasicInfo);
	}
	public List<WorkStaffBasicInfo> getByCompanyInfo(WorkStaffBasicInfo workStaffBasicInfo) {
        return workStaffAchivesDao.getByCompanyInfo(workStaffBasicInfo);
    }
    public WorkStaffBasicInfo getByUserOffice(WorkStaffBasicInfo workStaffBasicInfo) {
        return workStaffAchivesDao.getByUserOffice(workStaffBasicInfo);
    }
    //根据工号及名称获取信息
    public WorkStaffBasicInfo getByNoName(WorkStaffBasicInfo workStaffBasicInfo) {
        return workStaffAchivesDao.getByNoName(workStaffBasicInfo);
    }
	//档案表
    public WorkStaffBasicInfo getAchives(String id) {
        return workStaffAchivesDao.get(id);
    }
	public List<WorkStaffBasicInfo> findList(WorkStaffBasicInfo workStaffBasicInfo) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilterOR(workStaffBasicInfo.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_STAFFBASICINFO.getValue());
            workStaffBasicInfo.getSqlMap().put("dsf", dataScopeSql);
            if(workStaffBasicInfo.getCurrentUser().getBranchOffice()==null){
                workStaffBasicInfo.getCurrentUser().setBranchOffice(workStaffBasicInfo.getCurrentUser().getCompany());
            }
        }
		return super.findList(workStaffBasicInfo);
	}
	
	public Page<WorkStaffBasicInfo> findPage(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilterOR(workStaffBasicInfo.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_STAFFBASICINFO.getValue());
            workStaffBasicInfo.getSqlMap().put("dsf", dataScopeSql);
            if(workStaffBasicInfo.getCurrentUser().getBranchOffice()==null){
                workStaffBasicInfo.getCurrentUser().setBranchOffice(workStaffBasicInfo.getCurrentUser().getCompany());
            }
        }
		return super.findPage(page, workStaffBasicInfo);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStaffBasicInfo workStaffBasicInfo,HttpServletRequest request) throws IOException {
        String baseId = workStaffBasicInfo.getId();
        workStaffBasicInfo.setId(workStaffBasicInfo.getAchiveId());
        this.saveAchive(workStaffBasicInfo,request);
        workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
        workStaffBasicInfo.setId(baseId);
		super.save(workStaffBasicInfo);
	    this.saveDetails(workStaffBasicInfo,false);
	}

    public void preSave(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request) throws IOException {
        if(workStaffBasicInfo.getCompany()==null){
            workStaffBasicInfo.setCompany(UserUtils.getSelectCompany());
        }
        if(workStaffBasicInfo.getBranchOffice()==null|| StringUtils.isBlank(workStaffBasicInfo.getBranchOffice().getId())){
            Office branchOffice = officeService.get(workStaffBasicInfo.getOffice().getId());
            if(branchOffice==null||StringUtils.isBlank(branchOffice.getBranchOffice())){
                workStaffBasicInfo.setBranchOffice(workStaffBasicInfo.getCompany());
            }else {
                workStaffBasicInfo.setBranchOffice(new Office(branchOffice.getBranchOffice()));
            }
        }
        if(StringUtils.isBlank(workStaffBasicInfo.getNo())){
            workStaffBasicInfo.setNo(this.createNo(workStaffBasicInfo));
        }
        if(StringUtils.isBlank(workStaffBasicInfo.getUserId())){
	        //根据手机号查询用户
            User user = userService.findUniqueByProperty("mobile", workStaffBasicInfo.getMobile());
            if(user==null){
                //创建新的用户
                user = this.createUser(workStaffBasicInfo);
                userService.save(user,request);
            }else {
                user = UserUtils.get(user.getId());
                this.saveUserOffice(user,workStaffBasicInfo);
                if(workStaffBasicInfo.getCompany().getId().equals(user.getCompany().getId())){
                    user.setOffice(workStaffBasicInfo.getOffice());
                    userService.updateOfficeById(user);
                    systemService.removeSession(user);
                    UserUtils.clearCache(user);
                }
            }
            workStaffBasicInfo.setUserId(user.getId());
        }
    }

    public void uploadFile(WorkStaffBasicInfo workStaffBasicInfo) {
        MultipartFile pictureFile = workStaffBasicInfo.getPictureFile();
        if (pictureFile != null && !pictureFile.isEmpty() &&pictureFile.getSize()>0) {
            String oldPhoto = workStaffBasicInfo.getPicture();
            String key = "";
            if (StringUtils.isNotBlank(oldPhoto)) {
                String aliyunUrl = Global.getAliyunUrl();
                String aliDownloadUrl = Global.getAliDownloadUrl();
                String cons = "";
                if (oldPhoto.contains(aliyunUrl)) {
                    cons = aliyunUrl;
                } else if (oldPhoto.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")) {
                    cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                } else {
                    cons = aliDownloadUrl;
                }
                String[] arr = oldPhoto.split(cons + "/");
                key = arr[1];
            }
            try {
                OSSClientUtil ossUtil1 = new OSSClientUtil();
                if (StringUtils.isNotBlank(key)) {
                    ossUtil1.deleteSingleObject(key);
                }
            }catch (Exception e){
                logger.error("oss删除文件失败！");
            }
            try {
                OSSClientUtil ossUtil2 = new OSSClientUtil();
                String filepath = ossUtil2.uploadFile2OSS(pictureFile, "photo");
                workStaffBasicInfo.setPicture(filepath);
            } catch (Exception e) {
                logger.error("oss上传文件失败！");
            }
        }
    }

    public Page<WorkStaffBasicInfo> getByRoleId(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo, String roleId){
	    if (workStaffBasicInfo==null){
            workStaffBasicInfo = new WorkStaffBasicInfo();
        }
        workStaffBasicInfo.setRoleId(roleId);
        workStaffBasicInfo.setPage(page);
        List<WorkStaffBasicInfo> list = workStaffAchivesDao.findListByRoleList(workStaffBasicInfo);
        page.setList(list);
        return page;
    }

    private String cacuPercent(int cou) {
        BigDecimal bigDecimal = new BigDecimal(cou).divide(new BigDecimal("39"),2,BigDecimal.ROUND_HALF_UP);
        NumberFormat percent = NumberFormat.getPercentInstance();
        return percent.format(bigDecimal.doubleValue());
    }

    private void saveUserOffice(User user,WorkStaffBasicInfo workStaffBasicInfo) {
        Useroffice useroffice = new Useroffice();
        useroffice.setUserId(user.getId());
        useroffice.setStatus("3");
        useroffice.setMaster(UserUtils.getUser().getId());
        useroffice.setCompanyId(workStaffBasicInfo.getCompany().getId());
        useroffice.setOfficeId(workStaffBasicInfo.getOffice().getId());
        List<Useroffice> listOffice = userofficeService.findList(useroffice);
        if(listOffice==null || listOffice.size()==0){
            userofficeService.save(useroffice);
        }else {
            Useroffice oldUseroffice = listOffice.get(0);
            oldUseroffice.setOfficeId(workStaffBasicInfo.getOffice().getId());
            userofficeService.save(oldUseroffice);
        }
    }

    private void saveAchive(WorkStaffBasicInfo workStaffBasicInfo) {
        if (workStaffBasicInfo.getIsNewRecord()){
            workStaffBasicInfo.preInsert();
            workStaffAchivesDao.insert(workStaffBasicInfo);
        }else{
            workStaffBasicInfo.preUpdate();
            workStaffAchivesDao.update(workStaffBasicInfo);
        }
    }

    private int cacuField(WorkStaffBasicInfo workStaffBasicInfo) {
        int count = 0;
        Class<? extends WorkStaffBasicInfo> basicInfoClass = workStaffBasicInfo.getClass();
        Field[] declaredFields = basicInfoClass.getDeclaredFields();
        for (Field field : declaredFields) {
            String name = field.getName();
            if("userId".equals(name)||"sqlStr".equals(name)||"branchOffice".equals(name)||"company".equals(name)||"dimissionDate".equals(name)
                    || "percent".equals(name)||"freeEndDate".equals(name)||"workEndDate".equals(name)||"pictureFile".equals(name)||"achiveId".equals(name)
                    ||"relationshipStatus".equals(name)||"labourList".equals(name)||"notifyFlag".equals(name)||"serialVersionUID".equals(name)||"tryEndTime".equals(name)){
                continue;
            }
            String methodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
            try {
                Object invoke = basicInfoClass.getMethod(methodName).invoke(workStaffBasicInfo);
                if(invoke==null)continue;
                if(invoke instanceof List)continue;
                if(invoke instanceof String && StringUtils.isBlank((String) invoke)){
                    continue;
                }
                if (invoke instanceof Area && StringUtils.isBlank(((Area) invoke).getId())){
                    continue;
                }
                count++;
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    private void sendMessage(WorkStaffBasicInfo workStaffBasicInfo, String contentStr, String titleStr, String remark) {
	    if (workStaffBasicInfo==null||StringUtils.isBlank(workStaffBasicInfo.getId())||StringUtils.isBlank(workStaffBasicInfo.getUserId())){
	        return;
        }
        WorkProjectNotify workProjectNotify = UtilNotify.saveNotify(workStaffBasicInfo.getId(),null, workStaffBasicInfo.getCompany().getId(),
                titleStr, contentStr,"69","0",remark,"");
        List<String> userIds = new ArrayList<>();
        userIds.add(workStaffBasicInfo.getUserId());
        workProjectNotify.setUser(new User(workStaffBasicInfo.getUserId()));
        workProjectNotify.setId("");
        workProjectNotify.setNotifyRole("");
        workProjectNotifyService .save(workProjectNotify);
        UserUtils.pushIm(userIds,contentStr);
    }

    private String createNo(WorkStaffBasicInfo workStaffBasicInfo) {
        String newNo="0001";
        String no = dao.queryMaxNoWithCompany(workStaffBasicInfo);
        if(StringUtils.isNotBlank(no)){
            Integer integer = Integer.valueOf(no);
            integer+=1;
            newNo = String.valueOf(integer);
        }
        no = UserUtils.getSysParam("company_number",UserUtils.getUser());
        if(StringUtils.isBlank(no)){
            no = "0000";
        }
        for(int i = newNo.length(); i<4; i++){
            newNo = "0"+newNo;
        }
        return no+newNo;
    }

    private User createUser(WorkStaffBasicInfo workStaffBasicInfo) {
        User user = new User();
        user.setOffice(workStaffBasicInfo.getOffice());
        user.setCompany(workStaffBasicInfo.getCompany());
        user.setComId(workStaffBasicInfo.getCompany().getId());
        user.setNo(workStaffBasicInfo.getNo());
        user.setName(workStaffBasicInfo.getName());
        user.setMobile(workStaffBasicInfo.getMobile());
        user.setNewPassword("123456");
        user.setLoginName(workStaffBasicInfo.getMobile());
        user.setEmail(workStaffBasicInfo.getEmail());
        user.setSex(workStaffBasicInfo.getGender());
        user.setLoginFlag("1");
        user.setFirstFlag("1");
        return user;
    }

    private int saveDetails(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
	    int count = 0;
	    if(achievementService.save(workStaffBasicInfo,first))count++;
	    if(certificateService.save(workStaffBasicInfo,first))count++;
	    if(educationService.save(workStaffBasicInfo,first))count++;
	    if(experienceService.save(workStaffBasicInfo,first))count++;
	    if(familyService.save(workStaffBasicInfo,first))count++;
	    if(languagesService.save(workStaffBasicInfo,first))count++;
	    if(recordService.save(workStaffBasicInfo,first))count++;
	    if(rewardsService.save(workStaffBasicInfo,first))count++;
	    if(socialPositionService.save(workStaffBasicInfo,first))count++;
	    if(titleService.save(workStaffBasicInfo,first))count++;
	    if(trainingService.save(workStaffBasicInfo,first))count++;
	    return count;
    }

    public void queryDetails(WorkStaffBasicInfo workStaffBasicInfo){
        achievementService.query(workStaffBasicInfo);
        certificateService.query(workStaffBasicInfo);
        educationService.query(workStaffBasicInfo);
        experienceService.query(workStaffBasicInfo);
        familyService.query(workStaffBasicInfo);
        languagesService.query(workStaffBasicInfo);
        recordService.query(workStaffBasicInfo);
        rewardsService.query(workStaffBasicInfo);
        socialPositionService.query(workStaffBasicInfo);
        titleService.query(workStaffBasicInfo);
        trainingService.query(workStaffBasicInfo);
        queryRelationShips(workStaffBasicInfo);
    }

    public void queryRelationShips(WorkStaffBasicInfo workStaffBasicInfo) {
        List<WorkRelationship> workRelationships = workRelationshipDao.getWorkRelationships(null, workStaffBasicInfo.getId());
        workStaffBasicInfo.setLabourList(workRelationships);
        if(workRelationships!=null&&workRelationships.size()>0){
            for (WorkRelationship workRelationship : workRelationships) {
                if(workRelationship!=null && workRelationship.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getId())) {
                    WorkClientAttachment workClientAttachment = new WorkClientAttachment();
                    workClientAttachment.setAttachmentId(workRelationship.getId());
                    workClientAttachment.setAttachmentFlag("108");
                    workRelationship.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
                }
            }
        }
    }

    @Transactional(readOnly = false)
	public void delete(WorkStaffBasicInfo workStaffBasicInfo) {
		super.delete(workStaffBasicInfo);
	}


    public WorkStaffBasicInfo findByIdCardAndCom(String idCard) {
	    WorkStaffBasicInfo select = new WorkStaffBasicInfo();
	    select.setIdCard(idCard);
	    select.setCompany(UserUtils.getSelectCompany());
        List<WorkStaffBasicInfo> list = workStaffAchivesDao.findListByIdCard(select);
        if(list==null||list.size()<=0){
            return null;
        }
        //判断是否存在在职
        for (WorkStaffBasicInfo workStaffBasicInfo : list) {
            if(!("离职".equals(workStaffBasicInfo.getStatus())||"退休".equals(workStaffBasicInfo.getStatus()))){
                return workStaffBasicInfo;
            }
        }
        WorkStaffBasicInfo workStaffBasicInfo = list.get(0);
        return workStaffBasicInfo;
    }
    public  Page<WorkStaffBasicInfo> findUserListPage(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        workStaffBasicInfo.setPage(page);
        page.setList(workStaffAchivesDao.findUserList(workStaffBasicInfo));
        return page;
    }
    public  Page<WorkStaffBasicInfo> findUserApplyPage(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        workStaffBasicInfo.setPage(page);
        page.setList(workStaffAchivesDao.findUserApplyList(workStaffBasicInfo));
        return page;
    }
    public  Page<WorkStaffBasicInfo> findUserShipList(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        workStaffBasicInfo.setPage(page);
        page.setList(workStaffAchivesDao.findUserShipList(workStaffBasicInfo));
        return page;
    }
    public  Page<WorkStaffBasicInfo> findTemplateUser(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        workStaffBasicInfo.setPage(page);
        page.setList(workStaffAchivesDao.findTemplateUser(workStaffBasicInfo));
        return page;
    }
    public WorkStaffBasicInfo queryAchive(WorkStaffBasicInfo workStaffBasicInfo) {
        WorkStaffBasicInfo staffBasicInfo = workStaffAchivesDao.get(workStaffBasicInfo.getAchiveId());
        staffBasicInfo.setNo(null);
        staffBasicInfo.setAchiveId(null);
        //设置工号
        Office branchOffice = officeService.get(workStaffBasicInfo.getOffice().getId());
        if(branchOffice==null||StringUtils.isBlank(branchOffice.getBranchOffice())){
            branchOffice=workStaffBasicInfo.getCompany();
        }
        workStaffBasicInfo.setBranchOffice(new Office(branchOffice.getBranchOffice()));
        //userId
        List<WorkStaffBasicInfo> list = dao.findListByUserId(workStaffBasicInfo);
        if(list!=null&&list.size()>0){
            WorkStaffBasicInfo basicInfo = list.get(0);
            staffBasicInfo.setNo(basicInfo.getNo());
            //设置当前分公司档案信息
            staffBasicInfo.setAchiveId(basicInfo.getAchiveId());
        }
        return staffBasicInfo;
    }

    public Page<WorkStaffBasicInfo> findAchivePage(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilterOR(workStaffBasicInfo.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_STAFFBASICINFO.getValue());
            workStaffBasicInfo.getSqlMap().put("dsf", dataScopeSql);
            if(workStaffBasicInfo.getCurrentUser().getBranchOffice()==null){
                workStaffBasicInfo.getCurrentUser().setBranchOffice(workStaffBasicInfo.getCurrentUser().getCompany());
            }
            workStaffBasicInfo.setPage(page);
            page.setList(workStaffAchivesDao.findList(workStaffBasicInfo));
        }else {
            page.setList(new ArrayList<WorkStaffBasicInfo>());
        }

        return page;
    }

    public WorkStaffBasicInfo getByAchiveId(WorkStaffBasicInfo workStaffBasicInfo) {
        Office branchOffice = officeService.get(workStaffBasicInfo.getOffice().getId());
        if(branchOffice==null||StringUtils.isBlank(branchOffice.getBranchOffice())){
            branchOffice=workStaffBasicInfo.getCompany();
        }
        workStaffBasicInfo.setBranchOffice(new Office(branchOffice.getBranchOffice()));
        List<WorkStaffBasicInfo> list = this.findList(workStaffBasicInfo);
        if (list==null||list.size()<=0){
            return workStaffBasicInfo;
        }
        return list.get(0);
    }

    @Transactional(readOnly = false)
    public void complete(String achiveIds) {
        if(StringUtils.isBlank(achiveIds)){
            return;
        }
        String[] split = achiveIds.split(",");
        String contentStr = "待处理，请及时完善员工档案信息。";
        String titleStr = "完善档案信息，待处理";
        String remark = "待处理";
        for (String s : split) {
            WorkStaffBasicInfo workStaffBasicInfo = workStaffAchivesDao.get(s);
            this.sendMessage(workStaffBasicInfo,contentStr,titleStr,remark);
        }
    }

    @Transactional(readOnly = false)
    public void saveAchive(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request) throws IOException {
        Office branchOffice = officeService.get(workStaffBasicInfo.getOffice().getId());
        if(branchOffice!=null&&StringUtils.isNotBlank(branchOffice.getBranchOffice())){
            workStaffBasicInfo.setBranchOffice(new Office(branchOffice.getBranchOffice()));
        }
        this.preSave(workStaffBasicInfo, request);
        this.uploadFile(workStaffBasicInfo);
        this.saveAchive(workStaffBasicInfo);
        workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
        int cou = this.saveDetails(workStaffBasicInfo,true);
        //计算信息完成度
        cou +=this.cacuField(workStaffBasicInfo);
        workStaffAchivesDao.updatePercent(workStaffBasicInfo.getId(),this.cacuPercent(cou));
        if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
            WorkProjectNotify workProjectNotify = new WorkProjectNotify();
            workProjectNotify.setNotifyId(workStaffBasicInfo.getId());
            workProjectNotifyService.readByNotifyId(workProjectNotify);
            return;
        }
        if("1".equals(workStaffBasicInfo.getNotifyFlag())){
            String contentStr = "待处理，请及时完善员工档案信息。";
            String titleStr = "完善档案信息，待处理";
            String remark = "待处理";
            this.sendMessage(workStaffBasicInfo,contentStr,titleStr,remark);
        }
    }

    public WorkStaffBasicInfo getAchive(WorkStaffBasicInfo workStaffBasicInfo) {
	    workStaffBasicInfo.setId(workStaffBasicInfo.getAchiveId());
        return workStaffAchivesDao.get(workStaffBasicInfo.getId());
    }

    public boolean validateStaff(WorkStaffBasicInfo workStaffBasicInfo,StringBuilder errInfo) {
	    boolean flag = true;
	    if(workStaffBasicInfo==null){
	        return false;
        }
	    if(workStaffBasicInfo.getCompany()==null){
	        workStaffBasicInfo.setCompany(UserUtils.getSelectCompany());
        }
        if(StringUtils.isBlank(workStaffBasicInfo.getName())){
            errInfo.append("员工姓名不能为空");
            flag = false;
        }
        if(workStaffBasicInfo.getOffice()==null||StringUtils.isBlank(workStaffBasicInfo.getOffice().getId())){
	        errInfo.append("所属部门不能为空");
            flag = false;
        }
        if(StringUtils.isBlank(workStaffBasicInfo.getIdCard())){
            errInfo.append("身份证号不能为空");
            flag = false;
        }
        if(StringUtils.isBlank(workStaffBasicInfo.getMobile())){
	        errInfo.append("手机号不能为空");
	        flag = false;
        }
	    if(StringUtils.isNotBlank(workStaffBasicInfo.getNo())) {
           int cou = workStaffAchivesDao.countByNo(workStaffBasicInfo);
           if(cou>0){
               errInfo.append("重复的工号");
               flag = false;
           }
        }

        if(StringUtils.isNotBlank(workStaffBasicInfo.getIdCard())){
            WorkStaffBasicInfo staffBasicInfo = this.findByIdCardAndCom(workStaffBasicInfo.getIdCard());
            if(staffBasicInfo!=null&&StringUtils.isNotBlank(staffBasicInfo.getId())){
                if(!("离职".equals(staffBasicInfo.getStatus())||"退休".equals(staffBasicInfo.getStatus()))){
                    errInfo.append("重复的身份证号");
                    flag = false;
                }
            }
        }
        return flag;
    }
    public void queryDetailsApply(WorkStaffBasicInfo workStaffBasicInfo){
        achievementService.querys(workStaffBasicInfo);
        certificateService.querys(workStaffBasicInfo);
        educationService.querys(workStaffBasicInfo);
        experienceService.querys(workStaffBasicInfo);
        familyService.querys(workStaffBasicInfo);
        languagesService.querys(workStaffBasicInfo);
        recordService.querys(workStaffBasicInfo);
        rewardsService.querys(workStaffBasicInfo);
        socialPositionService.querys(workStaffBasicInfo);
        titleService.querys(workStaffBasicInfo);
        trainingService.querys(workStaffBasicInfo);
        queryRelationShips(workStaffBasicInfo);
    }
    private int saveDetailsApply(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        int count = 0;
        if(achievementService.saveApply(workStaffBasicInfo,first))count++;
        if(certificateService.saveApply(workStaffBasicInfo,first))count++;
        if(educationService.saveApply(workStaffBasicInfo,first))count++;
        if(experienceService.saveApply(workStaffBasicInfo,first))count++;
        if(familyService.saveApply(workStaffBasicInfo,first))count++;
        if(languagesService.saveApply(workStaffBasicInfo,first))count++;
        if(recordService.saveApply(workStaffBasicInfo,first))count++;
        if(rewardsService.saveApply(workStaffBasicInfo,first))count++;
        if(socialPositionService.saveApply(workStaffBasicInfo,first))count++;
        if(titleService.saveApply(workStaffBasicInfo,first))count++;
        if(trainingService.saveApply(workStaffBasicInfo,first))count++;
        return count;
    }
    @Transactional(readOnly = false)
    public String completeApply(String achiveIds) {
        if(StringUtils.isBlank(achiveIds)){
            return"";
        }
        String contentStr = "待处理，请及时审核修改档案信息申请。";
        String titleStr = "修改档案信息申请，待处理";
        String remark = "待处理";
            WorkStaffBasicInfo workStaffBasicInfo = workStaffAchivesDao.get(achiveIds);
        WorkProjectNotify workProjectNotify = UtilNotify.saveNotify(workStaffBasicInfo.getId(),null, workStaffBasicInfo.getCompany().getId(),
                titleStr, contentStr,"86","0",remark,"");
        List<String> userIds = new ArrayList<>();
        List<User> rlzyList = UserUtils.getByRoleActivityEnname("rlzy",3,UserUtils.getSelectOffice().getId(),"22",UserUtils.getUser());
        if (rlzyList.size()==0 ){
            return "流程审批人不能为空,请联系管理员！";
        }
        for(User u:rlzyList){
            userIds.add(u.getId());
            workProjectNotify.setUser(u);
            workProjectNotify.setId("");
            workProjectNotify.setNotifyRole("");
            workProjectNotifyService .save(workProjectNotify);
        }
        UserUtils.pushIm(userIds,contentStr);
        return"";
    }
    @Transactional(readOnly = false)
    public void saveAchiveApply(WorkStaffBasicInfo workStaffBasicInfo, HttpServletRequest request) throws IOException {
        this.saveAchive(workStaffBasicInfo);
        workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
        int cou = this.saveDetailsApply(workStaffBasicInfo,true);
        //计算信息完成度
        cou +=this.cacuField(workStaffBasicInfo);
        workStaffAchivesDao.updatePercent(workStaffBasicInfo.getId(),this.cacuPercent(cou));
        workStaffAchivesLogDao.updateState(workStaffBasicInfo.getId(),UserUtils.getUser().getId(),new Date());
        if (StringUtils.isNotBlank(workStaffBasicInfo.getHome()) && "home".equals(workStaffBasicInfo.getHome())){
            WorkProjectNotify workProjectNotify = new WorkProjectNotify();
            workProjectNotify.setNotifyId(workStaffBasicInfo.getId());
            workProjectNotifyService.readByNotifyId(workProjectNotify);
            return;
        }
        if("1".equals(workStaffBasicInfo.getNotifyFlag())){
            String contentStr = "待处理，请及时完善员工档案信息。";
            String titleStr = "完善档案信息，待处理";
            String remark = "待处理";
            this.sendMessage(workStaffBasicInfo,contentStr,titleStr,remark);
        }
    }
    private static Map<String,String> CODE_MAP = Maps.newHashMap();//基本信息
    static{//基本信息
        CODE_MAP.put("exSoldier", "是否退伍军人");
        CODE_MAP.put("marriage", "婚姻状况");
        CODE_MAP.put("politics", "政治面貌");
        CODE_MAP.put("address", "常住地址");
        CODE_MAP.put("household", "户口所在地");
        CODE_MAP.put("nativePlace", "籍贯");
        CODE_MAP.put("picture", "头像");
        CODE_MAP.put("industryDate", "从事本行业日期");
    }
    @Transactional(readOnly = false)
    public void saveLog(WorkStaffBasicInfo workStaffBasicInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        WorkStaffBasicInfo select1 = new WorkStaffBasicInfo();
        select1.setAchiveId(workStaffBasicInfo.getId());
        WorkStaffBasicInfo w = this.getAchive(select1);//从数据库取出记录的值
        Class<? extends WorkStaffBasicInfo> basicInfoClass = workStaffBasicInfo.getClass();
        Class<? extends WorkStaffBasicInfo> wClass = w.getClass();
        Field[] declaredFields = basicInfoClass.getDeclaredFields();
        if(workStaffBasicInfo.getPictureFile()!=null&&!workStaffBasicInfo.getPictureFile().isEmpty()&&workStaffBasicInfo.getPictureFile().getSize()>0){
            MultipartFile file = workStaffBasicInfo.getPictureFile();
            this.uploadFile(workStaffBasicInfo);
        }
        for (Field field : declaredFields) {
            String name = field.getName();
            if("picture".equals(name)||"marriage".equals(name)||"politics".equals(name)||"exSoldier".equals(name)||"address".equals(name)
                    || "nativePlace".equals(name)||"household".equals(name)||"industryDate".equals(name)){
                String methodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                workStaffAchivesLog.setModule("基本信息");
                workStaffAchivesLog.setFields(name);
                workStaffAchivesLog.setState("1");
                try {
                    Object newInvoke = basicInfoClass.getMethod(methodName).invoke(workStaffBasicInfo);//修改后
                    Object oldInvoke = wClass.getMethod(methodName).invoke(w);//修改前
                    String describes=CODE_MAP.get(name);
                    if(newInvoke==null)continue;
                    if(newInvoke instanceof String){
                        String newValue=newInvoke.toString();
                        String oldValue=oldInvoke.toString();
                        if(!newValue.equals(oldValue)){
                            if("exSoldier".equals(name)){
                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                        "基本信息",describes,name,
                                        DictUtils.getDictLabel(oldValue,"yes_no",""),
                                        DictUtils.getDictLabel(newValue,"yes_no",""),
                                        oldInvoke.toString(),
                                        newInvoke.toString(),
                                        "","修改");
                            }else{
                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                        "基本信息",describes,name,
                                        oldInvoke.toString(),newInvoke.toString(),oldInvoke.toString(),newInvoke.toString(),"","修改");
                            }

                        }
                    }
                    if(newInvoke instanceof Date){//日期
                        String newDate="";
                        String oldDate="";
                        if(newInvoke!=null){
                            newDate=sdf.format(newInvoke);
                        }
                        if(oldInvoke!=null){
                           oldDate=sdf.format(oldInvoke);
                        }
                            if(!newDate.equals(oldDate)){
                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                        "基本信息",describes,name,
                                        oldDate,newDate,oldDate,newDate,"","修改");
                            }
                    };
                    if (newInvoke instanceof Area){
                        String id=((Area) newInvoke).getId();
                        Area a=areaDao.get(id);
                        if(!((Area) newInvoke).getId().equals(((Area) oldInvoke).getId())){
                            workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                    "基本信息",describes,name,
                                    ((Area) oldInvoke).getName(),a.getName(),
                                    ((Area) oldInvoke).getId(),id,"","修改");
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }

        }
        educationService.saveEdu(workStaffBasicInfo);//教育经历
        languagesService.saveEdu(workStaffBasicInfo);//外语语种
        experienceService.saveEdu(workStaffBasicInfo);//工作经历
        achievementService.saveEdu(workStaffBasicInfo);//工作业绩
        certificateService.saveEdu(workStaffBasicInfo);//执业资格证书
        familyService.saveEdu(workStaffBasicInfo);//家庭情况
        recordService.saveEdu(workStaffBasicInfo);//电子档案
        rewardsService.saveEdu(workStaffBasicInfo);//奖惩情况
        socialPositionService.saveEdu(workStaffBasicInfo);//社会及行业职务
        titleService.saveEdu(workStaffBasicInfo);//职称
        trainingService.saveEdu(workStaffBasicInfo);//培训经历
    }
}