package com.jeeplus.human.enrollment.enrollmentRegistration.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserCreateResponse;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.*;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentRegistrationMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentSocialSecurityCardMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentUserInfoAuditMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentWageCardMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.dto.DingTalkUserDTO;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.dto.ExportDTO;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.DingTalkUtils;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.SnowFlake;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.*;
import com.jeeplus.sys.service.dto.*;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-27 14:27
 */
@Service
@Transactional
public class EnrollmentRegistrationService extends ServiceImpl<EnrollmentRegistrationMapper, EnrollmentRegistration> {

    @Resource
    private EnrollmentRegistrationMapper mapper;
    @Resource
    private EnrollmentUserInfoAuditMapper userInfoAuditMapper;


    @Resource
    private EnrollmentWageCardService wageCardService;

    @Resource
    private EnrollmentSocialSecurityCardService securityCardService;

    @Resource
    private EnrollmentSocialSecurityCardMapper socialSecurityCardMapper;

    @Resource
    private EnrollmentKeyCardService keyCardService;

    @Resource
    private EnrollmentWageCardMapper wageCardMapper;

    @Resource
    private DingTalkUtils dingTalkUtils;

    @Resource
    private EnrollmentEduInfoService eduInfoService;

    @Resource
    private EnrollmentWorkInfoService workInfoService;
    @Resource
    private EnrollmentTrainingInfoService trainingInfoService;

    @Resource
    private EnrollmentCertificateInfoService certificateInfoService;
    @Resource
    private EnrollmentSkillInfoService skillInfoService;

    @Resource
    private EnrollmentLanguageInfoService languageInfoService;
    @Resource
    private EnrollmentFamilyInfoService familyInfoService;
    @Resource
    private EnrollmentRewardInfoService rewardInfoService;

    @Resource
    private EnrollmentLaborContractInfoService laborContractInfoService;

    @Resource
    private EnrollmentSocietyInfoService societyInfoService;

    @Resource
    private EnrollmentPerformanceInfoService performanceInfoService;

    @Resource
    private EnrollmentUserInfoAuditService userInfoAuditService;

    /**
     * 实习人员登记表信息
     *
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<EnrollmentRegistration> findList(Page<EnrollmentRegistration> page, EnrollmentRegistration projectReportData) throws Exception {
        QueryWrapper<EnrollmentRegistration> queryWrapper = QueryWrapperGenerator.buildQueryCondition(projectReportData, EnrollmentRegistration.class);
        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotBlank(projectReportData.getMobilePhone())) {
            queryWrapper.like("a.mobile_phone", projectReportData.getMobilePhone());
        }
        if (StringUtils.isNotBlank(projectReportData.getName())) {
            queryWrapper.like("a.name", projectReportData.getName());
        }
        if (StringUtils.isNotBlank(projectReportData.getDepartment())) {
            queryWrapper.eq("a.department", projectReportData.getDepartment());
        }
        if (StringUtils.isNotBlank(projectReportData.getCompanyId())) {
            queryWrapper.eq("so.parent_id", projectReportData.getCompanyId());
        }
        if (StringUtils.isNotBlank(projectReportData.getLoginFlag())) {
            queryWrapper.eq("u.login_flag", projectReportData.getLoginFlag());
        }
        if (StringUtils.isNotBlank(projectReportData.getPoliticalOutlook())) {
            queryWrapper.eq("a.political_outlook", projectReportData.getPoliticalOutlook());
        }

        if (projectReportData.getCreateDates() != null && projectReportData.getCreateDates().length > 0) {
            queryWrapper.between("a.entry_date", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }

        IPage<EnrollmentRegistration> list = mapper.findList(page, queryWrapper);
        return list;

    }


    /**
     * 导出实习人员登记表信息
     *
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ExportDTO> exportList(Page<ExportDTO> page, ExportDTO projectReportData) throws Exception {
        QueryWrapper<ExportDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(projectReportData, ExportDTO.class);
        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotBlank(projectReportData.getMobilePhone())) {
            queryWrapper.like("a.mobile_phone", projectReportData.getMobilePhone());
        }
        if (StringUtils.isNotBlank(projectReportData.getName())) {
            queryWrapper.like("a.name", projectReportData.getName());
        }
        if (StringUtils.isNotBlank(projectReportData.getDepartment())) {
            queryWrapper.eq("a.department", projectReportData.getDepartment());
        }
        if (StringUtils.isNotBlank(projectReportData.getCompanyId())) {
            queryWrapper.eq("so.parent_id", projectReportData.getCompanyId());
        }
        IPage<ExportDTO> list = mapper.exportList(page, queryWrapper);
        for (ExportDTO record : list.getRecords()) {
            //根据用户查询岗位和角色信息
            if (ObjectUtil.isNotEmpty(record)) {
                UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(record.getUserId());
                if (userDTO != null) {
                    if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())) {
                        StringBuilder roleBuilder = new StringBuilder();
                        for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                            RoleDTO dto = SpringUtil.getBean(IRoleApi.class).getRoleDTOByIdForApp(roleDTO.getId());
                            if (ObjectUtil.isNotEmpty(dto)) {
                                roleBuilder.append(dto.getName()).append(",");
                            }
                        }

                        // 去掉最后一个多余的逗号
                        if (roleBuilder.length() > 0) {
                            roleBuilder.setLength(roleBuilder.length() - 1);
                        }

                        record.setRole(roleBuilder.toString());
                    }
                    if (CollectionUtil.isNotEmpty(userDTO.getPostDTOList())) {
                        StringBuilder postBuilder = new StringBuilder();
                        for (PostDTO postDTO : userDTO.getPostDTOList()) {
                            PostDTO dto = SpringUtil.getBean(IPostApi.class).getPostDTOById(postDTO.getId());
                            if (ObjectUtil.isNotEmpty(dto)) {
                                postBuilder.append(dto.getName()).append(",");
                            }
                        }
                        // 去掉最后一个多余的逗号
                        if (postBuilder.length() > 0) {
                            postBuilder.setLength(postBuilder.length() - 1);
                        }
                        record.setPost(postBuilder.toString());
                    }
                }
            }
        }
        return list;

    }


    public EnrollmentRegistration saveRegistration(EnrollmentRegistration registration) throws Exception {

        if (StringUtils.isNotEmpty(registration.getId())) {

            EnrollmentRegistration report = mapper.getById(registration.getId());
            if (report != null) {
                return update(registration);
            }
        }
        return add(registration);
    }

    public EnrollmentRegistration saveRegistration2(EnrollmentRegistration registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())) {

            EnrollmentRegistration report = mapper.getById(registration.getId());
            if (report != null) {
                return update2(registration);
            }
        }
        return add(registration);
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public EnrollmentRegistration add(EnrollmentRegistration reportData) throws Exception {

        String currentToken = TokenProvider.getCurrentToken();

        QueryWrapper<EnrollmentRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", reportData.getIdCard());
        queryWrapper.eq("del_flag", 0);

        // 删除基础信息表
        Integer integer = mapper.selectCount(queryWrapper);
        Integer mobilePhoneOnly = SpringUtil.getBean(IUserApi.class).selectCountByMobile(reportData.getMobilePhone());

        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        EnrollmentRegistration report = new EnrollmentRegistration();

        if (integer <= 0 && mobilePhoneOnly <= 0) {
            //为空则表示移动端扫码登录
            if (StringUtils.isBlank(reportData.getIsPc())) {
                reportData.setIsPc("2");
            }
            String id = SnowFlake.getId();
            BeanUtils.copyProperties(reportData, report);
            report.setId(id);
            report.setCreateById("1");
            report.setCreateTime(new Date());
            report.setUpdateById("1");
            report.setUpdateTime(new Date());

            if (StringUtils.isNotBlank(report.getSocialSecurityNumber())) {
                EnrollmentSocialSecurityCard securityCard = new EnrollmentSocialSecurityCard();
                String amountId = SnowFlake.getId();
                securityCard.setId(amountId);
                securityCard.setCreateById("1");
                securityCard.setCreateTime(new Date());
                securityCard.setUpdateById("1");
                securityCard.setUpdateTime(new Date());
                securityCard.setSocialSecurityNumber(report.getSocialSecurityNumber());
                securityCard.setSocialSecurityBankNumber(report.getSocialSecurityBankNumber());
                securityCard.setSocialSecurityPictureFront(report.getSocialSecurityPictureFront());
                securityCard.setSocialSecurityPictureOpposite(report.getSocialSecurityPictureOpposite());
                securityCard.setEnrollmentRegistrationId(id);

                socialSecurityCardMapper.insert(securityCard);
            }

            //if (null == currentToken) {

            //发起员工入职流程
            Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("员工入职");
            String procDefId = map.get("id") + "";

            report.setProcessDefinitionId(procDefId);
            report.setProcessType("0");
            mapper.insert(report);

            Map<String, Map<String, String>> allMap = new HashMap<>();

            String procDefKey = map.get("key") + "";
            String businessTable = "human_resources_enrollment_registration";

            String businessId = id;
            String title = "管理员发起了- [" + report.getName() + "员工入职]";

            //获取实习信息审核员信息
            RoleDTO roleDTO = SpringUtil.getBean(IRoleApi.class).getRoleDTOByName2("实习信息审核员");
            String assignee = getAssignee(roleDTO.getId());
            String recordType = "";

            Map<String, String> newMap = pingMap(procDefId, procDefKey, businessTable, businessId, title, assignee, recordType);
            allMap.put("入职", newMap);
            if ("2".equals(reportData.getIsPc())) {
                SpringUtil.getBean(IFlowableApi.class).startForFenNew(allMap);
            }
            /*} else {
                mapper.insert(report);
            }*/
        }

        return report;
    }

    public String getAssignee(String roleId) {
        List<UserDTO> userDTOS = SpringUtil.getBean(IUserApi.class).findListByRoleId(roleId);
        StringJoiner idJoiner = new StringJoiner(",");
        for (UserDTO user : userDTOS) {
            idJoiner.add(String.valueOf(user.getId()));
        }

        return idJoiner.toString();
    }

    public String getAssignee2(String roleId) {
        List<UserDTO> userDTOS = SpringUtil.getBean(IUserApi.class).findListFlowAbleByPostId(roleId);
        StringJoiner idJoiner = new StringJoiner(",");
        for (UserDTO user : userDTOS) {
            idJoiner.add(String.valueOf(user.getId()));
        }

        return idJoiner.toString();
    }

    public Map<String, String> pingMap(String procDefId, String procDefKey, String businessTable,
                                       String businessId, String title, String assignee, String recordType) {
        Map<String, String> map = new HashMap();
        map.put("procDefId", procDefId);
        map.put("procDefKey", procDefKey);
        map.put("businessTable", businessTable);
        map.put("businessId", businessId);
        map.put("title", title);
        map.put("assignee", assignee);
        map.put("recordType", recordType);
        return map;
    }


    public Map<String, String> pingMapUserId(String procDefId, String procDefKey, String businessTable,
                                             String businessId, String title, String assignee, String recordType, String userId) {
        Map<String, String> map = new HashMap();
        map.put("procDefId", procDefId);
        map.put("procDefKey", procDefKey);
        map.put("businessTable", businessTable);
        map.put("businessId", businessId);
        map.put("title", title);
        map.put("assignee", assignee);
        map.put("recordType", recordType);
        map.put("userId", userId);
        return map;
    }


    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public EnrollmentRegistration update(EnrollmentRegistration reportData) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        EnrollmentRegistration report = new EnrollmentRegistration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        //生成一个系统账号
        // 生成id
        String amountId = "";
        if (StringUtils.isBlank(report.getUserId())) {
            amountId = SnowFlake.getId();
            report.setUserId(amountId);
        } else {
            amountId = report.getUserId();
        }


        if (StringUtils.isNotBlank(report.getType()) && !userDTO.isAdmin()) {
            if (report.getType().equals("5")) {
                //获取当前的用户，审核的人
                UserDTO dto = new UserDTO();
                //设置信息
                dto.setId(amountId);
                dto.setName(report.getName());
                dto.setPassword(SecurityUtils.encryptPassword("123456"));
                dto.setLoginName(report.getName());
                dto.setLoginFlag("1");
                dto.setMobile(report.getMobilePhone());
                dto.setPhoto("");
//                dto.setTenantDTO(userDTO.getTenantDTO());
                //部门
                OfficeDTO officeDTO = new OfficeDTO();
                officeDTO.setId(report.getDepartment());
                dto.setOfficeDTO(officeDTO);
                //设置角色
                OfficeDTO office = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getDepartment());
                //公司
                OfficeDTO companyDto = new OfficeDTO();
                companyDto.setId(office.getParent().getId());
                dto.setCompanyDTO(companyDto);
                dto.setNo(report.getMobilePhone());

                String name = "兴光会计员工";
                List<RoleDTO> roleIdList = new ArrayList<>();

//                roleIdList.add(roleInfo);


                String officeName = "";
                String networkAddress = "";
                if (null != office) {
                    Map<String, String> keyMap = new HashMap<>();
                    TenantDTO tenantDTO = new TenantDTO();
                    tenantDTO.setId(office.getTenantId());
                    dto.setTenantDTO(tenantDTO);
                    if (office.getTenantId().equals("10003")) {
                        officeName = "会计业务管理公司";
                        networkAddress = "cpapmis.xgccpm.com";
                        keyMap.put("name", "兴光会计员工,共有权限（会计）");
                        keyMap.put("tenantId", office.getTenantId());
                        roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                    } else if (office.getTenantId().equals("10004")) {
                        officeName = "中审管理公司";
                        networkAddress = "zs.xgccpm.com";
                        keyMap.put("name", "中审员工,共有权限（中审）");
                        keyMap.put("tenantId", office.getTenantId());
                        roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                    } else if (office.getTenantId().equals("10001")) {
                        officeName = "评估管理公司";
                        networkAddress = "http://amc.xgccpm.com";
                        keyMap.put("name", "评估员工,共有权限（评估）");
                        keyMap.put("tenantId", office.getTenantId());
                        roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                    } else if (office.getTenantId().equals("10006")) {
                        officeName = "苏州分公司";
                        networkAddress = "sz.xgccpm.com";
                        keyMap.put("name", "审计员工,共有权限（苏州）");
                        keyMap.put("tenantId", office.getTenantId());
                        roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                    } else if (office.getTenantId().equals("10005")) {
                        officeName = "兴光项目公司";
                        networkAddress = "xm.xgccpm.com";
                        keyMap.put("name", "项目公司综合管理部员工,共有权限（项目）");
                        keyMap.put("tenantId", office.getTenantId());
                        roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                    }
                } else {
                    TenantDTO tenantDTO = new TenantDTO();
                    tenantDTO.setId("10002");
                    dto.setTenantDTO(tenantDTO);
                    officeName = "综合管理公司";
                }
                dto.setRoleDTOList(roleIdList);
                String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue("dd_status", "dd_status", "0");
                if ("1".equals(dictValue)) {
                    //钉钉逻辑
                    //判断用户是否为 评估 或者 会计 员工
                    if (office.getTenantId().equals("10003") || office.getTenantId().equals("10001")) {
                        //获取用户所在部门信息
                        OfficeDTO officeDto = SpringUtil.getBean(IOfficeApi.class).getOfficeById(dto.getOfficeDTO().getId());
                        //获取钉钉所有部门信息
                        List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponses = dingTalkUtils.deptList(office.getTenantId());
                        for (OapiV2DepartmentListsubResponse.DeptBaseResponse dept : deptBaseResponses) {
                            //找到用户所在的钉钉部门
                            if (officeDto.getName().equals(dept.getName())) {
                                DingTalkUserDTO dingTalkUserDTO = new DingTalkUserDTO();
                                dingTalkUserDTO.setMobile(dto.getMobile());
                                dingTalkUserDTO.setName(dto.getName());
                                dingTalkUserDTO.setDeptIdList(String.valueOf(dept.getDeptId()));
                                //通过用户手机号查询钉钉是否存在用户信息，判断是更新还是新增
                                if (StringUtils.isNotBlank(report.getDdId())) {
                                    dingTalkUserDTO.setUserid(report.getDdId());
                                    dingTalkUtils.updateUser(dingTalkUserDTO, office.getTenantId());
                                } else {
                                    //将手机号作为用户钉钉userID
                                    dingTalkUserDTO.setUserid(dingTalkUserDTO.getMobile());
                                    //添加钉钉用户，暂时无需处理返回
                                    OapiV2UserCreateResponse oapiV2UserCreateResponse = dingTalkUtils.addUser(dingTalkUserDTO, office.getTenantId());
                                    //数插入ddid
                                    dto.setDdId(dingTalkUserDTO.getMobile());
                                    report.setDdId(dingTalkUserDTO.getMobile());
                                }
                                break;
                            }
                        }
                    }
                    //钉钉逻辑
                }

                SpringUtil.getBean(IUserApi.class).saveOrUpdate(dto);


//                report.setOnJobStatus("正式");
                //发送短信通知 (未实现)

                PostDTO postDTO = SpringUtil.getBean(IPostApi.class).getPostDTOByName("门卡管理员");
                List<UserDTO> listByPostId = SpringUtil.getBean(IUserApi.class).findListFlowAbleByPostId(postDTO.getId());

                /*String randomCode = report.getName() + "你好!欢迎入职" + officeName + "，请尽快登录公司系统:" + networkAddress
                        + "完善个人信息（包括社保卡号与工资卡号）并修改初始密码，系统初始账号密码为：" + report.getName() +
                        "/123456，人事部门已在为你办理门禁卡，办理成功后将由系统告知，在收到系统通知后，请及时到信息部" + listByPostId.get(0).getName() + "处领取门禁卡！" +
                        "注：工资卡需同时提供中信银行、招商银行卡号";*/
                Map<String, Object> stringObjectMap = SpringUtil.getBean(IUserApi.class).sendEntryRandomCodes(report.getMobilePhone(), report.getName(), officeName, listByPostId.get(0).getName(), office.getTenantId());
                Integer statusCode = (Integer) stringObjectMap.get("statusCode");
                if (200 == statusCode) {
                    System.out.println("短信发送成功!");
                } else if (10001 == statusCode) {
                    String message = (String) stringObjectMap.get("message");
                    System.out.println(message);
                }else if(10002 == statusCode){
                    System.out.println("账户短信量余额不足，请联系管理员进行充值!");
                }else if(10003 == statusCode){
                    System.out.println("手机号获取验证码次数已达每日上限!");
                } else {
                    System.out.println("短信发送失败，错误代码：101，请联系管理员!");
                }

                //当流程结束的时候，发起工资卡信息完善流程
                Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("工资卡信息完善");
                String procDefId = map.get("id") + "";

                //当流程结束的时候，发起工资卡信息完善流程
                String uid = SnowFlake.getId();
                EnrollmentWageCard wageCard = new EnrollmentWageCard();
                wageCard.setId(uid);
                wageCard.setCreateById("1");
                wageCard.setUpdateById("1");
                wageCard.setProcessDefinitionId(procDefId);
                wageCard.setEnrollmentRegistrationId(report.getId());
                wageCardService.save(wageCard);

                String procDefKey = map.get("key") + "";
                String businessTable = "human_resources_enrollment_wage_card";
                String businessId = uid;
                String title = "工资卡信息完善";
                String assignee = amountId;
                String recordType = "";
                Map<String, String> newMap = new HashMap();
                newMap.put("procDefId", procDefId);
                newMap.put("procDefKey", procDefKey);
                newMap.put("businessTable", businessTable);
                newMap.put("businessId", businessId);
                newMap.put("title", title);
                newMap.put("assignee", assignee);
                newMap.put("recordType", recordType);
                String procInsId = SpringUtil.getBean(IFlowableApi.class).startForFen(newMap);

                wageCard.setProcInsId(procInsId);
                wageCard.setType("2");
                wageCardService.saveOrUpdate(wageCard);

                //发起社保流程
                if (StringUtils.isBlank(report.getSocialSecurityNumber())) {
                    Map cardMap = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("社保登记");
                    String procDefId2 = cardMap.get("id") + "";

                    //当流程结束的时候，发起工资卡信息完善流程
                    String uuid = SnowFlake.getId();
                    EnrollmentSocialSecurityCard securityCard = new EnrollmentSocialSecurityCard();
                    securityCard.setId(uuid);
                    securityCard.setCreateById("1");
                    securityCard.setUpdateById("1");
                    securityCard.setProcessDefinitionId(procDefId2);
                    securityCard.setEnrollmentRegistrationId(report.getId());
                    securityCardService.save(securityCard);

                    String procDefKey2 = cardMap.get("key") + "";
                    String businessTable2 = "human_resources_enrollment_social_security_card";
                    String businessId2 = uuid;
                    String title2 = "社保卡信息完善";
                    String assignee2 = amountId;
                    String recordType2 = "";
                    Map<String, String> newMap2 = new HashMap();
                    newMap2.put("procDefId", procDefId2);
                    newMap2.put("procDefKey", procDefKey2);
                    newMap2.put("businessTable", businessTable2);
                    newMap2.put("businessId", businessId2);
                    newMap2.put("title", title2);
                    newMap2.put("assignee", assignee2);
                    newMap2.put("recordType", recordType2);
                    String procInsId2 = SpringUtil.getBean(IFlowableApi.class).startForFen(newMap2);

                    securityCard.setProcInsId(procInsId2);
                    securityCard.setType("2");
                    securityCardService.saveOrUpdate(securityCard);
                }
                //发起门卡办理通知流程
                Map keyMap = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("门卡办理");
                String keyProcDefId = keyMap.get("id") + "";

                //当流程结束的时候，发起工资卡信息完善流程
                String keyUid = SnowFlake.getId();
                EnrollmentKeyCard keyCard = new EnrollmentKeyCard();
                keyCard.setId(keyUid);
                keyCard.setCreateById("1");
                keyCard.setUpdateById("1");
                keyCard.setProcessDefinitionId(keyProcDefId);
                keyCard.setEnrollmentRegistrationId(report.getId());
                keyCardService.save(keyCard);

                String keyProcDefKey = keyMap.get("key") + "";
                String keyBusinessTable = "human_resources_enrollment_key_card";
                String keyBusinessId = keyUid;
                String keyTitle = report.getName() + "的门卡办理";

//                UserDTO userInfo = SpringUtil.getBean(IUserApi.class).getByLoginNameNotTenantId("赵俐");
//                String keyAssignee = userInfo.getId();

                PostDTO postInfo = SpringUtil.getBean(IPostApi.class).getPostDTOByName("门卡管理员");
                String keyAssignee = getAssignee2(postInfo.getId());

                String keyRecordType = "";
                Map<String, String> keyMap2 = new HashMap();
                keyMap2.put("procDefId", keyProcDefId);
                keyMap2.put("procDefKey", keyProcDefKey);
                keyMap2.put("businessTable", keyBusinessTable);
                keyMap2.put("businessId", keyBusinessId);
                keyMap2.put("title", keyTitle);
                keyMap2.put("assignee", keyAssignee);
                keyMap2.put("recordType", keyRecordType);
                String procInsId2 = SpringUtil.getBean(IFlowableApi.class).startForFen(keyMap2);
                keyCard.setProcInsId(procInsId2);
                keyCard.setType("2");
                keyCardService.saveOrUpdate(keyCard);
            }
        }


        mapper.updateById(report);
        return report;
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public EnrollmentRegistration update2(EnrollmentRegistration reportData) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        EnrollmentRegistration report = new EnrollmentRegistration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        mapper.updateById(report);
        return report;
    }

    public EnrollmentRegistration findById(String id) throws Exception {
        // 查询基础信息表
        EnrollmentRegistration info = mapper.getById(id);
        //根据用户查询岗位和角色信息
        if (ObjectUtil.isNotEmpty(info)) {
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(info.getUserId());
            ArrayList<String> roles = new ArrayList<>();
            ArrayList<String> posts = new ArrayList<>();
            if (userDTO != null) {
                if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())) {
                    for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                        roles.add(roleDTO.getId());
                    }
                }
                if (CollectionUtil.isNotEmpty(userDTO.getPostDTOList())) {
                    for (PostDTO postDTO : userDTO.getPostDTOList()) {
                        posts.add(postDTO.getId());
                    }
                }
                info.setNo(userDTO.getNo());
            }
            info.setRoleIdList(roles);
            info.setPostIdList(posts);

            String userId = info.getUserId();
            // 查询身份证正反面信息
            List<WorkAttachmentInfoDTO> idCardFront = mapper.findDtos(info.getIdCard(), "idCardFront");
            List<WorkAttachmentInfoDTO> idCardBack = mapper.findDtos(info.getIdCard(), "idCardBack");
            if (CollectionUtils.isNotEmpty(idCardFront)) {
                info.setIdCardFront(idCardFront);
            }
            if (CollectionUtils.isNotEmpty(idCardBack)) {
                info.setIdCardBack(idCardBack);
            }
            if(StringUtils.isNotBlank(userId)){
                //查询教育经历数据
                List<EnrollmentEduInfo> eduInfoList = eduInfoService.findByUserId(userId, "5");
                info.setEduInfoList(eduInfoList);

                //查询工作经历数据
                List<EnrollmentWorkInfo> workInfos = workInfoService.findByUserId(userId, "5");
                info.setWorkInfoList(workInfos);

                //查询培训经历数据
                List<EnrollmentTrainingInfo> trainingInfos = trainingInfoService.findByUserId(userId, "5");
                info.setTrainingInfoList(trainingInfos);

                //查询资质证书数据
                List<EnrollmentCertificateInfo> certificateInfoList = certificateInfoService.findByUserId(userId, "5");
                info.setCertificateInfoList(certificateInfoList);

                //查询专业技能数据
                List<EnrollmentSkillInfo> skillInfoList = skillInfoService.findByUserId(userId, "5");
                info.setSkillInfoList(skillInfoList);

                //查询语言能力数据
                List<EnrollmentLanguageInfo> languageInfoList = languageInfoService.findByUserId(userId, "5");
                info.setLanguageInfoList(languageInfoList);

                //查询家庭成员数据
                List<EnrollmentFamilyInfo> familyInfoList = familyInfoService.findByUserId(userId, "5");
                info.setFamilyInfoList(familyInfoList);

                //查询奖项信息
                List<EnrollmentRewardInfo> rewardInfoList = rewardInfoService.findByUserId(userId, "5");
                info.setRewardInfoList(rewardInfoList);

                //查询劳动合同
                List<EnrollmentLaborContractInfo> laborContractInfoList = laborContractInfoService.findByUserId(userId, "5");
                info.setLaborContractInfoList(laborContractInfoList);

                //查询社会及行业职务
                List<EnrollmentSocietyInfo> societyInfoList = societyInfoService.findByUserId(userId, "5");
                info.setSocietyInfoList(societyInfoList);

                //工作业绩
                List<EnrollmentPerformanceInfo> performanceInfoList = performanceInfoService.findByUserId(userId, "5");
                info.setPerformanceInfoList(performanceInfoList);
            }
        }

        return info;
    }

    public EnrollmentUserInfoAudit findAuditInfoById(String id,String status,String flag) {
        //EnrollmentUserInfoAudit info = userInfoAuditService.getById(id);
        EnrollmentUserInfoAudit info = userInfoAuditService.findAuditInfoById(id, flag);
        //if("1".equals(status)){
        //    status = "4";
        //}
        //根据身份证动态计算年龄
        String idCard = info.getIdCard();
        if (StringUtils.isNotBlank(idCard)) {
            int age = IdcardUtil.getAgeByIdCard(idCard);
            info.setAge(String.valueOf(age)); // 转成字符串
        }

        if (ObjectUtil.isNotEmpty(info)) {
            String idCardId = info.getId();
            // 查询身份证正反面信息
            if("1".equals(flag)){
                idCardId = info.getIdCard();
            }
            List<WorkAttachmentInfoDTO> idCardFront = mapper.findDtos(idCardId, "idCardFront");
            List<WorkAttachmentInfoDTO> idCardBack = mapper.findDtos(idCardId, "idCardBack");
            if (CollectionUtils.isNotEmpty(idCardFront)) {
                info.setIdCardFront(idCardFront);
            }
            if (CollectionUtils.isNotEmpty(idCardBack)) {
                info.setIdCardBack(idCardBack);
            }
            String userId = info.getUserId();
            //查询教育经历数据
            List<EnrollmentEduInfo> eduInfoList = eduInfoService.findByUserId(userId, status);
            info.setEduInfoList(eduInfoList);

            //查询工作经历数据
            List<EnrollmentWorkInfo> workInfos = workInfoService.findByUserId(userId, status);
            info.setWorkInfoList(workInfos);

            //查询培训经历数据
            List<EnrollmentTrainingInfo> trainingInfos = trainingInfoService.findByUserId(userId, status);
            info.setTrainingInfoList(trainingInfos);

            //查询资质证书数据
            List<EnrollmentCertificateInfo> certificateInfoList = certificateInfoService.findByUserId(userId, status);
            info.setCertificateInfoList(certificateInfoList);

            //查询专业技能数据
            List<EnrollmentSkillInfo> skillInfoList = skillInfoService.findByUserId(userId, status);
            info.setSkillInfoList(skillInfoList);

            //查询语言能力数据
            List<EnrollmentLanguageInfo> languageInfoList = languageInfoService.findByUserId(userId, status);
            info.setLanguageInfoList(languageInfoList);

            //查询家庭成员数据
            List<EnrollmentFamilyInfo> familyInfoList = familyInfoService.findByUserId(userId, status);
            info.setFamilyInfoList(familyInfoList);

            //查询奖项信息
            List<EnrollmentRewardInfo> rewardInfoList = rewardInfoService.findByUserId(userId, status);
            info.setRewardInfoList(rewardInfoList);

            //查询劳动合同
            List<EnrollmentLaborContractInfo> laborContractInfoList = laborContractInfoService.findByUserId(userId, "5");
            info.setLaborContractInfoList(laborContractInfoList);

            //查询社会及行业职务
            List<EnrollmentSocietyInfo> societyInfoList = societyInfoService.findByUserId(userId, status);
            info.setSocietyInfoList(societyInfoList);

            //工作业绩
            List<EnrollmentPerformanceInfo> performanceInfoList = performanceInfoService.findByUserId(userId, status);
            info.setPerformanceInfoList(performanceInfoList);
        }
        return info;
    }

    public Integer findByUserId(String userId) throws Exception {
        QueryWrapper<EnrollmentRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("del_flag", 0);
        // 删除基础信息表
        Integer integer = mapper.selectCount(queryWrapper);
        return integer;
    }

    public EnrollmentRegistration findInfoByUserId(String id) throws Exception {
        // 查询基础信息表
        EnrollmentRegistration info = mapper.getInfoByUserId(id);
        //根据身份证动态计算年龄
        String idCard = info.getIdCard();
        if (StringUtils.isNotBlank(idCard)) {
            int age = IdcardUtil.getAgeByIdCard(idCard);
            info.setAge(String.valueOf(age)); // 转成字符串
        }
        //根据用户查询岗位和角色信息
        if (ObjectUtil.isNotEmpty(info)) {
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(info.getUserId());
            ArrayList<String> roles = new ArrayList<>();
            ArrayList<String> posts = new ArrayList<>();
            if (userDTO != null) {
                if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())) {
                    for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                        roles.add(roleDTO.getId());
                    }
                }
                if (CollectionUtil.isNotEmpty(userDTO.getPostDTOList())) {
                    for (PostDTO postDTO : userDTO.getPostDTOList()) {
                        posts.add(postDTO.getId());
                    }
                }
            }
            info.setRoleIdList(roles);
            info.setPostIdList(posts);

            // 查询身份证正反面信息
            List<WorkAttachmentInfoDTO> idCardFront = mapper.findDtos(info.getIdCard(), "idCardFront");
            List<WorkAttachmentInfoDTO> idCardBack = mapper.findDtos(info.getIdCard(), "idCardBack");
            if (CollectionUtils.isNotEmpty(idCardFront)) {
                info.setIdCardFront(idCardFront);
            }
            if (CollectionUtils.isNotEmpty(idCardBack)) {
                info.setIdCardBack(idCardBack);
            }

            String userId = info.getUserId();
            //查询教育经历数据
            List<EnrollmentEduInfo> eduInfoList = eduInfoService.findByUserId(userId, "1");
            info.setEduInfoList(eduInfoList);

            //查询工作经历数据
            List<EnrollmentWorkInfo> workInfos = workInfoService.findByUserId(userId, "1");
            info.setWorkInfoList(workInfos);

            //查询培训经历数据
            List<EnrollmentTrainingInfo> trainingInfos = trainingInfoService.findByUserId(userId, "1");
            info.setTrainingInfoList(trainingInfos);

            //查询资质证书数据
            List<EnrollmentCertificateInfo> certificateInfoList = certificateInfoService.findByUserId(userId, "1");
            info.setCertificateInfoList(certificateInfoList);

            //查询专业技能数据
            List<EnrollmentSkillInfo> skillInfoList = skillInfoService.findByUserId(userId, "1");
            info.setSkillInfoList(skillInfoList);

            //查询语言能力数据
            List<EnrollmentLanguageInfo> languageInfoList = languageInfoService.findByUserId(userId, "1");
            info.setLanguageInfoList(languageInfoList);

            //查询家庭成员数据
            List<EnrollmentFamilyInfo> familyInfoList = familyInfoService.findByUserId(userId, "1");
            info.setFamilyInfoList(familyInfoList);

            //查询奖项信息
            List<EnrollmentRewardInfo> rewardInfoList = rewardInfoService.findByUserId(userId, "1");
            info.setRewardInfoList(rewardInfoList);

            //查询劳动合同
            List<EnrollmentLaborContractInfo> laborContractInfoList = laborContractInfoService.findByUserId(userId, "5");
            info.setLaborContractInfoList(laborContractInfoList);

            //查询社会及行业职务
            List<EnrollmentSocietyInfo> societyInfoList = societyInfoService.findByUserId(userId, "1");
            info.setSocietyInfoList(societyInfoList);

            //工作业绩
            List<EnrollmentPerformanceInfo> performanceInfoList = performanceInfoService.findByUserId(userId, "1");
            info.setPerformanceInfoList(performanceInfoList);
        }

        return info;
    }

    public void updateStatusById(EnrollmentRegistration dto) {
        EnrollmentRegistration registration = mapper.getById(dto.getId());
        mapper.updateStatusById(dto.getId(), dto.getType());
        //判断流程的类型  是入职登记流程 还是 个人信息完善流程
        if (StringUtils.isNotBlank(registration.getProcessType()) && registration.getProcessType().equals("0")) {
            //说明是入职登记流程  这时删除入职登记相关信息
            mapper.deleteByIdOnPhysic(dto.getId());

        }


    }

    public String remove(String id) {
        //先删除用户表中的信息
        EnrollmentRegistration registration = mapper.getById(id);
        if (registration != null) {
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByMobile(registration.getMobilePhone());
            //设置角色
            if (userDTO != null) {
                SpringUtil.getBean(IUserApi.class).deleteById(userDTO.getId());
                String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue("dd_status", "dd_status", "0");
                if ("1".equals(dictValue)) {
                    //删除钉钉表中的数据
                    //判断用户是否为 评估 或者 会计 员工
                    if (userDTO.getTenantDTO().getId().equals("10003") || userDTO.getTenantDTO().getId().equals("10001")) {
                        DingTalkUserDTO dingTalkUserDTO = new DingTalkUserDTO();
                        dingTalkUserDTO.setUserid(userDTO.getDdId());
                        dingTalkUtils.deleteUser(dingTalkUserDTO, userDTO.getTenantDTO().getId());
                    }
                }

            }
        }
        // 删除基础信息表
        mapper.removeById(id);
        return "操作成功";
    }

    public Integer findIdCardOnly(String idCard, String userId) throws Exception {
        QueryWrapper<EnrollmentRegistration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", idCard);
        queryWrapper.eq("del_flag", 0);
        if (StringUtils.isNotBlank(userId)) {
            queryWrapper.ne("user_id", userId);
        }
        // 删除基础信息表
        Integer integer = mapper.selectCount(queryWrapper);
        return integer;
    }
    public String findIdCardByUserId(String id) throws Exception {
        // 查询基础信息表
        EnrollmentRegistration info = mapper.getInfoByUserId(id);
        if(info!= null && StringUtils.isNotBlank(info.getIdCard())){
            return info.getIdCard();
        }
        return "";
    }


    public Integer findMobilePhoneOnly(String mobilePhone) throws Exception {
        // 删除基础信息表
        Integer integer = SpringUtil.getBean(IUserApi.class).selectCountByMobile(mobilePhone);
        return integer;
    }

    public Integer findMobilePhoneOnlyByTenantId(String mobilePhone,String tenantId,String userId) throws Exception {
        // 删除基础信息表
        Integer integer = SpringUtil.getBean(IUserApi.class).selectCountByMobileByTenantId(mobilePhone,tenantId,userId);
        return integer;
    }

    /**
     * 获取正式工在职状态为离职的，并且user表中未删除的
     *
     * @return
     */
    public List<EnrollmentRegistration> getFormalUserInfo() {
        return mapper.getFormalUserInfo();
    }

    /**
     * 保存身份证照片
     *
     * @param reportData
     * @throws ApiException
     */
    public void updateIdCard(EnrollmentRegistration reportData) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        IWorkAttachmentApi workAttachmentApi = SpringUtil.getBean(IWorkAttachmentApi.class);
        SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(reportData.getIdCard());
        saveAttachments(reportData.getIdCardFront(), "idCardFront", reportData.getIdCard(), userDTO, workAttachmentApi);
        saveAttachments(reportData.getIdCardBack(), "idCardBack", reportData.getIdCard(), userDTO, workAttachmentApi);
    }

    private void saveAttachments(List<WorkAttachmentInfoDTO> attachmentList, String flag, String attachmentId, UserDTO userDTO, IWorkAttachmentApi workAttachmentApi) {
        if (ObjectUtil.isEmpty(attachmentList)) return;
        AtomicInteger sort = new AtomicInteger(1);
        for (WorkAttachmentInfoDTO item : attachmentList) {
            WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
            workAttachmentDto.setName(item.getName());
            workAttachmentDto.setSize(item.getSize());
            workAttachmentDto.setUrl(item.getUrl());
            Map<String, String> map = new HashMap<>();
            map.put("workAttachmentDtoInfo", JSON.toJSONString(workAttachmentDto));
            map.put("userDTOInfo", JSON.toJSONString(userDTO));
            map.put("attachmentId", attachmentId);
            map.put("attachmentFlag", flag);
            map.put("sortInfo", String.valueOf(sort.getAndIncrement()));
            workAttachmentApi.saveFile(map);
        }
    }

    /**
     * 将用户信息备份保存并设为审核状态
     *
     * @param registrationData
     */
    public void updateInfoAudit(EnrollmentRegistration registrationData) {
         try {
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            EnrollmentUserInfoAudit enrollmentUserInfoAudit = new EnrollmentUserInfoAudit();
            String id = UUID.randomUUID().toString().replace("-", "");
            BeanUtils.copyProperties(registrationData, enrollmentUserInfoAudit);
            enrollmentUserInfoAudit.setStatus("2");
            if (!"4".equals(registrationData.getStatus()) && !"1".equals(registrationData.getStatus())) {
                enrollmentUserInfoAudit.setId(id);
                enrollmentUserInfoAudit.setRegistrationId(registrationData.getId());
            } else {
                enrollmentUserInfoAudit.setId(registrationData.getId());
                enrollmentUserInfoAudit.setRegistrationId(registrationData.getRegistrationId());
            }
            //发起员工信息审批流程
            Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("员工信息审批");
            String procDefId = map.get("id") + "";
            enrollmentUserInfoAudit.setProcessDefinitionId(procDefId);
            userInfoAuditService.saveOrUpdate(enrollmentUserInfoAudit);
            Map<String, Map<String, String>> allMap = new HashMap<>();
            String procDefKey = map.get("key") + "";
            String businessTable = "human_resources_enrollment_user_info_audit";
            String businessId = enrollmentUserInfoAudit.getId();
            String title = enrollmentUserInfoAudit.getName() + "发起了- [" + enrollmentUserInfoAudit.getName() + "员工信息完善]";
            //根据角色查用户信息
            RoleDTO roleDTO = SpringUtil.getBean(IRoleApi.class).getRoleDTOByName2("实习信息审核员");
            String assignee = getAssignee(roleDTO.getId());
            String recordType = "";
            Map<String, String> newMap = pingMap(procDefId, procDefKey, businessTable, businessId, title,assignee, recordType);
            newMap.put("userId",registrationData.getUserId());
            allMap.put("员工信息审批", newMap);
            SpringUtil.getBean(IFlowableApi.class).startForFenNew(allMap);
            //更新提交审批的时间
            mapper.updateApprovalTime(registrationData.getUserId());
            if (!"4".equals(registrationData.getStatus()) ) {
                IWorkAttachmentApi workAttachmentApi = SpringUtil.getBean(IWorkAttachmentApi.class);
                SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(enrollmentUserInfoAudit.getId());
                saveAttachments(enrollmentUserInfoAudit.getIdCardFront(), "idCardFront", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);
                saveAttachments(enrollmentUserInfoAudit.getIdCardBack(), "idCardBack", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);
                //saveEnrollmentDetailInfo(registrationData);
                updateEnrollmentDetailInfo(registrationData,"2","approval");
            } else {
                IWorkAttachmentApi workAttachmentApi = SpringUtil.getBean(IWorkAttachmentApi.class);
                SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(enrollmentUserInfoAudit.getId());
                saveAttachments(enrollmentUserInfoAudit.getIdCardFront(), "idCardFront", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);
                saveAttachments(enrollmentUserInfoAudit.getIdCardBack(), "idCardBack", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);
                updateEnrollmentDetailInfo(registrationData,"2","approval");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 用户暂存信息
     *
     * @param registrationData
     */
    public void updateInfoTemporary(EnrollmentRegistration registrationData) {
        try {
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            EnrollmentUserInfoAudit enrollmentUserInfoAudit = new EnrollmentUserInfoAudit();
            String id = UUID.randomUUID().toString().replace("-", "");
            BeanUtils.copyProperties(registrationData, enrollmentUserInfoAudit);
            enrollmentUserInfoAudit.setStatus("1");
            if (!"4".equals(registrationData.getStatus()) && !"1".equals(registrationData.getStatus())) {
                enrollmentUserInfoAudit.setId(id);
                enrollmentUserInfoAudit.setRegistrationId(registrationData.getId());
            } else {
                enrollmentUserInfoAudit.setId(registrationData.getId());
                enrollmentUserInfoAudit.setRegistrationId(registrationData.getRegistrationId());
            }
            userInfoAuditService.saveOrUpdate(enrollmentUserInfoAudit);
            //更新提交审批的时间
            mapper.updateApprovalTime(registrationData.getUserId());
                IWorkAttachmentApi workAttachmentApi = SpringUtil.getBean(IWorkAttachmentApi.class);
                SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(enrollmentUserInfoAudit.getId());
                saveAttachments(enrollmentUserInfoAudit.getIdCardFront(), "idCardFront", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);
                saveAttachments(enrollmentUserInfoAudit.getIdCardBack(), "idCardBack", enrollmentUserInfoAudit.getId(), userDTO, workAttachmentApi);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveEnrollmentDetailInfo(EnrollmentRegistration dto) {
        // 教育经历
        List<EnrollmentEduInfo> eduList = dto.getEduInfoList();
        if (CollectionUtils.isNotEmpty(eduList)) {
            eduList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                eduInfoService.add(item);
            });
        }

        // 工作经历
        List<EnrollmentWorkInfo> workList = dto.getWorkInfoList();
        if (CollectionUtils.isNotEmpty(workList)) {
            workList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                workInfoService.add(item);
            });
        }

        // 培训经历
        List<EnrollmentTrainingInfo> trainingList = dto.getTrainingInfoList();
        if (CollectionUtils.isNotEmpty(trainingList)) {
            trainingList.forEach(item -> item.setStatus("2"));
            trainingList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                trainingInfoService.add(item);
            });
        }

        // 资质证书
        List<EnrollmentCertificateInfo> certificateList = dto.getCertificateInfoList();
        if (CollectionUtils.isNotEmpty(certificateList)) {
            certificateList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                certificateInfoService.add(item);
            });
        }

        // 专业技能
        List<EnrollmentSkillInfo> skillList = dto.getSkillInfoList();
        if (CollectionUtils.isNotEmpty(skillList)) {
            skillList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                skillInfoService.add(item);
            });
        }

        // 语言能力
        List<EnrollmentLanguageInfo> languageList = dto.getLanguageInfoList();
        if (CollectionUtils.isNotEmpty(languageList)) {
            languageList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                languageInfoService.add(item);
            });

        }

        // 家庭成员
        List<EnrollmentFamilyInfo> familyList = dto.getFamilyInfoList();
        if (CollectionUtils.isNotEmpty(familyList)) {
            familyList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                familyInfoService.add(item);
            });
        }

        // 奖项信息
        List<EnrollmentRewardInfo> rewardList = dto.getRewardInfoList();
        if (CollectionUtils.isNotEmpty(rewardList)) {
            rewardList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                rewardInfoService.add(item);
            });
        }


        // 社会及行业职务
        List<EnrollmentSocietyInfo> societyInfoList = dto.getSocietyInfoList();
        if (CollectionUtils.isNotEmpty(societyInfoList)) {
            societyInfoList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                societyInfoService.add(item);
            });
        }

        // 工作业绩
        List<EnrollmentPerformanceInfo> performanceInfoList = dto.getPerformanceInfoList();
        if (CollectionUtils.isNotEmpty(performanceInfoList)) {
            performanceInfoList.forEach(item -> {
                item.setId("");
                item.setStatus("2");
                performanceInfoService.add(item);
            });
        }
    }

    public void updateEnrollmentDetailInfo(EnrollmentRegistration dto,String status,String flag) {

            // 教育经历
            List<EnrollmentEduInfo> eduList = dto.getEduInfoList();
            if (CollectionUtils.isNotEmpty(eduList)) {
                eduList.forEach(item -> {
                    item.setStatus(status);
                    eduInfoService.saveOrUpdate(item);
                    eduInfoService.saveOrUpdateEduWorkAttachment(item);
                });
            }

            // 工作经历
            List<EnrollmentWorkInfo> workList = dto.getWorkInfoList();
            if (CollectionUtils.isNotEmpty(workList)) {
                workList.forEach(item -> {
                    item.setStatus(status);
                    workInfoService.saveOrUpdate(item);
                });
            }

            // 培训经历
            List<EnrollmentTrainingInfo> trainingList = dto.getTrainingInfoList();
            if (CollectionUtils.isNotEmpty(trainingList)) {
                trainingList.forEach(item -> {
                    item.setStatus(status);
                    trainingInfoService.saveOrUpdate(item);
                    trainingInfoService.saveOrUpdateWorkAttachment(item);
                });
            }

            // 资质证书
            List<EnrollmentCertificateInfo> certificateList = dto.getCertificateInfoList();
            if (CollectionUtils.isNotEmpty(certificateList)) {
                certificateList.forEach(item -> {
                    item.setStatus(status);
                    certificateInfoService.saveOrUpdate(item);
                    certificateInfoService.saveOrUpdateWorkAttachment(item);
                });
            }

            // 专业技能
            List<EnrollmentSkillInfo> skillList = dto.getSkillInfoList();
            if (CollectionUtils.isNotEmpty(skillList)) {
                skillList.forEach(item -> {
                    item.setStatus(status);
                    skillInfoService.saveOrUpdate(item);
                    skillInfoService.saveOrUpdateWorkAttachment(item);
                });
            }

            // 语言能力
            List<EnrollmentLanguageInfo> languageList = dto.getLanguageInfoList();
            if (CollectionUtils.isNotEmpty(languageList)) {
                languageList.forEach(item -> {
                    item.setStatus(status);
                    languageInfoService.saveOrUpdate(item);
                    languageInfoService.saveOrUpdateWorkAttachment(item);
                });

            }

            // 家庭成员
            List<EnrollmentFamilyInfo> familyList = dto.getFamilyInfoList();
            if (CollectionUtils.isNotEmpty(familyList)) {
                familyList.forEach(item -> {
                    item.setStatus(status);
                    familyInfoService.saveOrUpdate(item);
                });
            }

            // 奖项信息
            List<EnrollmentRewardInfo> rewardList = dto.getRewardInfoList();
            if (CollectionUtils.isNotEmpty(rewardList)) {
                rewardList.forEach(item -> {
                    item.setStatus(status);
                    rewardInfoService.saveOrUpdate(item);
                    rewardInfoService.saveOrUpdateWorkAttachment(item);
                });

            }

            // 社会及行业职务
            List<EnrollmentSocietyInfo> societyInfoList = dto.getSocietyInfoList();
            if (CollectionUtils.isNotEmpty(societyInfoList)) {
                societyInfoList.forEach(item -> {
                    item.setStatus(status);
                    societyInfoService.saveOrUpdate(item);
                });
            }

            // 工作业绩
            List<EnrollmentPerformanceInfo> performanceInfoList = dto.getPerformanceInfoList();
            if (CollectionUtils.isNotEmpty(performanceInfoList)) {
                performanceInfoList.forEach(item -> {
                    item.setStatus(status);
                    performanceInfoService.saveOrUpdate(item);
                });

            }
    }




    public void updateRegistration(EnrollmentRegistration reportData) throws ApiException {

        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        EnrollmentRegistration report = new EnrollmentRegistration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        //if (StringUtils.isBlank(reportData.getJoinIndustryDate())) {
        //    reportData.setJoinIndustryDate(null);
        //}
        //reportData.getJoinWorkDate()
        //if () {
        //    reportData.setJoinWorkDate(null);
        //}



        updateIdCard(reportData);

        String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue("dd_status", "dd_status", "0");
        if ("1".equals(dictValue)) {
            //钉钉逻辑
            //获取用户所在部门信息
            OfficeDTO officeDto = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getDepartment());
            String tenantId = officeDto.getTenantId();
            //判断用户是否为 评估 或者 会计 的公司
            if (tenantId.equals("10003") || tenantId.equals("10001")) {
                //获取钉钉所有部门信息
                List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponses = dingTalkUtils.deptList(tenantId);
                for (OapiV2DepartmentListsubResponse.DeptBaseResponse dept : deptBaseResponses) {
                    //找到用户所在的钉钉部门
                    if (officeDto.getName().equals(dept.getName())) {
                        // 相应逻辑
                        DingTalkUserDTO dingTalkUserDTO = new DingTalkUserDTO();
                        dingTalkUserDTO.setMobile(report.getMobilePhone());
                        dingTalkUserDTO.setName(report.getName());
                        dingTalkUserDTO.setDeptIdList(String.valueOf(dept.getDeptId()));
                        if (StringUtils.isNotBlank(report.getDdId())) {
                            dingTalkUserDTO.setUserid(report.getDdId());
                            dingTalkUtils.updateUser(dingTalkUserDTO, tenantId);
                        }
                        break;
                    }
                }
            }
            //钉钉逻辑
        }

        ////更新用户信息
        //String newPassword = report.getNewPassword();
        //String confirmNewPassword = report.getConfirmNewPassword();
        //String loginName = report.getLoginName();
        //UserDTO userDTO1 =  SpringUtil.getBean(IUserApi.class).getById(reportData.getUserId());
        //if((StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(confirmNewPassword)) || StringUtils.isNotBlank(loginName) ){
        //    if(StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(confirmNewPassword)){
        //        if (newPassword.equals(confirmNewPassword)){
        //            userDTO1.setId(reportData.getUserId());
        //            userDTO1.setPassword(SecurityUtils.encryptPassword(newPassword));
        //        }
        //    }
        //    userDTO1.setLoginName(loginName);
        //    SpringUtil.getBean(IUserApi.class).saveOrUpdate(userDTO1);
        //    UserUtils.deleteCache(userDTO1);
        //}

        updateIdCard(reportData);
        mapper.updateById(report);

        if (StringUtils.isNotBlank(report.getSocialSecurityNumber())) {
            LambdaQueryWrapper<EnrollmentSocialSecurityCard> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(EnrollmentSocialSecurityCard::getEnrollmentRegistrationId, report.getId())
                    .eq(EnrollmentSocialSecurityCard::getDelFlag, "0"); // 加上有效标志条件（如果有）
            EnrollmentSocialSecurityCard existing = securityCardService.getOne(queryWrapper);
            EnrollmentSocialSecurityCard securityCard = new EnrollmentSocialSecurityCard();
            String amountId = SnowFlake.getId();
            securityCard.setId(amountId);
            securityCard.setCreateById("1");
            securityCard.setCreateTime(new Date());
            securityCard.setUpdateById("1");
            securityCard.setUpdateTime(new Date());
            securityCard.setSocialSecurityNumber(report.getSocialSecurityNumber());
            securityCard.setSocialSecurityBankNumber(report.getSocialSecurityBankNumber());
            securityCard.setSocialSecurityPictureFront(report.getSocialSecurityPictureFront());
            securityCard.setSocialSecurityPictureOpposite(report.getSocialSecurityPictureOpposite());
            securityCard.setEnrollmentRegistrationId(report.getId());
            if (existing != null) {
                securityCard.setId(existing.getId());
                securityCardService.updateById(securityCard);
            } else {
                // 不存在，走 insert
                securityCardService.save(securityCard);
            }
            //socialSecurityCardMapper.insert(securityCard);
        }

        /**
         * 修改工资卡信息
         */
        //EnrollmentWageCard wageCard = new EnrollmentWageCard();
        //wageCard.setEnrollmentRegistrationId(report.getId());
        //wageCard.setId(report.getWageCardId());
        //wageCard.setAccountHolderFront(report.getAccountHolderFront());
        //wageCard.setAccountHolderOpposite(report.getAccountHolderOpposite());
        //wageCard.setZxAccountHolder(report.getZxAccountHolder());
        //wageCard.setGsAccountHolder(report.getGsAccountHolder());
        //wageCard.setGsAccountHolderFront(report.getGsAccountHolderFront());
        //wageCard.setGsAccountHolderOpposite(report.getGsAccountHolderOpposite());
        //wageCard.setZxBankCardNumber(report.getZxBankCardNumber());
        //wageCard.setGsBankCardNumber(report.getGsBankCardNumber());
        //wageCardService.saveOrUpdate(wageCard);


        //// 先根据 reg_id 查找是否已存在
        LambdaQueryWrapper<EnrollmentWageCard> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EnrollmentWageCard::getEnrollmentRegistrationId, report.getId())
                .eq(EnrollmentWageCard::getDelFlag, "0"); // 加上有效标志条件（如果有）
        EnrollmentWageCard existing = wageCardService.getOne(queryWrapper);
        EnrollmentWageCard wageCard = new EnrollmentWageCard();
        wageCard.setEnrollmentRegistrationId(report.getId());
        wageCard.setId(report.getWageCardId());
        wageCard.setAccountHolderFront(report.getAccountHolderFront());
        wageCard.setAccountHolderOpposite(report.getAccountHolderOpposite());
        wageCard.setZxAccountHolder(report.getZxAccountHolder());
        wageCard.setGsAccountHolder(report.getGsAccountHolder());
        wageCard.setGsAccountHolderFront(report.getGsAccountHolderFront());
        wageCard.setGsAccountHolderOpposite(report.getGsAccountHolderOpposite());
        wageCard.setZxBankCardNumber(report.getZxBankCardNumber());
        wageCard.setGsBankCardNumber(report.getGsBankCardNumber());
        if (existing != null) {
            wageCard.setId(existing.getId());
            wageCardService.updateById(wageCard);
        } else {
            // 不存在，走 insert
            wageCardService.save(wageCard);
        }

        /**
         * 修改用户信息
         */
        EnrollmentRegistration registration = mapper.getById(reportData.getId());
        if (StringUtils.isNotBlank(registration.getUserId())) {
            UserDTO dto = SpringUtil.getBean(IUserApi.class).getById(registration.getUserId());
            if (dto != null) {
                //往用户表中新增一条数据
                UserDTO dto1 = new UserDTO();
                dto1.setId(dto.getId());
                dto1.setName(report.getName());
                dto1.setLoginName(report.getName());
                dto1.setMobile(report.getMobilePhone());
                dto1.setNo(report.getMobilePhone());
                dto1.setPhoto("");
                //根据实习部门获取部门信息
                OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(registration.getDepartment());
                dto1.setOfficeDTO(officeDTO);
                OfficeDTO officeDTO1 = new OfficeDTO();
                officeDTO1.setId(officeDTO.getParent().getId());
                dto1.setCompanyDTO(officeDTO1);
                //角色和岗位信息
                List<RoleDTO> roleIdList = new ArrayList<>();
                List<PostDTO> postDTOList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(reportData.getPostIdList())) {
                    for (String post : reportData.getPostIdList()) {
                        PostDTO postDTO = new PostDTO();
                        postDTO.setId(post);
                        postDTOList.add(postDTO);
                    }
                }
                if (CollectionUtil.isNotEmpty(reportData.getRoleIdList())) {
                    for (String role : reportData.getRoleIdList()) {
                        RoleDTO roleDTO = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(role);
                        if(roleDTO!= null ){
                            roleIdList.add(roleDTO);
                        }
                    }
                }
                //所属租户
                TenantDTO tenantDTO = new TenantDTO();
                tenantDTO.setId(officeDTO.getTenantId());
                dto1.setTenantDTO(tenantDTO);
                //根据用户id查询其管理部门的id并插入
                if (null != reportData && StringUtils.isNotBlank(reportData.getId())) {
                    String manageOfficeIdsById = SpringUtil.getBean(IUserApi.class).getManageOfficeIdsById(reportData.getUserId());
                    if (StringUtils.isNotBlank(manageOfficeIdsById)) {
                        dto1.setManageOfficeIds(manageOfficeIdsById);
                    }
                }
                dto1.setRoleDTOList(roleIdList);
                dto1.setPostDTOList(postDTOList);
                dto1.setNo(reportData.getNo());
                SpringUtil.getBean(IUserApi.class).updateUser(dto1);
            }
        }

    }


    public void updateAuditRegistration(EnrollmentRegistration reportData) throws ApiException {

        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        EnrollmentRegistration report = new EnrollmentRegistration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        updateIdCard(reportData);

        String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue("dd_status", "dd_status", "0");
        if ("1".equals(dictValue)) {
            //钉钉逻辑
            //获取用户所在部门信息
            OfficeDTO officeDto = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getDepartment());
            String tenantId = officeDto.getTenantId();
            //判断用户是否为 评估 或者 会计 的公司
            if (tenantId.equals("10003") || tenantId.equals("10001")) {
                //获取钉钉所有部门信息
                List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponses = dingTalkUtils.deptList(tenantId);
                for (OapiV2DepartmentListsubResponse.DeptBaseResponse dept : deptBaseResponses) {
                    //找到用户所在的钉钉部门
                    if (officeDto.getName().equals(dept.getName())) {
                        // 相应逻辑
                        DingTalkUserDTO dingTalkUserDTO = new DingTalkUserDTO();
                        dingTalkUserDTO.setMobile(report.getMobilePhone());
                        dingTalkUserDTO.setName(report.getName());
                        dingTalkUserDTO.setDeptIdList(String.valueOf(dept.getDeptId()));
                        if (StringUtils.isNotBlank(report.getDdId())) {
                            dingTalkUserDTO.setUserid(report.getDdId());
                            dingTalkUtils.updateUser(dingTalkUserDTO, tenantId);
                        }
                        break;
                    }
                }
            }
            //钉钉逻辑
        }


        mapper.updateById(report);

        /**
         * 修改用户信息
         */
        EnrollmentRegistration registration = mapper.getById(reportData.getId());
        if (StringUtils.isNotBlank(registration.getUserId())) {
            UserDTO dto = SpringUtil.getBean(IUserApi.class).getById(registration.getUserId());
            if (dto != null) {
                //往用户表中新增一条数据
                UserDTO dto1 = new UserDTO();
                dto1.setId(dto.getId());
                dto1.setName(report.getName());
                dto1.setMobile(report.getMobilePhone());
                dto1.setNo(report.getMobilePhone());
                dto1.setPhoto("");
                SpringUtil.getBean(IUserApi.class).saveOrUpdate(dto1);
            }
        }

    }

    public void insertIntoEnrollmentRegistrationInfo(String value) {
        EnrollmentRegistration infos = JSON.parseObject(value, new TypeReference<EnrollmentRegistration>() {
        });
        mapper.insert(infos);
    }

    public List<String> getAllUserIdInSuccess() {
        return mapper.getAllUserIdInSuccess();
    }

    /**
     * 用户新增时对入职信息进行同步
     *
     * @param registration
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(EnrollmentRegistration registration) {
        //现根据userId查询入职信息
        if (StringUtils.isNotBlank(registration.getUserId())) {
            registration.setType("5");
            registration.setOnJobStatus("2");
            EnrollmentRegistration enrollmentRegistration = mapper.getByUserId(registration.getUserId());
            if (enrollmentRegistration != null) {
                registration.setId(enrollmentRegistration.getId());
                mapper.updateById(registration);
            } else {
                registration.setId(SnowFlake.getId());
                mapper.insert(registration);
            }


        }

    }

    /**
     * 根据用户id删除用户信息
     *
     * @param id
     */
    public void delByUserId(String id) {
        mapper.delByUserId(id);
    }

    /**
     * 添加导入的用户信息
     *
     * @param staffUserInfoDTO
     */
    public void updateInfo(EnrollmentRegistration staffUserInfoDTO) {
        if (ObjectUtil.isNotEmpty(staffUserInfoDTO)) {
            if (StringUtils.isNotBlank(staffUserInfoDTO.getMobilePhone())) {
                //根据手机号查询信息
                EnrollmentRegistration registration = mapper.getByMobile(staffUserInfoDTO.getMobilePhone());
                if (ObjectUtil.isNotEmpty(registration)) {
                    if (registration.getName().equals(staffUserInfoDTO.getName())) {
                        registration.setSex(staffUserInfoDTO.getSex());//性别
                        registration.setBirthday(staffUserInfoDTO.getBirthday());//生日
                        registration.setAge(staffUserInfoDTO.getAge());//年龄
                        registration.setNativePlace(staffUserInfoDTO.getNativePlace());//籍贯
                        registration.setOnJobStatus(staffUserInfoDTO.getOnJobStatus());//正式
                        registration.setDepartment(staffUserInfoDTO.getDepartment());//所属部门
                        registration.setMobilePhone(staffUserInfoDTO.getMobilePhone());//联系电话
                        if (ObjectUtil.isNotEmpty(staffUserInfoDTO.getInDate())) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            String format = simpleDateFormat.format(staffUserInfoDTO.getInDate());
                            registration.setEntryDate(format);//入职时间
                        }
                        registration.setIdCard(staffUserInfoDTO.getIdCard());//身份证
                        mapper.updateById(registration);
                        if (com.jeeplus.utils.StringUtils.isNotBlank(staffUserInfoDTO.getRole()) && staffUserInfoDTO.getRole().contains(",")) {
                            if (StringUtils.isNotBlank(registration.getUserId())) {
                                UserDTO dto = SpringUtil.getBean(IUserApi.class).getById(registration.getUserId());
                                List<RoleDTO> roleIdList = new ArrayList<>();
                                String[] split = staffUserInfoDTO.getRole().split(",");
                                for (String s : split) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    hashMap.put("name", s);
                                    hashMap.put("tenantId", dto.getTenantDTO().getId());
                                    List<RoleDTO> roleDTOS = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(hashMap);
                                    roleIdList.addAll(roleDTOS);
                                }
                                dto.setRoleDTOList(roleIdList);
                                //根据实习部门获取部门信息
                                OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(staffUserInfoDTO.getDepartment());
                                dto.setOfficeDTO(officeDTO);
                                OfficeDTO officeDTO1 = new OfficeDTO();
                                officeDTO1.setId(officeDTO.getParent().getId());
                                dto.setCompanyDTO(officeDTO1);
                                TenantDTO tenantDTO = new TenantDTO();
                                tenantDTO.setId(officeDTO.getTenantId());
                                dto.setTenantDTO(tenantDTO);
                                SpringUtil.getBean(IUserApi.class).saveOrUpdate(dto);
                            }
                        }
                    }
                } else {
                    //入职id
                    String id = SnowFlake.getId();
                    EnrollmentRegistration enrollmentRegistration = new EnrollmentRegistration();
                    enrollmentRegistration.setId(id);
                    enrollmentRegistration.setCreateById("1");
                    enrollmentRegistration.setCreateTime(new Date());
                    enrollmentRegistration.setUpdateById("1");
                    enrollmentRegistration.setUpdateTime(new Date());
                    enrollmentRegistration.setName(staffUserInfoDTO.getName());
                    enrollmentRegistration.setSex(staffUserInfoDTO.getSex());//性别
                    enrollmentRegistration.setBirthday(staffUserInfoDTO.getBirthday());//生日
                    enrollmentRegistration.setAge(staffUserInfoDTO.getAge());//年龄
                    enrollmentRegistration.setNativePlace(staffUserInfoDTO.getNativePlace());//籍贯
                    enrollmentRegistration.setOnJobStatus(staffUserInfoDTO.getOnJobStatus());//正式
                    enrollmentRegistration.setDepartment(staffUserInfoDTO.getDepartment());//所属部门
                    enrollmentRegistration.setMobilePhone(staffUserInfoDTO.getMobilePhone());//联系电话
                    if (ObjectUtil.isNotEmpty(staffUserInfoDTO.getInDate())) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String format = simpleDateFormat.format(staffUserInfoDTO.getInDate());
                        enrollmentRegistration.setEntryDate(format);//入职时间
                    }
                    enrollmentRegistration.setIdCard(staffUserInfoDTO.getIdCard());//身份证
                    enrollmentRegistration.setType("5");//状态
                    //根据手机号查询用户信息
                    UserDTO dto = SpringUtil.getBean(IUserApi.class).getByMobile(staffUserInfoDTO.getMobilePhone());

                    //新增用户信息
                    UserDTO dto1 = new UserDTO();
                    if (ObjectUtil.isNotEmpty(dto)) {
                        enrollmentRegistration.setUserId(dto.getId());
                        BeanUtils.copyProperties(dto, dto1);
                    } else {
                        //生成一个用户id
                        String userId = SnowFlake.getId();
                        enrollmentRegistration.setUserId(userId);
                        dto1.setId(userId);
                        dto1.setName(staffUserInfoDTO.getName());
                        dto1.setLoginName(staffUserInfoDTO.getName());
                        dto1.setMobile(staffUserInfoDTO.getMobilePhone());
                        dto1.setNo(staffUserInfoDTO.getMobilePhone());
                        dto1.setPhoto("");
                        //根据实习部门获取部门信息
                        OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(staffUserInfoDTO.getDepartment());
                        dto1.setOfficeDTO(officeDTO);
                        OfficeDTO officeDTO1 = new OfficeDTO();
                        officeDTO1.setId(officeDTO.getParent().getId());
                        dto1.setCompanyDTO(officeDTO1);
                        TenantDTO tenantDTO = new TenantDTO();
                        tenantDTO.setId(officeDTO.getTenantId());
                        dto1.setTenantDTO(tenantDTO);
                    }
                    if (com.jeeplus.utils.StringUtils.isNotBlank(staffUserInfoDTO.getRole()) && staffUserInfoDTO.getRole().contains(",")) {
                        List<RoleDTO> roleIdList = new ArrayList<>();
                        String[] split = staffUserInfoDTO.getRole().split(",");
                        for (String s : split) {
                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("name", s);
                            hashMap.put("tenantId", dto.getTenantDTO().getId());
                            List<RoleDTO> roleDTOS = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(hashMap);
                            roleIdList.addAll(roleDTOS);
                        }
                        dto1.setRoleDTOList(roleIdList);
                    }
                    SpringUtil.getBean(IUserApi.class).saveOrUpdate(dto1);
                    mapper.insert(enrollmentRegistration);
                }
            }
        }

    }

    public void updateDdIdById(EnrollmentRegistration registration) {
        mapper.updateDdIdById(registration);
    }


    public List<EnrollmentRegistration> getUserInfoByIds(List<String> ids, String type) {
        List<EnrollmentRegistration> enrollmentRegistrations = new ArrayList<>();
        for (String id : ids) {
            EnrollmentRegistration info = mapper.getById(id);
            if (ObjectUtil.isNotEmpty(info)) {
                String userId = info.getUserId();
                switch (type) {
                    case "1"://身份证
                        List<WorkAttachmentInfoDTO> idCardFront = mapper.findDtos(info.getIdCard(), "idCardFront");
                        List<WorkAttachmentInfoDTO> idCardBack = mapper.findDtos(info.getIdCard(), "idCardBack");
                        if (CollectionUtils.isNotEmpty(idCardFront)) {
                            info.setIdCardFront(idCardFront);
                        }
                        if (CollectionUtils.isNotEmpty(idCardBack)) {
                            info.setIdCardBack(idCardBack);
                        }
                        break;
                    case "2"://学历
                    case "3"://学位
                        List<EnrollmentEduInfo> eduInfoList = eduInfoService.findByUserId(userId, "5");
                        info.setEduInfoList(eduInfoList);
                        break;
                    case "4"://培训
                        List<EnrollmentTrainingInfo> trainingInfos = trainingInfoService.findByUserId(userId, "5");
                        info.setTrainingInfoList(trainingInfos);
                        break;
                    case "5"://资质
                        List<EnrollmentCertificateInfo> certificateInfoList = certificateInfoService.findByUserId(userId, "5");
                        info.setCertificateInfoList(certificateInfoList);
                        break;
                    case "6"://技能
                        List<EnrollmentSkillInfo> skillInfoList = skillInfoService.findByUserId(userId, "5");
                        info.setSkillInfoList(skillInfoList);
                        break;
                    case "7"://语言
                        List<EnrollmentLanguageInfo> languageInfoList = languageInfoService.findByUserId(userId, "5");
                        info.setLanguageInfoList(languageInfoList);
                        break;
                    case "8"://表彰
                        List<EnrollmentRewardInfo> rewardInfoList = rewardInfoService.findByUserId(userId, "5");
                        info.setRewardInfoList(rewardInfoList);
                        break;
                    case "9"://劳动合同
                        List<EnrollmentLaborContractInfo> laborContractInfoList = laborContractInfoService.findByUserId(userId, "5");
                        info.setLaborContractInfoList(laborContractInfoList);
                        break;
                    default:
                        break;
                }
                enrollmentRegistrations.add(info);

            }
        }
        return enrollmentRegistrations;
    }

    public void updateStatusByIdUserInfo(EnrollmentRegistration registrationData,String flag) {
        try {
            EnrollmentUserInfoAudit enrollmentUserInfoAudit = new EnrollmentUserInfoAudit();
            enrollmentUserInfoAudit.setStatus("4");
            enrollmentUserInfoAudit.setId(registrationData.getId());
            enrollmentUserInfoAudit.setProcInsId("");
            enrollmentUserInfoAudit.setProcessDefinitionId("");
            enrollmentUserInfoAudit.setRegistrationId(registrationData.getRegistrationId());
            userInfoAuditService.saveOrUpdate(enrollmentUserInfoAudit);
            //更新提交审批的时间
            mapper.updateApprovalTime(registrationData.getUserId());
            updateEnrollmentDetailInfo(registrationData,"4",flag);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateInfoStatus(EnrollmentRegistration info) {
        try {
            String type = info.getType();
            switch (type){
                case "1":
                    EnrollmentEduInfo enrollmentEduInfo = new EnrollmentEduInfo();
                    enrollmentEduInfo.setId(info.getId());
                    enrollmentEduInfo.setStatus(info.getStatus());
                    eduInfoService.updateById(enrollmentEduInfo);
                    break;
                case "2":
                    EnrollmentWorkInfo workInfo = new EnrollmentWorkInfo();
                    workInfo.setId(info.getId());
                    workInfo.setStatus(info.getStatus());
                    workInfoService.updateById(workInfo);
                    break;
                case "3":
                    EnrollmentTrainingInfo trainingInfo = new EnrollmentTrainingInfo();
                    trainingInfo.setId(info.getId());
                    trainingInfo.setStatus(info.getStatus());
                    trainingInfoService.updateById(trainingInfo);
                    break;
                case "4":
                    EnrollmentCertificateInfo certificateInfo = new EnrollmentCertificateInfo();
                    certificateInfo.setId(info.getId());
                    certificateInfo.setStatus(info.getStatus());
                    certificateInfoService.updateById(certificateInfo);
                    break;
                case "5":
                    EnrollmentSkillInfo skillInfo = new EnrollmentSkillInfo();
                    skillInfo.setId(info.getId());
                    skillInfo.setStatus(info.getStatus());
                    skillInfoService.updateById(skillInfo);
                    break;
                case "6":
                    EnrollmentLanguageInfo enrollmentLanguageInfo = new EnrollmentLanguageInfo();
                    enrollmentLanguageInfo.setId(info.getId());
                    enrollmentLanguageInfo.setStatus(info.getStatus());
                    languageInfoService.updateById(enrollmentLanguageInfo);
                    break;
                case "7":
                    EnrollmentFamilyInfo enrollmentFamilyInfo = new EnrollmentFamilyInfo();
                    enrollmentFamilyInfo.setId(info.getId());
                    enrollmentFamilyInfo.setStatus(info.getStatus());
                    familyInfoService.updateById(enrollmentFamilyInfo);
                    break;
                case "8":
                    EnrollmentRewardInfo enrollmentRewardInfo = new EnrollmentRewardInfo();
                    enrollmentRewardInfo.setId(info.getId());
                    enrollmentRewardInfo.setStatus(info.getStatus());
                    rewardInfoService.updateById(enrollmentRewardInfo);
                    break;
                case "9":
                    EnrollmentSocietyInfo enrollmentSocietyInfo = new EnrollmentSocietyInfo();
                    enrollmentSocietyInfo.setId(info.getId());
                    enrollmentSocietyInfo.setStatus(info.getStatus());
                    societyInfoService.updateById(enrollmentSocietyInfo);
                    break;
                case "10":
                    EnrollmentPerformanceInfo enrollmentPerformanceInfo = new EnrollmentPerformanceInfo();
                    enrollmentPerformanceInfo.setId(info.getId());
                    enrollmentPerformanceInfo.setStatus(info.getStatus());
                    performanceInfoService.updateById(enrollmentPerformanceInfo);
                    break;
                default:

                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




    /**
     * 批量下载附件压缩包
     *
     * @param ids
     * @param attachmentType
     * @param response
     * @throws Exception
     */
    public void downloadAttachmentByUserIds(List<String> ids, String attachmentType, HttpServletResponse response) throws Exception {
        //根据id获取用户信息
        List<EnrollmentRegistration> enrollmentRegistrations = getUserInfoByIds(ids, attachmentType);
        if (enrollmentRegistrations.isEmpty()) {
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_OK); // 可选
            response.getWriter().write("{\"code\":400,\"msg\":\"所选用户未查询到附件信息，无法下载\"}");
            return;
        }
        // 临时路径
        String baseDir = "";
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            baseDir = "D:\\attachment-file";
        } else {
            baseDir = "/attachment-file/";
        }
        String tempDir = baseDir + File.separator + UUID.randomUUID();
        String zipPath = baseDir + File.separator + UUID.randomUUID() + ".zip";
        // 创建文件结构
        generateUserEducationFiles(enrollmentRegistrations, tempDir, attachmentType);
        // 压缩
        zipFolder(tempDir, zipPath);
        File zipFile = new File(zipPath);
        // 检查是否为空
        if (!zipFile.exists() || zipFile.length() == 0 || zipFile.length() == 22) {
            // 清理目录和空文件
            FileUtil.del(tempDir);
            zipFile.delete();
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("{\"code\":400,\"msg\":\"所选用户未查询到附件信息，无法下载\"}");
            return;
        }

        // 设置响应头并输出流
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=file.zip");
        response.setContentLength((int) zipFile.length());

        // 写入输出流
        try (FileInputStream fis = new FileInputStream(zipFile);
             BufferedInputStream bis = new BufferedInputStream(fis);
             ServletOutputStream sos = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer, 0, 1024)) != -1) {
                sos.write(buffer, 0, bytesRead);
            }
            sos.flush();
        }

        // 删除临时目录和 zip 文件
        FileUtil.del(tempDir);
        zipFile.delete();
    }


    /**
     * 数据处理逻辑
     *
     * @param userList
     * @param rootPath
     * @throws IOException
     */
    public void generateUserEducationFiles(List<EnrollmentRegistration> userList, String rootPath, String type) throws IOException {
        for (EnrollmentRegistration user : userList) {
            String userDir = rootPath + File.separator + user.getName();
            Files.createDirectories(Paths.get(userDir));
            switch (type) {
                case "1"://身份证
                    if (CollUtil.isNotEmpty(user.getIdCardFront())) {
                        for (WorkAttachmentInfoDTO idFront : user.getIdCardFront()) {
                            String fileName = "身份证正面." + FileUtil.extName(idFront.getName());
                            byte[] fileContent = downloadFile(idFront);
                            if (fileContent != null) {
                                Path filePath = Paths.get(userDir, fileName);
                                Files.write(filePath, fileContent);
                            }

                        }
                    }
                    if (CollUtil.isNotEmpty(user.getIdCardBack())) {
                        for (WorkAttachmentInfoDTO idBack : user.getIdCardBack()) {
                            String fileName = "身份证反面." + FileUtil.extName(idBack.getName());
                            byte[] fileContent = downloadFile(idBack);
                            if (fileContent != null) {
                                Path filePath = Paths.get(userDir, fileName);
                                Files.write(filePath, fileContent);
                            }
                        }
                    }
                    break;
                case "2"://学历
                    for (EnrollmentEduInfo info : user.getEduInfoList()) {
                        if (CollUtil.isNotEmpty(info.getEducationFile())) {
                            for (WorkAttachmentInfoDTO file : info.getEducationFile()) {
                                String fileName = info.getGraduatedFrom() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "3"://学位
                    for (EnrollmentEduInfo info : user.getEduInfoList()) {
                        if (CollUtil.isNotEmpty(info.getDegreeFile())) {
                            for (WorkAttachmentInfoDTO file : info.getDegreeFile()) {
                                String fileName = info.getGraduatedFrom() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "4"://培训
                    for (EnrollmentTrainingInfo info : user.getTrainingInfoList()) {
                        if (CollUtil.isNotEmpty(info.getFiles())) {
                            for (WorkAttachmentInfoDTO file : info.getFiles()) {
                                String fileName = info.getName() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "5"://资质
                    for (EnrollmentCertificateInfo info : user.getCertificateInfoList()) {
                        if (CollUtil.isNotEmpty(info.getCertificateAttachment())) {
                            for (WorkAttachmentInfoDTO file : info.getCertificateAttachment()) {
                                String sysCertType = SpringUtil.getBean(IDictApi.class).getDictLabel(info.getType(), "sys_cert_type", "文件");
                                String fileName = sysCertType + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "6"://技能
                    for (EnrollmentSkillInfo info : user.getSkillInfoList()) {
                        if (CollUtil.isNotEmpty(info.getFiles())) {
                            for (WorkAttachmentInfoDTO file : info.getFiles()) {
                                String fileName = info.getName() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "7"://语言
                    for (EnrollmentLanguageInfo info : user.getLanguageInfoList()) {
                        if (CollUtil.isNotEmpty(info.getFiles())) {
                            for (WorkAttachmentInfoDTO file : info.getFiles()) {
                                String fileName = info.getLanguage() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "8"://表彰
                    for (EnrollmentRewardInfo info : user.getRewardInfoList()) {
                        if (CollUtil.isNotEmpty(info.getFiles())) {
                            for (WorkAttachmentInfoDTO file : info.getFiles()) {
                                String fileName = info.getName() + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                case "9"://劳动合同
                    for (EnrollmentLaborContractInfo info : user.getLaborContractInfoList()) {
                        if (CollUtil.isNotEmpty(info.getFiles())) {
                            for (WorkAttachmentInfoDTO file : info.getFiles()) {
                                String typeName = SpringUtil.getBean(IDictApi.class).getDictLabel(info.getType(), "labor_contract_type", "文件");
                                String fileName = typeName + "." + FileUtil.extName(file.getName());
                                byte[] fileContent = downloadFile(file);
                                if (fileContent != null) {
                                    Path filePath = Paths.get(userDir, fileName);
                                    Files.write(filePath, fileContent);
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * 下载到本地
     *
     * @param workattachment
     * @return
     * @throws IOException
     */
    public byte[] downloadFile(WorkAttachmentInfoDTO workattachment) throws IOException {
        String aliyunUrl = "http://cdn.gangwaninfo.com";
        String aliDownloadUrl = "http://oss.gangwaninfo.com";
        String file = aliyunUrl + workattachment.getUrl();
        file = file.replace("amp;", "");
        String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
        String cons = "";
        if (file.contains(aliyunUrl)) {
            cons = aliyunUrl;
        } else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")) {
            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
        } else {
            cons = aliDownloadUrl;
        }
        String ossKey = file.split(cons + "/")[1];
        return SpringUtil.getBean(IWorkAttachmentApi.class).downBytesByStream(ossKey, fileName);
    }

    /**
     * 压缩方法
     *
     * @param sourceDirPath
     * @param zipPath
     * @throws IOException
     */
    public static void zipFolder(String sourceDirPath, String zipPath) throws IOException {
        Path zipFilePath = Paths.get(zipPath);
        Path sourcePath = Paths.get(sourceDirPath);

        try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
            Files.walk(sourcePath)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourcePath.relativize(path).toString());
                        try {
                            zs.putNextEntry(zipEntry);
                            Files.copy(path, zs);
                            zs.closeEntry();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
        }
    }

}
