package jnpf.personnels.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationResponse;
import io.seata.spring.annotation.GlobalTransactional;
import jnpf.account.PTenantAccountApi;
import jnpf.attendance.AttendanceDailyRuleApi;
import jnpf.attendance.dto.AttendanceUserGroupVo;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.authority.utils.PermissionsEnums;
import jnpf.authority.utils.PermissionsUtils;
import jnpf.base.ActionResult;
import jnpf.certificate.service.CertificateInstanceService;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.entity.StoreEntity;
import jnpf.enums.personnel.PersonnelFormDataSystemRosterFields;
import jnpf.enums.personnel.PhoneStatusEnum;
import jnpf.exception.LoginException;
import jnpf.model.certificate.vo.app.HealthCertificateDetailVO;
import jnpf.model.personnels.bo.FtbRosterImportConstants;
import jnpf.model.personnels.dto.contractinfo.ContactStatusInfo;
import jnpf.model.personnels.dto.emp.FtbEmpAddNewDTO;
import jnpf.model.personnels.dto.staff.field.*;
import jnpf.model.personnels.dto.staff.registerform.CheckRegisterFormFillDto;
import jnpf.model.personnels.dto.staff.registerform.GroupFieldDataDto;
import jnpf.model.personnels.dto.staff.registerform.ProbationPeriodDto;
import jnpf.model.personnels.dto.staff.registerform.WorkAddressDto;
import jnpf.model.personnels.dto.staff.roster.SaffRoleDto;
import jnpf.model.personnels.dto.staff.roster.WorkerGroupDataDto;
import jnpf.model.personnels.po.*;
import jnpf.model.personnels.req.registerform.SaveFormDataReq;
import jnpf.model.personnels.req.roster.UserAccountDto;
import jnpf.permission.V2UserApi;
import jnpf.permission.dto.SaveUserManagerAddDTO;
import jnpf.permission.dto.v2.UserBoundInfoDTO;
import jnpf.permission.dto.v2.user.SaveUserDTO;
import jnpf.permission.dto.v2.user.UpdateUserDTO;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.PositionEntity;
import jnpf.permission.entity.UserCopyEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.eum.v2.UserWorkStatusEnums;
import jnpf.permission.model.position.PositionGradesInfoVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.mapper.FtbPersonnelsStaffEmploymentApplyMapper;
import jnpf.personnels.mapper.FtbPersonnelsStaffRegistrationFormDataMapper;
import jnpf.personnels.mapper.FtbPersonnelsUchisuikePondMapper;
import jnpf.personnels.service.*;
import jnpf.personnels.utils.*;
import jnpf.salary.QuerySalaryApi;
import jnpf.util.AuthUtil;
import jnpf.util.FtbUtil;
import jnpf.util.RegexUtils;
import jnpf.util.UserProvider;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FtbPersonnelsStaffRegistrationFormDataServiceImpl extends ServiceImpl<FtbPersonnelsStaffRegistrationFormDataMapper, FtbPersonnelsStaffRegistrationFormData> implements FtbPersonnelsStaffRegistrationFormDataService {

    @Autowired
    private FtbPersonnelsRegistrationFormTypeService registrationFormTypeService;

    @Autowired
    private FtbPersonnelsRegistrationFormFieldService registrationFormFieldService;

    @Autowired
    private FtbPersonnelsStaffEmploymentApplyService staffEmploymentApplyService;

    @Autowired
    private FtbPersonnelsEmEntryService ftbPersonnelsEmEntryService;

    @Autowired
    private FtbPersonnelsStaffRosterService staffRosterService;

    @Autowired
    private FtbPersonnelsRegistrationFormFieldOptionService fieldOptionService;

    private final static String AFFILIATED_GROUP_NAME = "affiliated";

    @Autowired
    private PersonnelOrgUtils personnelOrgUtils;

    @Autowired
    private FtbPersonnelsAuditMasterConfigService auditMasterConfigService;

    @Resource
    private AttendanceGroupService attendanceGroupService;

    @Autowired
    private PersonnelAsyncServiceUtils personnelAsyncServiceUtils;

    @Autowired
    FtbPersonnelsStaffEmploymentApplyMapper applyMapper;

    @Autowired
    private AttendanceDailyRuleApi attendanceDailyRuleApi;

    @Autowired
    private Executor threadPoolExecutor;
    @Resource
    private QuerySalaryApi querySalaryApi;
    @Resource
    private FtbPersonnelsUchisuikePondMapper ftbPersonnelsUchisuikePondMapper;

    @Autowired
    PermissionsUtils permissionsUtils;

    @Autowired
    FtbPersonnlesIMUtils ftbPersonnlesIMUtils;

    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    V2UserApi v2UserApi;

    @Resource
    private AuthUtil authUtil;

    @Autowired
    private PTenantAccountApi pTenantAccountApi;

    @Resource
    private PersonnelIdCardVerificationUtils personnelIdCardVerificationUtils;
    @Resource
    private CertificateInstanceService certificateInstanceService;

    private static final String DEFAULT_USER_LOGO = "001.png";

    public static String getAffiliatedGroupName() {
        return AFFILIATED_GROUP_NAME;
    }

    private List<FtbPersonnelsRegistrationFormFieldOption> fillFieldOption(List<FormFieldDto> fieldList) {

        QueryWrapper<FtbPersonnelsRegistrationFormFieldOption> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbPersonnelsRegistrationFormFieldOption::getEnabledMark, 0)
                .notIn(FtbPersonnelsRegistrationFormFieldOption::getId, "301")
                .orderByAsc(FtbPersonnelsRegistrationFormFieldOption::getId);
        List<FtbPersonnelsRegistrationFormFieldOption> optionList = fieldOptionService.list(wrapper);
        if (CollectionUtil.isEmpty(optionList)) {
            return new ArrayList<>();
        }
        List<FtbPersonnelsRegistrationFormFieldOptionDto> optionDtoList = BeanUtil.copyToList(optionList, FtbPersonnelsRegistrationFormFieldOptionDto.class);
        //按照formFieldid 分组
        Map<String, List<FtbPersonnelsRegistrationFormFieldOptionDto>> fieldMap = optionDtoList.stream().collect(Collectors.groupingBy(FtbPersonnelsRegistrationFormFieldOptionDto::getFormFieldId));

        for (FormFieldDto formFieldDto : fieldList) {
            List<FtbPersonnelsRegistrationFormFieldOptionDto> dtoList = fieldMap.get(formFieldDto.getId());
            formFieldDto.setOptionDtoList(dtoList);
        }
        return optionList;
    }


    private List<GroupFieldDataDto> convertGroupFieldDataDto(List<FormFieldDto> formFieldDtoList, String affiliatedGroupData, String userId) {
        List<GroupFieldDataDto> retList = new ArrayList<>();
        List<FormFieldDto> groupList = new ArrayList<>();
        for (FormFieldDto formFieldDto : formFieldDtoList) {
            if (StringUtils.isNotEmpty(formFieldDto.getGroupName())) {
                groupList.add(formFieldDto);
            } else {
                if (CollectionUtil.isNotEmpty(groupList)) {
                    GroupFieldDataDto dto = new GroupFieldDataDto();
                    dto.setIsMulitField(true);
                    dto.setGroupFieldDtoList(personnelOrgUtils.buildMulitField(groupList, affiliatedGroupData, userId));
                    retList.add(dto);
                    dto.setGroupName(groupList.get(0).getGroupName());
                    groupList = new ArrayList<>();
                }
                GroupFieldDataDto dto = new GroupFieldDataDto();
                if ("phone".equals(formFieldDto.getId()) || "workAge".equals(formFieldDto.getId()) || "age".equals(formFieldDto.getId())) {
                    formFieldDto.setCurrIsUpdate(false);
                }
                dto.setFormFieldDto(formFieldDto);
                retList.add(dto);
            }
        }
        return retList;
    }

    private List<GroupFieldDataDto> convertGroupFieldDataDto(List<FormFieldDto> formFieldDtoList, String affiliatedGroupData, String userId, String tenantId) {
        List<GroupFieldDataDto> retList = new ArrayList<>();
        List<FormFieldDto> groupList = new ArrayList<>();
        for (FormFieldDto formFieldDto : formFieldDtoList) {
            if (StringUtils.isNotEmpty(formFieldDto.getGroupName())) {
                groupList.add(formFieldDto);
            } else {
                if (CollectionUtil.isNotEmpty(groupList)) {
                    GroupFieldDataDto dto = new GroupFieldDataDto();
                    dto.setIsMulitField(true);
                    dto.setGroupFieldDtoList(personnelOrgUtils.buildMulitField(groupList, affiliatedGroupData, userId, tenantId));
                    retList.add(dto);
                    dto.setGroupName(groupList.get(0).getGroupName());
                    groupList = new ArrayList<>();
                }
                GroupFieldDataDto dto = new GroupFieldDataDto();
                dto.setFormFieldDto(formFieldDto);
                retList.add(dto);


            }
        }
        return retList;
    }


    /**
     * 查询字段类型
     *
     * @return
     */
    private List<FtbPersonnelsRegistrationFormType> queryFormTypeList() {
        return registrationFormTypeService.list(new QueryWrapper<FtbPersonnelsRegistrationFormType>()
                .lambda()
                .select(FtbPersonnelsRegistrationFormType::getId, FtbPersonnelsRegistrationFormType::getName, FtbPersonnelsRegistrationFormType::getSystemType,
                        FtbPersonnelsRegistrationFormType::getSorts, FtbPersonnelsRegistrationFormType::getStatus, FtbPersonnelsRegistrationFormType::getEnabledMark)
                .eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0) //1无效 0有效
                .eq(FtbPersonnelsRegistrationFormType::getStatus, 0) //0、启用  1、禁用
                .orderByAsc(FtbPersonnelsRegistrationFormType::getSorts));
    }

    /**
     * 查询字段
     *
     * @param registerFormField true 表示只查询入职登记表中字段，false 查询所有字段
     * @return
     */
    private List<FtbPersonnelsRegistrationFormField> queryFormFieldList(Boolean registerFormField) {
        return registrationFormFieldService.list(new QueryWrapper<FtbPersonnelsRegistrationFormField>()
                .lambda()
                .eq(FtbPersonnelsRegistrationFormField::getEnabledMark, 0) //1无效 0有效
                .eq(FtbPersonnelsRegistrationFormField::getStatus, 0) //0、启用  1、禁用
                .eq(registerFormField, FtbPersonnelsRegistrationFormField::getIsRegisterFormShow, 0)
                .orderByAsc(FtbPersonnelsRegistrationFormField::getSorts));
    }

    @Override
    public List<FtbPersonnelsStaffRegistrationFormData> queryFormFieldValueList(String phone, String rosterId) {
        return baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(StringUtils.isNotEmpty(rosterId), FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(StringUtils.isNotEmpty(phone), FtbPersonnelsStaffRegistrationFormData::getPhone, phone));
    }

    @Override
    public Map<String, List<FtbPersonnelsStaffRegistrationFormData>> queryFormFieldValueListWithPhone(List<String> phones) {
        List<FtbPersonnelsStaffRegistrationFormData> formData = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .in(FtbPersonnelsStaffRegistrationFormData::getPhone, phones));
        Map<String, List<FtbPersonnelsStaffRegistrationFormData>> listMap = formData.stream().collect(Collectors.groupingBy(FtbPersonnelsStaffRegistrationFormData::getPhone));

        return listMap;
    }

    @Override
    public List<FtbPersonnelsStaffRegistrationFormData> queryFormFieldValueForRosterIds(List<String> rosterIds) {
        if (CollectionUtil.isEmpty(rosterIds)) {
            return new ArrayList<>();
        }
        return baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .select(FtbPersonnelsStaffRegistrationFormData::getId, FtbPersonnelsStaffRegistrationFormData::getRosterId,
                        FtbPersonnelsStaffRegistrationFormData::getPhone, FtbPersonnelsStaffRegistrationFormData::getValue,
                        FtbPersonnelsStaffRegistrationFormData::getFormTypeId, FtbPersonnelsStaffRegistrationFormData::getFormFieldId)
                .in(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterIds));
    }

    @Override
    public List<FtbPersonnelsStaffRegistrationFormData> queryListForRosterIdAndField(List<String> rosterIds, List<String> formFieldIds) {
        if (CollectionUtil.isEmpty(rosterIds)) {
            return new ArrayList<>();
        }
        return baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .in(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, formFieldIds)
                .in(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterIds));
    }

    @Override
    public void updateForOneField(String phone, String formFieldId, String value) {
        UpdateWrapper<FtbPersonnelsStaffRegistrationFormData> wrapper = new UpdateWrapper<>();
        wrapper.lambda().set(FtbPersonnelsStaffRegistrationFormData::getValue, value)
                .eq(FtbPersonnelsStaffRegistrationFormData::getPhone, phone)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, formFieldId);
        baseMapper.update(null, wrapper);
    }

    @Override
    public void updateForOneField(String rosterId, String phone, String formFieldId, String value) {
        List<FtbPersonnelsStaffRegistrationFormData> oldData = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, formFieldId));
        if (CollectionUtil.isNotEmpty(oldData)) {
            UpdateWrapper<FtbPersonnelsStaffRegistrationFormData> wrapper = new UpdateWrapper<>();
            wrapper.lambda().set(FtbPersonnelsStaffRegistrationFormData::getValue, value)
                    .eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                    .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, formFieldId);
            baseMapper.update(new FtbPersonnelsStaffRegistrationFormData(), wrapper);
        } else {
            FtbPersonnelsRegistrationFormField field = registrationFormFieldService.getById(formFieldId);
            if (null == field) {
                return;
            }
            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            formData.setRosterId(rosterId);
            formData.setPhone(phone);
            formData.setFormTypeId(field.getFormTypeId());
            formData.setFormFieldId(formFieldId);
            formData.setValue(value);
            baseMapper.insert(formData);
        }
    }

    public String queryOneFieldValue(String phone, String rosterId, String fieldName) {
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(FtbPersonnelsStaffRegistrationFormData::getPhone, phone)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, fieldName));
        if (CollectionUtil.isNotEmpty(formDataList)) {
            FtbPersonnelsStaffRegistrationFormData ftbPersonnelsStaffRegistrationFormData = formDataList.get(0);
            if (StringUtils.isNotEmpty(ftbPersonnelsStaffRegistrationFormData.getValue())) {
                return ftbPersonnelsStaffRegistrationFormData.getValue();
            }
        }
        return "";
    }

    public FtbPersonnelsStaffRegistrationFormData queryOneFieldForFieldId(String rosterId, String fieldName) {
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, fieldName));
        if (CollectionUtil.isNotEmpty(formDataList)) {
            return formDataList.get(0);

        }
        return null;
    }

    public String queryOneFieldValueForPhone(String phone, String fieldName) {
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(FtbPersonnelsStaffRegistrationFormData::getPhone, phone)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, fieldName));
        if (CollectionUtil.isNotEmpty(formDataList)) {
            FtbPersonnelsStaffRegistrationFormData ftbPersonnelsStaffRegistrationFormData = formDataList.get(0);
            if (StringUtils.isNotEmpty(ftbPersonnelsStaffRegistrationFormData.getValue())) {
                return ftbPersonnelsStaffRegistrationFormData.getValue();
            }
        }
        return "";
    }


    public FtbPersonnelsStaffRegistrationFormData queryOneField(String phone, String rosterId, String fieldName) {
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = baseMapper.selectList(new QueryWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .lambda()
                .eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(FtbPersonnelsStaffRegistrationFormData::getPhone, phone)
                .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, fieldName));
        if (CollectionUtil.isNotEmpty(formDataList)) {
            return formDataList.get(0);

        }
        return null;
    }

    @Override
    public String queryTenantIdForCode(String code) {
        return personnelOrgUtils.queryTenantIdForCode(code);
    }

    /**
     * 根据手机号查询所有已经填写的字段
     *
     * @param phone
     * @return
     */
    @Override
    public Map<String, FtbPersonnelsStaffRegistrationFormData> queryAllFormData(String phone, String rosterId) {
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, rosterId);
        if (CollectionUtil.isEmpty(formFieldValueList)) {
            return new HashMap<>();
        }
        return personnelOrgUtils.convertFormValueMap(formFieldValueList);
    }

    @Override
    public Map<String, Map<String, String>> querAllFormDataForRosterIds(List<String> rosterIds) {
        Map<String, Map<String, String>> resultMap = new HashMap<>();
        if (CollUtil.isEmpty(rosterIds)) {
            return resultMap;
        }
        LambdaQueryWrapper<FtbPersonnelsStaffRegistrationFormData> wrapper = Wrappers.lambdaQuery();
        wrapper.in(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterIds);
        wrapper.and(a ->
                a.eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, "probationPeriod")
                        .or()
                        .eq(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, "planProbationaryDate")
        );
        List<FtbPersonnelsStaffRegistrationFormData> formData = baseMapper.selectList(wrapper);

        if (CollUtil.isNotEmpty(formData)) {
            Map<String, List<FtbPersonnelsStaffRegistrationFormData>> listMap = formData.stream().collect(Collectors.groupingBy(FtbPersonnelsStaffRegistrationFormData::getRosterId, Collectors.toList()));
            Set<String> keySet = listMap.keySet();
            keySet.forEach(str -> {
                List<FtbPersonnelsStaffRegistrationFormData> data = listMap.get(str);
                Map<String, String> map = data.stream().collect(Collectors.toMap(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, FtbPersonnelsStaffRegistrationFormData::getValue));
                resultMap.put(str, map);
            });
        }
        return resultMap;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class,lockRetryInternal =  5000 ,lockRetryTimes = 30)
    public void saveRegistrationForm(String tenantId, List<SubFormFieldDto> inputFieldValueList, Integer flag, String registerImg, String moduleId) {
        if (CollectionUtil.isEmpty(inputFieldValueList)) {
            throw new RuntimeException("提交数据为空");
        }
        //获取手机号
        String phone = personnelOrgUtils.getPhoneFormInput(inputFieldValueList);
        QueryWrapper<FtbPersonnelsStaffEmploymentApply> wrappe1r = new QueryWrapper<>();
        wrappe1r.lambda()
                .eq(FtbPersonnelsStaffEmploymentApply::getPhone, phone)
                .eq(FtbPersonnelsStaffEmploymentApply::getEnabledMark, 0).last("limit 1")
        ;
        FtbPersonnelsStaffEmploymentApply employmentApplyEntity = applyMapper.selectOne(wrappe1r);
        if (null != employmentApplyEntity) {
            if (employmentApplyEntity.getIsNeedCheck() == PhoneStatusEnum.BASE_ONBOARD_WAIT.getCode()) {//0、需要审批  1、不需要审批
                throw new RuntimeException("手机号已经在入职列表中!");
            } else {
                if (employmentApplyEntity.getCheckStatus() == PhoneStatusEnum.BASE_APPROVAL_WAIT.getCode() && employmentApplyEntity.getStatus() != PhoneStatusEnum.BASE_ONBOARD_WAIT.getCode()) {
                    throw new RuntimeException("手机号已经在入职列表中!");
                }else if (employmentApplyEntity.getCheckStatus() == PhoneStatusEnum.BASE_APPROVAL_WAIT.getCode()) {
                    throw new RuntimeException("该手机号等待入职审批中!");
                }else if (employmentApplyEntity.getCheckStatus() == PhoneStatusEnum.BASE_ONBOARD_WAIT.getCode()) {
                    throw new RuntimeException("该手机号等待入职审批中!");
                } else if (employmentApplyEntity.getCheckStatus() == PhoneStatusEnum.BASE_APPROVAL_REJECT.getCode()) {
                    throw new RuntimeException("该手机号已办理入职,但审批流程未通过,请前往待审批列表,进行重新办理!");
                }
            }
        }
        if (StringUtils.isEmpty(phone)) {
            throw new RuntimeException("手机号不能为空");
        }
        if (!personnelOrgUtils.isValidPhoneNumber(phone)) {
            throw new RuntimeException("手机号格式不正确");
        }
        FtbPersonnelsStaffRoster roster = staffRosterService.queryRosterInfoByPhone(phone);
        String rosterId = "";
        if (null != roster) {
            rosterId = roster.getId();
        }
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(true);
        if (CollectionUtil.isEmpty(formFeildList)) {
            return;
        }
        // 获取姓名
        String workerUserName = inputFieldValueList.stream()
                .filter(item -> "workerName".equals(item.getId())).findFirst()
                .map(SubFormFieldDto::getUserValue)
                .orElse("");
        // 校验身份证号
        inputFieldValueList.stream().filter(item -> "idCardNum".equals(item.getId())&& !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(phone, "idCardNum", a.getUserValue()) > 0) {
                throw new RuntimeException("身份证号已存在");
            }
            if (!RegexUtils.checkIdCard(a.getUserValue())) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            DateTime ageByIdCard = IdcardUtil.getBirthDate(a.getUserValue());
            if (ageByIdCard.isAfter(new Date())) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            // 姓名+身份证号校验
            IdCardVerificationResponse idCardVerificationResponse = personnelIdCardVerificationUtils.idCardVerification(a.getUserValue(),
                    workerUserName, tenantId);
            personnelIdCardVerificationUtils.checkIdCardVerification(idCardVerificationResponse);
        });
        // 校验银行卡号
        inputFieldValueList.stream().filter(item -> "bankCardNo".equals(item.getId())&& !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(phone, "bankCardNo", a.getUserValue()) > 0) {
                throw new RuntimeException("银行卡号已存在");
            }
        });
        // 校验公积金号
        inputFieldValueList.stream().filter(item -> "providentFundAccount".equals(item.getId())&& !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(phone, "providentFundAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("公积金号已存在");
            }
        });
        // 校验社保账号
        inputFieldValueList.stream().filter(item -> "socialAccount".equals(item.getId())&& !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(phone, "socialAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("社保账号已存在");
            }
        });
        //查询所有字段
        Map<String, FtbPersonnelsRegistrationFormField> formFieldMap = formFeildList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormField::getId, Function.identity()));

        //写入formData数据
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, rosterId);
        Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        FtbPersonnelsStaffRoster updateRosterEntity = new FtbPersonnelsStaffRoster();
        //需要同步的数据

        String flowerName = "";
        String workerName = "";
        String workerSex = "";
        String workerStatus = "";
        String actualProbationaryDate = "";
        String birthday = "";
        String idCardNum = "";
        String headLogo = "";
        String currGroupId = "";
        String healthCertificate = "";
        String startHealthDate = "";
        String endHealthDate = "";
        Date now = new Date();
        String actualStartDate = personnelOrgUtils.getPhoneFormInputForField(inputFieldValueList, "actualStartDate");
        Boolean canUpdateRealName = staffRosterService.canUpdateRealName();
        for (SubFormFieldDto subFormFieldDto : inputFieldValueList) {
            if (StringUtils.isEmpty(subFormFieldDto.getId())) {
                throw new RuntimeException("字段id不能为空");
            }
            if ("workerName".equals(subFormFieldDto.getId()) && canUpdateRealName == false) {
                if (null != roster) {
                    subFormFieldDto.setUserValue(roster.getName());
                }
            }
            FtbPersonnelsRegistrationFormField ftbPersonnelsRegistrationFormField = formFieldMap.get(subFormFieldDto.getId());
            if (!AFFILIATED_GROUP_NAME.equals(subFormFieldDto.getId())) {
                if (null == ftbPersonnelsRegistrationFormField) {
                    throw new RuntimeException("登记表配置已更新，请退出页面后重新填写！");
                    //throw new RuntimeException("[" + subFormFieldDto.getId() + "] 字段不存在");
                }
                if (ftbPersonnelsRegistrationFormField.getIsNeedFill() == 1 &&  (
                        StringUtils.isEmpty(subFormFieldDto.getUserValue())
                                || "[]".equals(subFormFieldDto.getUserValue())
                )) {
                    throw new RuntimeException(ftbPersonnelsRegistrationFormField.getName() + "必填");
                }
            }
            if ("flowerName".equals(subFormFieldDto.getId())) {
                flowerName = subFormFieldDto.getUserValue();
            } else if ("workerName".equals(subFormFieldDto.getId())) {
                workerName = subFormFieldDto.getUserValue();
            } else if ("workerSex".equals(subFormFieldDto.getId())) {
                workerSex = subFormFieldDto.getUserValue();
            } else if ("workerStatus".equals(subFormFieldDto.getId())) {
                workerStatus = subFormFieldDto.getUserValue();
            } else if ("actualProbationaryDate".equals(subFormFieldDto.getId())) {
                actualProbationaryDate = subFormFieldDto.getUserValue();
            } else if ("idCardNum".equals(subFormFieldDto.getId())) {
                idCardNum = subFormFieldDto.getUserValue();
            } else if ("headLogo".equals(subFormFieldDto.getId())) {
                headLogo = subFormFieldDto.getUserValue();
                if (StringUtils.isNotEmpty(headLogo) && !headLogo.startsWith("[")) {
                    throw new RuntimeException("提交的头像数据格式不正确");
                }
            } else if ("birthday".equals(subFormFieldDto.getId())) {
                checkBirthdayFormat(subFormFieldDto.getUserValue());
                birthday = subFormFieldDto.getUserValue();
            } else if ("companyAge".equals(subFormFieldDto.getId())) {
                if (StringUtils.isNotEmpty(actualStartDate)
                        && null != roster
                        && (!roster.getWorkerStatus().equals("304") || !roster.getWorkerStatus().equals("305"))) {
                    long betweenDay = 0L;
                    DateTime parse = DateUtil.parse(actualStartDate, "yyyy-MM-dd");
                    if (now.after(parse)) {
                        betweenDay = DateUtil.betweenDay(parse, now, false);
                    }
                    subFormFieldDto.setUserValue(String.valueOf(betweenDay));
                }
            } else if ("healthCertificate".equals(subFormFieldDto.getId())) {
                healthCertificate = subFormFieldDto.getUserValue();
            } else if ("startHealthDate".equals(subFormFieldDto.getId())) {
                startHealthDate = subFormFieldDto.getUserValue();
            } else if ("endHealthDate".equals(subFormFieldDto.getId())) {
                endHealthDate = subFormFieldDto.getUserValue();
            }
            personnelOrgUtils.fillRoster(updateRosterEntity, subFormFieldDto);
            FtbPersonnelsStaffRegistrationFormData oldFormData = formFieldValueMap.get(subFormFieldDto.getId());
            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            if (null != oldFormData) {
                formData.setId(oldFormData.getId());
            }
            if (StringUtils.isNotEmpty(rosterId)) {
                formData.setRosterId(rosterId);
            } else {
                formData.setRosterId("");
            }
            formData.setPhone(phone);
            formData.setFormFieldId(subFormFieldDto.getId());
            formData.setFormTypeId(subFormFieldDto.getFormTypeId());
            formData.setValue(subFormFieldDto.getUserValue());

            formDataList.add(formData);
        }
        // 身份证号码识别出生日期
        if (StringUtils.isNotEmpty(idCardNum) && !"null".equals(idCardNum)  && StringUtils.isEmpty(birthday)) {
            Date birthdayDate = IdcardUtil.getBirthDate(idCardNum).toJdkDate();
            FtbPersonnelsRegistrationFormField registrationFormField = formFieldMap.get("birthday");
            FtbPersonnelsRegistrationFormField registrationFormFieldAge = formFieldMap.get("age");
            if (Objects.nonNull(registrationFormField) && Objects.nonNull(registrationFormFieldAge)) {
                FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
                formData.setRosterId(rosterId);
                formData.setPhone(phone);
                formData.setFormTypeId(registrationFormField.getFormTypeId());
                formData.setFormFieldId(registrationFormField.getId());
                formData.setValue(DateUtil.format(birthdayDate, "yyyy-MM-dd"));
                int age = personnelOrgUtils.calculateAge(personnelOrgUtils.dateToLocalDate(birthdayDate));
                FtbPersonnelsStaffRegistrationFormData formDataAge = new FtbPersonnelsStaffRegistrationFormData();
                formDataAge.setRosterId(rosterId);
                formDataAge.setPhone(phone);
                formDataAge.setFormTypeId(registrationFormFieldAge.getFormTypeId());
                formDataAge.setFormFieldId(registrationFormFieldAge.getId());
                formDataAge.setValue(String.valueOf(age));
                formDataList.add(formDataAge);
                formDataList.add(formData);
            }
        }
        // 校验前后是否有空格
        Pattern spacesCheck = Pattern.compile(FtbRosterImportConstants.NAME_REGEX);
        Matcher spacesCheckMatcher = spacesCheck.matcher(workerName);
        if (!spacesCheckMatcher.matches()){
            throw new RuntimeException("请使用标准格式的中文名或英文名!");
        }
        //写入数据库
        if (CollectionUtil.isNotEmpty(formDataList)) {
            updateData(formDataList);
        }
        if(employmentApplyEntity == null) {
            String userId = onboardingData(tenantId, flag, registerImg, phone, workerName,moduleId);
            // 健康证同步
            certificateInstanceService.saveHealthCertificate(userId, healthCertificate, startHealthDate, endHealthDate);
        }else {
            // 更新身份证号
            LambdaUpdateWrapper<FtbPersonnelsStaffEmploymentApply> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
            lambdaUpdateWrapper.set(FtbPersonnelsStaffEmploymentApply::getIdCardNum, idCardNum);
            lambdaUpdateWrapper.eq(FtbPersonnelsStaffEmploymentApply::getId, employmentApplyEntity.getId());
            applyMapper.update(new FtbPersonnelsStaffEmploymentApply(),lambdaUpdateWrapper);
            // 未登记数据进行更新
            String userId = "";
            if (employmentApplyEntity.getIsSubmitForm() != 1) {
                LambdaUpdateWrapper<FtbPersonnelsStaffEmploymentApply> wrapper = Wrappers.lambdaUpdate();
                if (StringUtils.isNotEmpty(workerName)) {
                    wrapper.set(FtbPersonnelsStaffEmploymentApply::getWorkerName, workerName);
                    userId = employmentApplyEntity.getUserId();
                    // 老数据兼容
                    if (userId == null){
                        String userHeadLog =  generaDefaultUserHeadLog(employmentApplyEntity.getWorkerName());
                        userId = saveUserInfo(employmentApplyEntity, userHeadLog);
                        wrapper.set(FtbPersonnelsStaffEmploymentApply::getUserId,userId);
                    }else {
                        syncWorkName(workerName, tenantId, userId);
                    }
                }
                wrapper.set(FtbPersonnelsStaffEmploymentApply::getIsSubmitForm, 1);
                wrapper.set(FtbPersonnelsStaffEmploymentApply::getRegisterImg, registerImg);
                wrapper.eq(FtbPersonnelsStaffEmploymentApply::getId, employmentApplyEntity.getId());
                applyMapper.update(new FtbPersonnelsStaffEmploymentApply(), wrapper);
                extracted(workerName, tenantId, employmentApplyEntity.getUserId(),employmentApplyEntity.getCurrOrg(),moduleId);
            }
            // 健康证同步
            certificateInstanceService.saveHealthCertificate(userId, healthCertificate, startHealthDate, endHealthDate);
        }
        // 内推池状态变更
        personnelOrgUtils.sysWorkerStatusToUchisuike(phone, updateRosterEntity.getWorkerStatus());
        if (null != roster) {
            updateRosterEntity.setId(roster.getId());
            updateRosterEntity.setIsSubmitForm(1);
            staffRosterService.updateById(updateRosterEntity);
            String inputHeadLogo = getInputHeadLogo(headLogo);
            if (StringUtils.isNotEmpty(inputHeadLogo)) {
                personnelOrgUtils.sysUserHeadLog(roster.getUserId(), inputHeadLogo);
            }
            //同步姓名 花名册等信息到组织架构
            Boolean isUpdateTenant = false;
            SaveUserManagerAddDTO dto = new SaveUserManagerAddDTO();
            dto.setUserId(roster.getUserId());
            if (StringUtils.isNotEmpty(workerName)) {
                dto.setRealName(workerName);
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(workerSex)) {
                dto.setGender(Integer.valueOf(workerSex));
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(inputHeadLogo)) {
                dto.setHeadIcon(inputHeadLogo);
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(flowerName)) {
                dto.setNickName(flowerName);
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(actualProbationaryDate)) {
                dto.setBecomeDate(DateUtil.parse(actualProbationaryDate, "yyyy-MM-dd"));
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(actualStartDate)) {
                dto.setEntryDate(DateUtil.parse(actualStartDate, "yyyy-MM-dd"));
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(birthday)) {
                dto.setBirthday(DateUtil.parse(birthday, "yyyy-MM-dd"));
                isUpdateTenant = true;
            }
            if (StringUtils.isNotEmpty(idCardNum)) {
                dto.setCertificatesNumber(idCardNum);
                dto.setCertificatesType("a745d425adbb4321880817661cae8910");
                isUpdateTenant = true;
            }
            if (isUpdateTenant) {
                personnelOrgUtils.sysTenantAccountBaseNoLogin(dto, tenantId);
            }
        }
    }

    @SneakyThrows
    private String generaDefaultUserHeadLog(String name) {
        String headLogo = DEFAULT_USER_LOGO;
        ActionResult headResult = pTenantAccountApi.generateDefaultAvatar(name);
        if (null != headResult) {
            headLogo = (String) headResult.getData();
        }
        return headLogo;
    }
    public String  saveUserInfo(FtbPersonnelsStaffEmploymentApply apply, String userHeadLog,String... tenantIdS){
        // 生成账号建立关系信息
        SaveUserDTO saveUserDTO = new SaveUserDTO();
        saveUserDTO.setAccount(apply.getPhone());
        saveUserDTO.setRealName(apply.getWorkerName());
        saveUserDTO.setMobilePhone(apply.getPhone());
        saveUserDTO.setWorkerStatus(UserWorkStatusEnums.PRE_ONBOARDING.getCode());
        saveUserDTO.setAccount(apply.getPhone());
        saveUserDTO.setHeadIcon(userHeadLog);
        saveUserDTO.setEntryDate(apply.getExpectedStartDate());
        UserBoundInfoDTO userBoundInfoDTO = new UserBoundInfoDTO();
        userBoundInfoDTO.setOrganizeId(apply.getCurrOrg());
        userBoundInfoDTO.setPositionId(apply.getCurrPosition());
        userBoundInfoDTO.setGradesId(apply.getCurrRank());
        userBoundInfoDTO.setStoreTeamId(apply.getCurrGroupId());
        saveUserDTO.setBoundInfoDTO(userBoundInfoDTO);
        String tenantId = tenantIdS.length > 0 ? tenantIdS[0] : UserProvider.getUser().getTenantId();
        saveUserDTO.setTenantId(tenantId);
        //解决组织架构分布式事务 行锁问题 不多次调用 组织架构修改用户接口一次完成 提前生成ID 租户->用户
        //生成主账号
        String userId = FtbUtil.getId();
        //判断是否离职
        UserCopyEntity copyInfo = v2UserApi.getUserCopyInfo(saveUserDTO.getMobilePhone());
        if (copyInfo != null && StrUtil.isNotBlank(copyInfo.getId())){
            userId = copyInfo.getId();
        }
        UserAccountDto userAccountDto = new UserAccountDto();
        userAccountDto.setFid(userId);
        userAccountDto.setUserName(apply.getWorkerName());
        userAccountDto.setTenantId(tenantId);
        userAccountDto.setUserMobilePhone(apply.getPhone());
        userAccountDto.setHeadImageUrl(userHeadLog);
        List<UserAccountDto> addUserList = List.of(userAccountDto);
        ActionResult<List<UserAccountDto>> batchAddUserAccount = pTenantAccountApi.batchAddUserAccount(addUserList);
        if(batchAddUserAccount == null || !batchAddUserAccount.getCode().equals(200)){
            pTenantAccountApi.deleteUser(userId);
            throw new RuntimeException("主账号生成失败");
        }
        UserAccountDto accountDto = batchAddUserAccount.getData().stream().findFirst().orElse(new UserAccountDto());
        saveUserDTO.setId(userId);
        saveUserDTO.setAccount(accountDto.getAccount());
        ActionResult<String> actionResult = v2UserApi.saveUserInfo(saveUserDTO);
        if (actionResult ==null || actionResult.getCode() != 200) {
            pTenantAccountApi.deleteUser(userId);
            throw new RuntimeException(actionResult !=null   ? actionResult.getMsg() : "保存用户信息失败！");
        }
        return userId;
    }
    public void extracted(String workerName , String tenantId, String userId,String currOrg,String moduleId) {
        taskExecutor.execute(()->{
            List<String> stringList = permissionsUtils.getUserPersonnelOrganizationIdDataPermissions(userId,
                    List.of(PermissionsEnums.PERSONNEL_MANAGEMENT_Button.getValue().split(",")),
                    "",
                    List.of(PermissionsEnums.PERSONNEL_MANAGEMENT_WEB.getValue(),
                            PermissionsEnums.PERSONNEL_MANAGEMENT_APP.getValue()),
                    tenantId, currOrg, moduleId);
            ftbPersonnlesIMUtils.sendMsgWithList(tenantId,stringList, workerName,moduleId);
        });
    }


    // @Async
    public String onboardingData(String tenantId, Integer flag, String registerImg, String phone, String workerName, String moduleId) {
        // 根据入职填写新增 入职办理列表数据
        // 是否内推
        LambdaQueryWrapper<FtbPersonnelsUchisuikePond> uchisuikePondLambdaQueryWrapper = Wrappers.lambdaQuery();
        uchisuikePondLambdaQueryWrapper.eq(FtbPersonnelsUchisuikePond::getPhone, phone);
        uchisuikePondLambdaQueryWrapper.eq(FtbPersonnelsUchisuikePond::getEnableMark, 0);
        uchisuikePondLambdaQueryWrapper.last("limit 1");
        FtbPersonnelsStaffEmploymentApply employmentApply = new FtbPersonnelsStaffEmploymentApply();
        FtbPersonnelsUchisuikePond uchisuikePond = ftbPersonnelsUchisuikePondMapper.selectOne(uchisuikePondLambdaQueryWrapper);
        if (uchisuikePond != null) {
            employmentApply.setSource(Math.toIntExact(uchisuikePond.getSource()));
            employmentApply.setCurrOrg(uchisuikePond.getOrgId());
            employmentApply.setCurrPosition(uchisuikePond.getPostId());
            employmentApply.setCurrRank(uchisuikePond.getPostRankId());
        } else {
            if (flag != null && flag == 4) {
                employmentApply.setSource(0);
            } else {
                //同步入职登记表已经提交的员工信息
                employmentApply.setSource(1);
            }
        }
        if (StringUtils.isNotEmpty(registerImg)) {
            employmentApply.setRegisterImg(registerImg);
        }
        employmentApply.setWorkerName(workerName);
        employmentApply.setPhone(phone);
        employmentApply.setVersionNum(1);
        employmentApply.setStatus(0);
        employmentApply.setIsSubmitForm(1);
        employmentApply.setEnabledMark(0);
        FtbEmpAddNewDTO covert = FtbPersonnelsStaffEmploymentApply.covert(employmentApply);
        return ftbPersonnelsEmEntryService.promoteOnboardingManagement(covert, tenantId,moduleId);
    }

    private String getInputHeadLogo(String headLogo) {
        if (StringUtils.isEmpty(headLogo) || "[]".equals(headLogo)) {
            return "";
        } else {
            List<String> headList = JSONUtil.toList(headLogo, String.class);
            if (CollectionUtil.isNotEmpty(headList)) {
                headLogo = headList.get(0);
            } else {
                headLogo = "";
            }
        }
        return headLogo;
    }

    /**
     * 同步数据
     * @param dataMap
     * @param phone
     * @param rosterId
     */
    public void syncData(Map<String, Object> dataMap, String phone, String rosterId) {
        //获取所有字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(false);
        if (CollectionUtil.isEmpty(formFeildList)) {
            return;
        }
        //查询所有字段
        Map<String, FtbPersonnelsRegistrationFormField> formFieldMap = formFeildList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormField::getId, Function.identity()));
        //查询字段已经有的值
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, "");
        // 登记表字段主键ID : vo
        Map<String, FtbPersonnelsStaffRegistrationFormData> oldDataMap = formFieldValueList.stream().collect(Collectors.toMap(FtbPersonnelsStaffRegistrationFormData::getFormFieldId, Function.identity(), (a, b) -> a));
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        formFieldMap.forEach((key,value)->{
            // 没有数据进行新增
            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            // 校验字段是否存在
            Object o = dataMap.get(key);
            if (ObjectUtil.isNull(o)){
                return;
            }
            // 字段存在进行数据更新
            // 查看是否存在历史数据进行覆盖
            FtbPersonnelsStaffRegistrationFormData registrationFormDataOld = oldDataMap.get(key);
            // 将id进行覆盖
            if (ObjectUtil.isNotEmpty(registrationFormDataOld)){
                formData.setId(registrationFormDataOld.getId());
            }
            // 补充主键id
            if (StringUtils.isNotEmpty(rosterId)) {
                formData.setRosterId(rosterId);
            }
            FtbPersonnelsRegistrationFormField field = formFieldMap.get(key);
            formData.setPhone(phone);
            formData.setFormFieldId(field.getId());
            formData.setFormTypeId(field.getFormTypeId());
            formData.setValue(o.toString());
            formDataList.add(formData);
        });

        //写入数据库
        // 分批写入
        if (CollectionUtil.isNotEmpty(formDataList)) {
            Predicate<FtbPersonnelsStaffRegistrationFormData> predicateUpdate = item -> StringUtils.isNotEmpty(item.getId());
            Predicate<FtbPersonnelsStaffRegistrationFormData> predicateSave = item -> StringUtils.isEmpty(item.getId());
            List<FtbPersonnelsStaffRegistrationFormData> staffRegistrationFormDataUpdate = getData(formDataList, predicateUpdate);
            if (CollectionUtil.isNotEmpty(staffRegistrationFormDataUpdate))staffRegistrationFormDataUpdate.forEach(item-> baseMapper.updateById(item));
            List<FtbPersonnelsStaffRegistrationFormData> staffRegistrationFormDataSave = getData(formDataList, predicateSave);
            if (CollectionUtil.isNotEmpty(staffRegistrationFormDataSave))staffRegistrationFormDataSave.forEach(item -> baseMapper.insert(item));

        }
    }

    @NotNull
    private static List<FtbPersonnelsStaffRegistrationFormData> getData(List<FtbPersonnelsStaffRegistrationFormData> formDataList, Predicate<FtbPersonnelsStaffRegistrationFormData> predicate) {
        return formDataList.stream().filter(predicate).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void importSyncData(Map<String, Object> dataMap, String phone, String rosterId, Map<String, FtbPersonnelsRegistrationFormField> formFieldMap) {
        //查询字段已经有的值(此处是新增，数据库必然没有值，暂时屏蔽),正常情况是没有问题，由于用户先办理入职，但是还没有确认到岗，这个时候用户又使用导入功能就会有问题
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, rosterId);
        Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        dataMap.forEach((k, v) -> {
            if (null == v) {
                return;
            }
            FtbPersonnelsRegistrationFormField field = formFieldMap.get(k);
            if (null != field) {
                FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
                FtbPersonnelsStaffRegistrationFormData fieldValue = formFieldValueMap.get(k);
                if (null != fieldValue) {
                    formData.setId(fieldValue.getId());
                }
                if (StringUtils.isNotEmpty(rosterId)) {
                    formData.setRosterId(rosterId);
                } else {
                    formData.setRosterId("");
                }
                formData.setPhone(phone);
                formData.setFormFieldId(field.getId());
                formData.setFormTypeId(field.getFormTypeId());
                formData.setValue(v.toString());
                formDataList.add(formData);
            }
        });

        //写入数据库
        if (CollectionUtil.isNotEmpty(formDataList)) {
            saveBatch(formDataList);
        }
    }

    /**
     * 查询员工入职登记表
     *
     * @param phone 手机号
     * @return
     */
    @Override
    public List<FormTypeDto> queryRegistrationForm(String phone, Boolean registerForm) {
        String userId = "",rosterId = "";
        if (!registerForm) {
            LambdaQueryWrapper<FtbPersonnelsStaffRoster> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FtbPersonnelsStaffRoster::getPhone, phone);
            queryWrapper.eq(FtbPersonnelsStaffRoster::getEnabledMark,0);
            FtbPersonnelsStaffRoster serviceOne = staffRosterService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(serviceOne)) {
                userId = serviceOne.getUserId();
                rosterId = serviceOne.getId();
            }
        }
        return queryAndFillFormFieldValue(phone, userId, rosterId, registerForm);
    }


    /**
     * 查询员工入职登记表
     *
     * @return
     */
    @Override
    public List<FormTypeDto> queryRegistrationForm() {
        //查询字段类型
        List<FtbPersonnelsRegistrationFormType> formTypeList = queryFormTypeList();
        if (CollectionUtil.isEmpty(formTypeList)) {
            return new ArrayList<>();
        }
        List<FormTypeDto> formTypeDtoList = BeanUtil.copyToList(formTypeList, FormTypeDto.class);
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(true);
        if (CollectionUtil.isEmpty(formFeildList)) {
            return formTypeDtoList;
        }

        List<FormFieldDto> fieldList = BeanUtil.copyToList(formFeildList, FormFieldDto.class);
        fillFieldOption(fieldList);
        //按照formTypeId 分组
        Map<String, List<FormFieldDto>> fieldMap = fieldList.stream().collect(Collectors.groupingBy(FormFieldDto::getFormTypeId));
        for (FormTypeDto formTypeDto : formTypeDtoList) {
            List<FormFieldDto> formFieldDtoList = fieldMap.get(formTypeDto.getId());
            if (CollectionUtil.isNotEmpty(formFieldDtoList)) {
                formTypeDto.setGroupFieldDataDtoList(convertGroupFieldDataDto(formFieldDtoList, "", ""));
            }
        }
        return filterNullFieldType(formTypeDtoList, true);
    }

    @Override
    public CheckRegisterFormFillDto checkRegistrationFormFill(String phone) {
        Boolean isFill = staffEmploymentApplyService.checkFillRegistrationForm(phone);
        CheckRegisterFormFillDto dto = new CheckRegisterFormFillDto();
        dto.setIsFill(isFill);
        return dto;
    }

    /**
     * 查询员工归档登记表
     *
     * @param
     * @return
     */
    @Override
    public List<FormTypeDto> queryArchivalForm(String userId) {
        //查询入职登记信息
        FtbPersonnelsStaffRoster rosterEntity = staffRosterService.queryRosterInfoByUserId(userId);
        if (null == rosterEntity) {
            LambdaQueryWrapper<FtbPersonnelsStaffEmploymentApply> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FtbPersonnelsStaffEmploymentApply::getUserId,userId);
            queryWrapper.eq(FtbPersonnelsStaffEmploymentApply::getEnabledMark, 0);
            queryWrapper.in(FtbPersonnelsStaffEmploymentApply::getCheckStatus, 0);
            queryWrapper.last("limit 1");
            FtbPersonnelsStaffEmploymentApply one = staffEmploymentApplyService.getOne(queryWrapper);
            if(Objects.nonNull(one)){
                throw new RuntimeException("未办理入职，暂无档案信息!");
            }
            throw new RuntimeException("员工花名册信息不存在");
        }
        String phone = rosterEntity.getPhone();
        return queryAndFillFormFieldValue(phone, rosterEntity.getUserId(), rosterEntity.getId(), false);
    }

    /**
     * 查询员工归档登记表
     *
     * @param userId
     * @return
     */
    @Override
    public List<FormTypeDto> queryArchivalForm(String userId, String tenantId) {
        //查询入职登记信息
        FtbPersonnelsStaffRoster rosterEntity = staffRosterService.queryRosterInfoByUserId(userId);
        if (null == rosterEntity) {
            throw new RuntimeException("员工花名册信息不存在");
        }
        String phone = rosterEntity.getPhone();
        return queryAndFillFormFieldValue(phone, rosterEntity.getUserId(), rosterEntity.getId(), false, tenantId);
    }

    /**
     * @param phone
     * @param registerForm true 表示只查询入职登记表中字段，false 查询所有字段
     * @return
     */
    public List<FormTypeDto> queryAndFillFormFieldValue(String phone, String userId, String rosterId, Boolean registerForm, String tenantId) {
        //查询字段类型
        List<FtbPersonnelsRegistrationFormType> formTypeList = queryFormTypeList();
        if (CollectionUtil.isEmpty(formTypeList)) {
            return new ArrayList<>();
        }
        List<FormTypeDto> formTypeDtoList = BeanUtil.copyToList(formTypeList, FormTypeDto.class);
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(registerForm);
        if (CollectionUtil.isEmpty(formFeildList)) {
            return formTypeDtoList;
        }
        List<FormFieldDto> fieldList = BeanUtil.copyToList(formFeildList, FormFieldDto.class);
        List<FtbPersonnelsRegistrationFormFieldOption> optionList = fillFieldOption(fieldList);
        Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap = optionList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormFieldOption::getId, Function.identity()));
        //查询值
        String affiliatedGroupData = "";//组织 岗位 职等
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, rosterId);

        if (CollectionUtil.isNotEmpty(formFieldValueList)) {
            Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
            if (null != formFieldValueMap.get(AFFILIATED_GROUP_NAME)) {
                affiliatedGroupData = formFieldValueMap.get(AFFILIATED_GROUP_NAME).getValue();
            }
            List<SaffRoleDto> roleDtoList = personnelOrgUtils.queryRoleListForUserIdNoToken(userId, tenantId);
            Map<String, List<WorkerGroupDataDto>> userOrgBoundInfoForUserListAndTenantIdMap = personnelOrgUtils.getUserOrgBoundInfoForUserListAndTenantId(List.of(userId), tenantId, true);
            List<WorkerGroupDataDto> workerGroupDataDtoList = userOrgBoundInfoForUserListAndTenantIdMap.get(userId);
            for (FormFieldDto formFieldDto : fieldList) {
                FtbPersonnelsStaffRegistrationFormData formFieldValue = formFieldValueMap.get(formFieldDto.getId());
                String formValueStr = "";
                if (null != formFieldValue) {
                    formValueStr = formFieldValue.getValue();
                    formFieldDto.setUserValue(formFieldValue.getValue());
                    if (formFieldDto.getType() == 2 || formFieldDto.getType() == 3) {
                        if (StringUtils.isNotEmpty(formFieldValue.getValue())) {
                            FtbPersonnelsRegistrationFormFieldOption optionEntity = null;
                            if ("probationPeriod".equals(formFieldDto.getId())) {
                                if (StringUtils.isNotEmpty(formFieldValue.getValue()) && formFieldValue.getValue().startsWith("{")) {
                                    ProbationPeriodDto bean = JSONUtil.toBean(formFieldValue.getValue(), ProbationPeriodDto.class);
                                    String key = bean.getType();
                                    optionEntity = optionMap.get(key);
                                }

                            } else if ("contractType".equals(formFieldDto.getId())) {
                                String contractTypeName = personnelOrgUtils.queryContractTypeNameNoToken(formFieldValue.getValue(), tenantId);
                                formFieldDto.setUserValueLable(contractTypeName);
                            } else if ("currShopId".equals(formFieldDto.getId())) {
                                StoreEntity storeEntity = personnelOrgUtils.queryStoreInfo(formFieldValue.getValue());
                                if (null != storeEntity) {
                                    formFieldDto.setUserValueLable(storeEntity.getStorename());
                                }
                            } else {
                                optionEntity = optionMap.get(formFieldValue.getValue());
                            }
                            if (null != optionEntity) {
                                formFieldDto.setUserValueLable(optionEntity.getName());
                            }
                        }


                    } else {
                        if ("headLogo".equals(formFieldDto.getId())) {
                            List<String> headLogoList = personnelOrgUtils.parseHeadLogo(formFieldValue.getValue());
                            if (CollectionUtil.isNotEmpty(headLogoList)) {
                                formFieldDto.setUserValue(JSONUtil.toJsonStr(headLogoList));
                            }
                        }

                    }
                }

                if ("currRole".equals(formFieldDto.getId())) {
                    if (CollectionUtil.isNotEmpty(roleDtoList)) {
                        //获取所有角色名称
                        List<String> roleName = roleDtoList.stream().map(SaffRoleDto::getFullName).collect(Collectors.toList());
                        formFieldDto.setUserValueLable(String.join(",", roleName));
                        List<String> roleIds = roleDtoList.stream().map(SaffRoleDto::getId).collect(Collectors.toList());
                        formFieldDto.setUserValue(String.join(",", roleIds));
                    } else {
                        formFieldDto.setUserValue("");
                    }
                } else if ("currOrg".equals(formFieldDto.getId())) {
                    if (StringUtils.isNotEmpty(formValueStr)) {
                        OrganizeEntity organizeEntity = personnelOrgUtils.queryOrganizeInfoNoToken(formValueStr, tenantId);
                        if (null != organizeEntity) {
                            formFieldDto.setUserValueLable(organizeEntity.getFullName());
                        } else {
                            formFieldDto.setUserValue("");
                        }
                    } else {
                        if (CollectionUtil.isNotEmpty(workerGroupDataDtoList)) {
                            formFieldDto.setUserValue(workerGroupDataDtoList.get(0).getAffiliatedOrg());
                            formFieldDto.setUserValueLable(workerGroupDataDtoList.get(0).getAffiliatedOrgName());
                        }

                    }
                } else if ("currPosition".equals(formFieldDto.getId())) {
                    if (StringUtils.isNotEmpty(formValueStr)) {
                        PositionEntity positionEntity = personnelOrgUtils.queryPositionNoToken(formValueStr, tenantId);
                        if (null != positionEntity) {
                            formFieldDto.setUserValueLable(positionEntity.getFullName());
                        } else {
                            formFieldDto.setUserValue("");
                        }
                    } else {
                        if (CollectionUtil.isNotEmpty(workerGroupDataDtoList)) {
                            formFieldDto.setUserValue(workerGroupDataDtoList.get(0).getAffiliatedPosition());
                            formFieldDto.setUserValueLable(workerGroupDataDtoList.get(0).getAffiliatedPositionName());
                        }
                    }
                } else if ("currRank".equals(formFieldDto.getId())) {
                    if (StringUtils.isNotEmpty(formValueStr)) {
                        PositionGradesInfoVO rankVo = personnelOrgUtils.queryRankNoToken(formValueStr, tenantId);
                        if (null != rankVo) {
                            formFieldDto.setUserValueLable(rankVo.getFullName());
                        } else {
                            formFieldDto.setUserValue("");
                        }
                    } else {
                        if (CollectionUtil.isNotEmpty(workerGroupDataDtoList)) {
                            formFieldDto.setUserValue(workerGroupDataDtoList.get(0).getAffiliatedRank());
                            formFieldDto.setUserValueLable(workerGroupDataDtoList.get(0).getAffiliatedRankName());
                        }
                    }
                } else if ("currReportsTo".equals(formFieldDto.getId())) {
                    FtbPersonnelsStaffRoster userEntity = personnelOrgUtils.queryUserInfoLocal(formValueStr);
                    if (null != userEntity) {
                        formFieldDto.setUserValueLable(userEntity.getName());
                    } else {
                        formFieldDto.setUserValue("");
                    }
                } else if (PersonnelFormDataSystemRosterFields.AGE.getId().equals(formFieldDto.getId())) {
                    fieldList.stream().filter(data -> data.getId().equals(PersonnelFormDataSystemRosterFields.BIRTHDAY.getId())).findFirst().ifPresent(data -> {
                                FtbPersonnelsStaffRegistrationFormData birthdayFieldValue = formFieldValueMap.get(data.getId());
                                if (birthdayFieldValue == null || StrUtil.isBlank(birthdayFieldValue.getValue())) {
                                    formFieldDto.setUserValue(null);
                                } else {
                                    Date dateBirthday = DateUtil.parse(birthdayFieldValue.getValue());
                                    long age = DateUtil.betweenYear(dateBirthday, DateUtil.date(), false);
                                    formFieldDto.setUserValue(Long.toString(age));
                                }
                            }
                    );
                    formFieldDto.setCurrIsUpdate(false);
                } else if (PersonnelFormDataSystemRosterFields.WORK_AGE.getId().equals(formFieldDto.getId())) {
                    fieldList.stream().filter(data -> data.getId().equals(PersonnelFormDataSystemRosterFields.FIRST_WORK_DATE.getId())).findFirst().ifPresent(data -> {
                                FtbPersonnelsStaffRegistrationFormData workAgeFieldValue = formFieldValueMap.get(data.getId());
                                if (workAgeFieldValue == null || StrUtil.isBlank(workAgeFieldValue.getValue())) {
                                    formFieldDto.setUserValue(null);
                                } else {
                                    Date ageWorkAge = DateUtil.parse(workAgeFieldValue.getValue());
                                    long age = DateUtil.betweenYear(ageWorkAge, DateUtil.date(), false);
                                    formFieldDto.setUserValue(Long.toString(age));
                                }
                            }
                    );
                    formFieldDto.setCurrIsUpdate(false);
                } else if (PersonnelFormDataSystemRosterFields.ATTENDANCE_GROUP.getId().equals(formFieldDto.getId())) {
                    formFieldDto.setUserValue(StrUtil.EMPTY);
                    formFieldDto.setUserValueLable(StrUtil.EMPTY);
                    List<AttendanceUserGroupVo> attendanceUserGroup = attendanceGroupService.getAttendanceUserGroup(List.of(userId));
                    if (CollectionUtil.isNotEmpty(attendanceUserGroup)) {
                        AttendanceUserGroupVo attendanceUserGroupVo = attendanceUserGroup.get(0);
                        formFieldDto.setUserValue(attendanceUserGroupVo.getGroupName());
                        formFieldDto.setUserValueLable(attendanceUserGroupVo.getGroupName());
                    }
//                    attendanceGroupService.getAttendanceUserListGroupVO(List.of(userId)).stream().findFirst().ifPresent(vo -> {
//                        formFieldDto.setUserValue(vo.getGroupName());
//                        formFieldDto.setUserValueLable(vo.getGroupFullName());
//                    });
                }

            }
        }

        //按照formTypeId 分组
        Map<String, List<FormFieldDto>> fieldMap = fieldList.stream().collect(Collectors.groupingBy(FormFieldDto::getFormTypeId));
        for (
                FormTypeDto formTypeDto : formTypeDtoList) {
            List<FormFieldDto> formFieldDtoList = fieldMap.get(formTypeDto.getId());
            if (CollectionUtil.isNotEmpty(formFieldDtoList)) {
                formTypeDto.setGroupFieldDataDtoList(convertGroupFieldDataDto(formFieldDtoList, affiliatedGroupData, userId, tenantId));
            }
        }
        return filterNullFieldType(formTypeDtoList, registerForm);

    }


    /**
     * @param phone
     * @param registerForm true 表示只查询入职登记表中字段，false 查询所有字段
     * @return
     */
    @Override
    public List<FormTypeDto> queryAndFillFormFieldValue(String phone, String userId, String rosterId, Boolean registerForm) {
        //查询字段类型
        List<FtbPersonnelsRegistrationFormType> formTypeList = queryFormTypeList();
        if (CollectionUtil.isEmpty(formTypeList)) {
            return new ArrayList<>();
        }
        List<FormTypeDto> formTypeDtoList = BeanUtil.copyToList(formTypeList, FormTypeDto.class);
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(registerForm);
        if (CollectionUtil.isEmpty(formFeildList)) {
            return formTypeDtoList;
        }
        List<FormFieldDto> fieldList = BeanUtil.copyToList(formFeildList, FormFieldDto.class);
        List<FtbPersonnelsRegistrationFormFieldOption> optionList = fillFieldOption(fieldList);
        Map<String, FtbPersonnelsRegistrationFormFieldOption> optionMap = optionList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormFieldOption::getId, Function.identity()));
        //查询值
        String affiliatedGroupData = "";//组织 岗位 职等
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, rosterId);
        FtbPersonnelsStaffRoster exiestRosterEntity = null;
        if (StringUtils.isNotEmpty(rosterId)) {
            exiestRosterEntity = staffRosterService.getById(rosterId);
        }else{
            // 兼容离职数据
            LambdaQueryWrapper<FtbPersonnelsStaffRoster> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FtbPersonnelsStaffRoster::getPhone,phone);
            queryWrapper.eq(FtbPersonnelsStaffRoster::getWorkerStatus,"305");
            FtbPersonnelsStaffRoster serviceOne = staffRosterService.getOne(queryWrapper);
            if (Objects.nonNull(serviceOne)){
                exiestRosterEntity = serviceOne;
            }
        }

        if (CollectionUtil.isNotEmpty(formFieldValueList)) {
            Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
            if (null != formFieldValueMap.get(AFFILIATED_GROUP_NAME)) {
                affiliatedGroupData = formFieldValueMap.get(AFFILIATED_GROUP_NAME).getValue();
            }
            // 健康证
            Optional<HealthCertificateDetailVO> healthCertificateDetail = certificateInstanceService.getHealthCertificateDetail(userId);
            for (FormFieldDto formFieldDto : fieldList) {
                FtbPersonnelsStaffRegistrationFormData formFieldValue = formFieldValueMap.get(formFieldDto.getId());
                FtbPersonnelsRegistrationFormFieldOption optionEntity = null;
                String formValueStr = "";
                if (null != formFieldValue) {
                    formValueStr = formFieldValue.getValue();
                    formFieldDto.setUserValue(formFieldValue.getValue());
                    if (formFieldDto.getType() == 2 || formFieldDto.getType() == 3) {
                        if (StringUtils.isNotEmpty(formFieldValue.getValue())) {
                            if ("probationPeriod".equals(formFieldDto.getId())) {
                                if (StringUtils.isNotEmpty(formFieldValue.getValue()) && formFieldValue.getValue().startsWith("{")) {
                                    ProbationPeriodDto bean = JSONUtil.toBean(formFieldValue.getValue(), ProbationPeriodDto.class);
                                    String key = bean.getType();
                                    optionEntity = optionMap.get(key);
                                }

                            } else if ("contractType".equals(formFieldDto.getId())) {
                                String contractTypeName = personnelOrgUtils.queryContractTypeName(formFieldValue.getValue());
                                formFieldDto.setUserValueLable(contractTypeName);
                            } else if ("currShopId".equals(formFieldDto.getId())) {
                                StoreEntity storeEntity = personnelOrgUtils.queryStoreInfo(formFieldValue.getValue());
                                if (null != storeEntity) {
                                    formFieldDto.setUserValueLable(storeEntity.getStorename());
                                }
                            } else if ("意向组织".equals(formFieldDto.getName())) {
                                OrganizeEntity organizeEntity = personnelOrgUtils.queryOrganizeInfo(formValueStr);
                                formFieldDto.setOptionDtoList(new ArrayList<>());
                                if (null != organizeEntity) {
                                    formFieldDto.setUserValueLable(organizeEntity.getFullName());
                                } else {
                                    formFieldDto.setUserValue("");
                                    formFieldDto.setUserValueLable("");
                                }
                            } else {
                                optionEntity = optionMap.get(formFieldValue.getValue());
                            }
                            if (null != optionEntity) {
                                formFieldDto.setUserValueLable(optionEntity.getName());
                            }
                        }

                    } else {
                        if ("headLogo".equals(formFieldDto.getId())) {
                            List<String> headLogoList = personnelOrgUtils.parseHeadLogo(formFieldValue.getValue());
                            if (CollectionUtil.isNotEmpty(headLogoList)) {
                                formFieldDto.setUserValue(JSONUtil.toJsonStr(headLogoList));
                            }
                        } else if (PersonnelFormDataSystemRosterFields.CONTRACT_FILE.getId().equals(formFieldDto.getId())) {
                            if (StringUtils.isNotEmpty(formValueStr) && !formValueStr.equals("[]")) {
                                if (!formValueStr.contains("{")) {
                                    formFieldDto.setUserValue(convertOldContractFile(formValueStr));
                                }
                            }
                        }

                    }
                }
                // 修改司龄
                if ("companyAge".equals(formFieldDto.getId()) && ObjectUtil.isNotEmpty(exiestRosterEntity)){
                    Date departDate = exiestRosterEntity.getDepartDate();
                    String workerStatus = exiestRosterEntity.getWorkerStatus();
                    // 实际入职时间
                    Date actualStartDate = exiestRosterEntity.getActualStartDate();
                    String companyAge = "";
                    if ("305".equals(workerStatus) &&  ObjectUtil.isNotEmpty(departDate)) {
                        companyAge = CompanyAgeUtil.calculateServiceAgeShort(actualStartDate,departDate);
                    }else if (ObjectUtil.isNotEmpty(actualStartDate)) {
                        companyAge = CompanyAgeUtil.calculateServiceAgeShort(actualStartDate,new Date());
                    }
                    formFieldDto.setUserValue(companyAge);
                } else if ("currOrg".equals(formFieldDto.getId())) {
                    String formValueStrTeamId = formValueStr;
                    if (Objects.nonNull(exiestRosterEntity) && StringUtils.isNotEmpty(exiestRosterEntity.getCurrOrg())) {
                        formValueStrTeamId = exiestRosterEntity.getCurrOrg();
                    }
                    if (StringUtils.isNotEmpty(formValueStrTeamId)) {
                        formFieldDto.setUserValue(formValueStrTeamId);
                        OrganizeEntity organizeEntity = personnelOrgUtils.queryOrganizeInfo(formValueStrTeamId);
                        if (null != organizeEntity) {
                            formFieldDto.setUserValueLable(organizeEntity.getFullName());
                        } else {
                            formFieldDto.setUserValueLable("");
                        }
                    } else {
                        formFieldDto.setUserValue("");
                        formFieldDto.setUserValueLable("");

                    }
                } else if ("currPosition".equals(formFieldDto.getId())) {
                    String formValueStrTeamId = formValueStr;
                    if (Objects.nonNull(exiestRosterEntity) && StringUtils.isNotEmpty(exiestRosterEntity.getCurrPosition())) {
                        formValueStrTeamId = exiestRosterEntity.getCurrPosition();
                    }
                    if (StringUtils.isNotEmpty(formValueStrTeamId)) {
                        formFieldDto.setUserValue(formValueStrTeamId);
                        PositionEntity positionEntity = personnelOrgUtils.queryPosition(formValueStrTeamId);
                        if (null != positionEntity) {
                            formFieldDto.setUserValueLable(positionEntity.getFullName());
                        } else {
                            formFieldDto.setUserValueLable("");
                        }
                    } else {
                        formFieldDto.setUserValue("");
                        formFieldDto.setUserValueLable("");
                    }
                } else if ("currRank".equals(formFieldDto.getId())) {
                    String formValueStrTeamId = formValueStr;
                    if (Objects.nonNull(exiestRosterEntity) && StringUtils.isNotEmpty(exiestRosterEntity.getCurrRank())) {
                        formValueStrTeamId = exiestRosterEntity.getCurrRank();
                    }
                    if (StringUtils.isNotEmpty(formValueStrTeamId)) {
                        formFieldDto.setUserValue(formValueStrTeamId);
                        PositionGradesInfoVO rankVo = personnelOrgUtils.queryRank(formValueStrTeamId);
                        if (null != rankVo) {
                            formFieldDto.setUserValueLable(rankVo.getFullName());
                        } else {
                            formFieldDto.setUserValueLable("");
                        }
                    } else {
                        formFieldDto.setUserValue("");
                        formFieldDto.setUserValueLable("");
                    }
                } else if ("currReportsTo".equals(formFieldDto.getId())) {
                    String formValueStrTeamId = formValueStr;
                    if (Objects.nonNull(exiestRosterEntity) && StringUtils.isNotEmpty(exiestRosterEntity.getCurrReportsTo())) {
                        formValueStrTeamId = exiestRosterEntity.getCurrReportsTo();
                    }
                    UserEntity userEntity = personnelOrgUtils.queryUserInfo(formValueStrTeamId);
                    formFieldDto.setUserValue(formValueStrTeamId);
                    if (null != userEntity) {
                        formFieldDto.setUserValueLable(userEntity.getRealName());
                    } else {
                        formFieldDto.setUserValue("");
                        formFieldDto.setUserValueLable("");
                    }
                } else if ("onboardingTeam".equals(formFieldDto.getId())) {
                    String formValueStrTeamId = formValueStr;
                    if (Objects.nonNull(exiestRosterEntity) && StringUtils.isNotEmpty(exiestRosterEntity.getCurrGroupId())) {
                        formValueStrTeamId = exiestRosterEntity.getCurrGroupId();
                    }
                    if (StringUtils.isNotEmpty(formValueStrTeamId)) {
                        formFieldDto.setUserValue(formValueStrTeamId);
                        OrganizeEntity organizeEntity = personnelOrgUtils.queryOrganizeInfo(formValueStrTeamId);
                        if (null != organizeEntity) {
                            formFieldDto.setUserValueLable(organizeEntity.getFullName());
                        } else {
                            formFieldDto.setUserValueLable("");
                        }
                    } else {
                        formFieldDto.setUserValue("");
                        formFieldDto.setUserValueLable("");
                    }
                } else if (PersonnelFormDataSystemRosterFields.AGE.getId().equals(formFieldDto.getId())) {
                    fieldList.stream().filter(data -> data.getId().equals(PersonnelFormDataSystemRosterFields.BIRTHDAY.getId())).findFirst().ifPresent(data -> {
                                FtbPersonnelsStaffRegistrationFormData birthdayFieldValue = formFieldValueMap.get(data.getId());
                                if (birthdayFieldValue == null || StrUtil.isBlank(birthdayFieldValue.getValue())) {
                                    formFieldDto.setUserValue(null);
                                } else {
                                    Date dateBirthday = DateUtil.parse(birthdayFieldValue.getValue());
                                    long age = DateUtil.betweenYear(dateBirthday, DateUtil.date(), false);
                                    formFieldDto.setUserValue(Long.toString(age));
                                }
                            }
                    );
                    formFieldDto.setCurrIsUpdate(false);
                } else if (PersonnelFormDataSystemRosterFields.WORK_AGE.getId().equals(formFieldDto.getId())) {
                    fieldList.stream().filter(data -> data.getId().equals(PersonnelFormDataSystemRosterFields.FIRST_WORK_DATE.getId())).findFirst().ifPresent(data -> {
                                FtbPersonnelsStaffRegistrationFormData workAgeFieldValue = formFieldValueMap.get(data.getId());
                                if (workAgeFieldValue == null || StrUtil.isBlank(workAgeFieldValue.getValue())) {
                                    formFieldDto.setUserValue(null);
                                } else {
                                    Date ageWorkAge = DateUtil.parse(workAgeFieldValue.getValue());
                                    long age = DateUtil.betweenYear(ageWorkAge, DateUtil.date(), false);
                                    formFieldDto.setUserValue(Long.toString(age));
                                }
                            }
                    );
                    formFieldDto.setCurrIsUpdate(false);
                } else if (PersonnelFormDataSystemRosterFields.CONTRACT_STATUS.getId().equals(formFieldDto.getId())) {
                    if (formFieldValue != null && StringUtils.isNotEmpty(formFieldValue.getValue())) {
                        optionEntity = optionMap.get(formFieldValue.getValue());
                        if (null != optionEntity) {
                            formFieldDto.setUserValue(formFieldValue.getValue());
                            formFieldDto.setUserValueLable(optionEntity.getName());
                        }
                    } else {
                        if (null != exiestRosterEntity) {
                            optionEntity = optionMap.get(exiestRosterEntity.getContractStatus().toString());
                            if (null != optionEntity) {
                                formFieldDto.setUserValue(exiestRosterEntity.getContractStatus() + "");
                                formFieldDto.setUserValueLable(optionEntity.getName());
                            }
                        }
                    }
                } else if (PersonnelFormDataSystemRosterFields.HEALTH_CERTIFICATE.getId().equals(formFieldDto.getId())) {
                    if (healthCertificateDetail.isPresent()) {
                        formFieldDto.setUserValue(healthCertificateDetail.get().getCertificateImage());
                        formFieldDto.setUserValueLable(healthCertificateDetail.get().getCertificateImage());
                    }
                } else if ("startHealthDate".equals(formFieldDto.getId())) {
                    if (healthCertificateDetail.isPresent() && healthCertificateDetail.get().getIssueDate() != null) {
                        String issueDate = DateUtil.format(healthCertificateDetail.get().getIssueDate(),"yyyy-MM-dd");
                        formFieldDto.setUserValue(issueDate);
                        formFieldDto.setUserValueLable(issueDate);
                    }
                } else if ("endHealthDate".equals(formFieldDto.getId())) {
                    if (healthCertificateDetail.isPresent() && healthCertificateDetail.get().getExpireDate() != null) {
                        String issueDate = DateUtil.format(healthCertificateDetail.get().getExpireDate(),"yyyy-MM-dd");
                        formFieldDto.setUserValue(issueDate);
                        formFieldDto.setUserValueLable(issueDate);
                    }
                }
            }
        }

        //按照formTypeId 分组
        Map<String, List<FormFieldDto>> fieldMap = fieldList.stream().collect(Collectors.groupingBy(FormFieldDto::getFormTypeId));
        for (
                FormTypeDto formTypeDto : formTypeDtoList) {
            List<FormFieldDto> formFieldDtoList = fieldMap.get(formTypeDto.getId());
            if (CollectionUtil.isNotEmpty(formFieldDtoList)) {
                formTypeDto.setGroupFieldDataDtoList(convertGroupFieldDataDto(formFieldDtoList, affiliatedGroupData, userId));
            }
        }
        return filterNullFieldType(formTypeDtoList, registerForm);

    }

    private String convertOldContractFile(String formValueStr) {
        List<ContactStatusInfo.ContactInfoFile> fileList = new ArrayList<>();
        List<String> list = JSONUtil.toList(formValueStr, String.class);
        if (CollectionUtil.isNotEmpty(list)) {
            for (String urlPath : list) {
                Path path = Paths.get(urlPath);
                String fileName = path.getFileName().toString();
                // 分离扩展名
                int dotIndex = fileName.lastIndexOf('.');
                String extension = dotIndex == -1 ? "" : fileName.substring(dotIndex + 1);
                ContactStatusInfo.ContactInfoFile file = new ContactStatusInfo.ContactInfoFile();
                file.setName(fileName);
                file.setUrl(urlPath);
                file.setFileExtension(extension);
                fileList.add(file);
            }
        }
        return JSONUtil.toJsonStr(fileList);
    }

    /**
     * 过滤没有字段的项
     *
     * @param formTypeDtoList
     * @return
     */
    private List<FormTypeDto> filterNullFieldType(List<FormTypeDto> formTypeDtoList, Boolean registerForm) {
        List<FormTypeDto> retList = new ArrayList<>();
        for (FormTypeDto formTypeDto : formTypeDtoList) {
            if (!registerForm) {
                //系统类型直接保留
                if (formTypeDto.getSystemType().equals(0)) {
                    retList.add(formTypeDto);
                    continue;
                }
            }
            if (CollectionUtil.isNotEmpty(formTypeDto.getGroupFieldDataDtoList())) {
                retList.add(formTypeDto);
            }
        }
        return retList;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 5*60*1000)
    public void saveArchivesWithPhone(SaveFormDataReq req) {
        String phone = req.getPhone();
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FtbPersonnelsStaffRoster::getPhone, phone);
        wrapper.ne(FtbPersonnelsStaffRoster::getWorkerStatus,"305");
        wrapper.eq(FtbPersonnelsStaffRoster::getEnabledMark,0);
        long count = staffRosterService.count(wrapper);
        if (count > 0) throw new RuntimeException("当前员工手机号已经存在系统,请勿重复添加!");
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        FtbPersonnelsStaffRoster updateEntity = new FtbPersonnelsStaffRoster();
        //需要同步的数据
        String currRole = "";
        String headLogo = "";
        String birthday = "";
        String idCardNum = "";
        String workerName = "";
        List<SubFormFieldDto> inputFieldValueList = req.getFieldValueList();
        if (CollectionUtil.isEmpty(inputFieldValueList)) {
            throw new RuntimeException("提交数据为空");
        }
        QueryWrapper<FtbPersonnelsStaffEmploymentApply> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda()
                .eq(FtbPersonnelsStaffEmploymentApply::getPhone, phone)
                .eq(FtbPersonnelsStaffEmploymentApply::getEnabledMark, 0).last("limit 1");
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(false);
        if (CollectionUtil.isEmpty(formFeildList)) {
            log.error("未查询到字段");
            return;
        }
        // 提取姓名
        String workIdCardName = inputFieldValueList.stream()
                .filter(item -> "workerName".equals(item.getId()))
                .map(SubFormFieldDto::getUserValue)
                .findFirst()
                .orElse(null);
        // 获取租户Id
        String tenantId = UserProvider.getUser().getTenantId();
        // 校验身份证号
        inputFieldValueList.stream().filter(item -> "idCardNum".equals(item.getId())&& !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "idCardNum", a.getUserValue()) > 0) {
                throw new RuntimeException("身份证号已存在");
            }
            if (!RegexUtils.checkIdCard(a.getUserValue())) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            DateTime ageByIdCard = IdcardUtil.getBirthDate(a.getUserValue());
            DateTime dateTime = DateUtil.beginOfDay(DateUtil.date());
            if (ageByIdCard.isAfterOrEquals(dateTime)) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            // 身份证合法校验
            IdCardVerificationResponse idCardVerificationResponse = personnelIdCardVerificationUtils.idCardVerification(a.getUserValue(), workIdCardName, tenantId);
            personnelIdCardVerificationUtils.checkIdCardVerification(idCardVerificationResponse);
        });
        // 校验银行卡号
        inputFieldValueList.stream().filter(item -> "bankCardNo".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "bankCardNo", a.getUserValue()) > 0) {
                throw new RuntimeException("银行卡号已存在");
            }
        });
        // 校验公积金号
        inputFieldValueList.stream().filter(item -> "providentFundAccount".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "providentFundAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("公积金号已存在");
            }
        });
        // 校验社保账号
        inputFieldValueList.stream().filter(item -> "socialAccount".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "socialAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("社保账号已存在");
            }
        });
        Map<String, FtbPersonnelsRegistrationFormField> formFieldMap = formFeildList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormField::getId, Function.identity()));
        //写入formData数据
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(phone, null);
        Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
        //健康证几个字段
        String healthCertificate = "";
        String startHealthDate = "";
        String endHealthDate = "";
        for (SubFormFieldDto subFormFieldDto : inputFieldValueList) {
            String field = subFormFieldDto.getId();
            if (StringUtils.isEmpty(field)) {
                throw new RuntimeException("字段id不能为空");
            }
            if ( StringUtils.isEmpty(subFormFieldDto.getUserValue())) {
                subFormFieldDto.setUserValue("");
            }

            if (!AFFILIATED_GROUP_NAME.equals(field)) {
                FtbPersonnelsRegistrationFormField ftbPersonnelsRegistrationFormField = formFieldMap.get(field);
                if (null == ftbPersonnelsRegistrationFormField) {
                    throw new RuntimeException("登记表配置已更新，请退出页面后重新填写！");
                    // throw new RuntimeException(field + "字段不存在");
                }
                if (ftbPersonnelsRegistrationFormField.getIsNeedFill() == 1 && (
                        StringUtils.isEmpty(subFormFieldDto.getUserValue())
                                || "[]".equals(subFormFieldDto.getUserValue())
                )) {
                    throw new RuntimeException(ftbPersonnelsRegistrationFormField.getName() + "不能为空");
                }
                Boolean isCheck = true;

                if (ftbPersonnelsRegistrationFormField.getIsUpdateWorker() == 1 && ftbPersonnelsRegistrationFormField.getIsUpdateManager() == 1) {
                    isCheck = false;
                }

                //如果是字符串判断长度不能超限
                if (isCheck == true && (ftbPersonnelsRegistrationFormField.getType() == 0 || ftbPersonnelsRegistrationFormField.getType() == 1)) {
                    Long limits = ftbPersonnelsRegistrationFormField.getLimits();
                    if (limits != null && limits > 0) {
                        long length = StringUtils.length(subFormFieldDto.getUserValue());
                        if (length > limits) {
                            throw new RuntimeException(ftbPersonnelsRegistrationFormField.getName() + "长度不能超过" + limits + "个字符");
                        }
                    }
                }
            }
            if ("birthday".equals(subFormFieldDto.getId())) {
                birthday = subFormFieldDto.getUserValue();
                checkBirthdayFormat(birthday);
            }  else if ("idCardNum".equals(subFormFieldDto.getId())) {
                idCardNum = subFormFieldDto.getUserValue();
            } else if ("workerName".equals(subFormFieldDto.getId())) {
                workerName = subFormFieldDto.getUserValue();
                // 校验前后是否有空格
                Pattern spacesCheck = Pattern.compile(FtbRosterImportConstants.NAME_REGEX);
                Matcher spacesCheckMatcher = spacesCheck.matcher(workerName);
                if (!spacesCheckMatcher.matches()){
                    throw new RuntimeException("请使用标准格式的中文名或英文名!");
                }
            }else if ("currRole".equals(subFormFieldDto.getId())) {
                currRole = subFormFieldDto.getUserValue();
                if (StringUtils.isNotEmpty(currRole) && currRole.startsWith("{")) {
                    throw new RuntimeException("角色字段不能为json格式");
                }
            } else if ("headLogo".equals(subFormFieldDto.getId())) {
                headLogo = subFormFieldDto.getUserValue();
                if (StringUtils.isNotEmpty(headLogo) && !headLogo.startsWith("[")) {
                    throw new RuntimeException("提交的头像数据格式不正确");
                }
            } else if ("healthCertificate".equals(subFormFieldDto.getId())) {
                healthCertificate = subFormFieldDto.getUserValue();
            } else if ("startHealthDate".equals(subFormFieldDto.getId())) {
                startHealthDate = subFormFieldDto.getUserValue();
            } else if ("endHealthDate".equals(subFormFieldDto.getId())) {
                endHealthDate = subFormFieldDto.getUserValue();
            }
            personnelOrgUtils.fillRoster(updateEntity, subFormFieldDto);
            FtbPersonnelsStaffRegistrationFormData oldFormData = formFieldValueMap.get(subFormFieldDto.getId());
            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            if (null != oldFormData) {
                formData.setId(oldFormData.getId());
            }
            formData.setPhone(phone);
            formData.setFormFieldId(subFormFieldDto.getId());
            formData.setFormTypeId(subFormFieldDto.getFormTypeId());
            formData.setValue(subFormFieldDto.getUserValue());
            formDataList.add(formData);
        }
        // 身份证号码识别出生日期
        if (StringUtils.isNotEmpty(idCardNum) && !"null".equals(idCardNum) && StringUtils.isEmpty(birthday)) {
            Date birthdayDate = IdcardUtil.getBirthDate(idCardNum).toJdkDate();
            FtbPersonnelsRegistrationFormField registrationFormField = formFieldMap.get("birthday");
            FtbPersonnelsRegistrationFormField registrationFormFieldAge = formFieldMap.get("age");
            if (Objects.nonNull(registrationFormField) && Objects.nonNull(registrationFormFieldAge)) {
                FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
                formData.setPhone(phone);
                formData.setFormTypeId(registrationFormField.getFormTypeId());
                formData.setFormFieldId(registrationFormField.getId());
                formData.setValue(DateUtil.format(birthdayDate, "yyyy-MM-dd"));
                int age = personnelOrgUtils.calculateAge(personnelOrgUtils.dateToLocalDate(birthdayDate));
                FtbPersonnelsStaffRegistrationFormData formDataAge = new FtbPersonnelsStaffRegistrationFormData();
                formDataAge.setPhone(phone);
                formDataAge.setFormTypeId(registrationFormFieldAge.getFormTypeId());
                formDataAge.setFormFieldId(registrationFormFieldAge.getId());
                formDataAge.setValue(String.valueOf(age));
                formDataList.add(formDataAge);
                formDataList.add(formData);
            }
        }
        //写入数据库
        if (CollectionUtil.isNotEmpty(formDataList)) {
            updateData(formDataList);
            /*List<FtbPersonnelsStaffRegistrationFormData> updateFormData = formDataList.stream().filter(item -> StringUtils.isNotEmpty(item.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(updateFormData))  Db.updateBatchById(updateFormData);
            List<FtbPersonnelsStaffRegistrationFormData> insertFormData = formDataList.stream().filter(item -> StringUtils.isEmpty(item.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(insertFormData)) Db.saveBatch(insertFormData);*/
        }
        // 内推池状态变更
        personnelOrgUtils.sysWorkerStatusToUchisuike(phone, updateEntity.getWorkerStatus());
        LambdaQueryWrapper<FtbPersonnelsStaffEmploymentApply> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsStaffEmploymentApply::getPhone,phone);
        FtbPersonnelsStaffEmploymentApply staffEmploymentApply = staffEmploymentApplyService.getBaseMapper().selectOne(queryWrapper);
        // 根据入职填写新增 入职办理列表数据
        String certificateUserId = "";
        if (req.getSource().equals("1")) {
            if (staffEmploymentApply == null) {
                // 新增入职
                certificateUserId = onboardingData(UserProvider.getUser().getTenantId(), 4, null, phone, workerName, permissionsUtils.getRequestModule());
            }else {
                LambdaUpdateWrapper<FtbPersonnelsStaffEmploymentApply> wrapper3 = Wrappers.lambdaUpdate();
                wrapper3.set(StringUtils.isNotEmpty(workerName), FtbPersonnelsStaffEmploymentApply::getWorkerName,workerName);
                if (StringUtils.isNotEmpty(workerName)) {
                    wrapper3.set(FtbPersonnelsStaffEmploymentApply::getWorkerName,workerName);
                    String userId = staffEmploymentApply.getUserId();
                    if (userId == null){
                        String userHeadLog =  generaDefaultUserHeadLog(staffEmploymentApply.getWorkerName());
                        userId = saveUserInfo(staffEmploymentApply, userHeadLog);
                        wrapper3.set(FtbPersonnelsStaffEmploymentApply::getUserId,userId);
                    }
                    certificateUserId = userId;
                    syncWorkName(workerName, UserProvider.getUser().getTenantId(), userId);
                }
                wrapper3.set(FtbPersonnelsStaffEmploymentApply::getIdCardNum,idCardNum);
                wrapper3.set(FtbPersonnelsStaffEmploymentApply::getIsSubmitForm,1);
                wrapper3.eq(FtbPersonnelsStaffEmploymentApply::getId, staffEmploymentApply.getId());
                applyMapper.update(new FtbPersonnelsStaffEmploymentApply(),wrapper3);
            }
        }else if (req.getSource().equals("2") &&  staffEmploymentApply != null){
            String userId = staffEmploymentApply.getUserId();
            if (userId == null){
                String userHeadLog =  generaDefaultUserHeadLog(staffEmploymentApply.getWorkerName());
                userId = saveUserInfo(staffEmploymentApply, userHeadLog);
                staffEmploymentApply.setUserId(userId);
            }
            if (staffEmploymentApply.getIsSubmitForm() != 1) {
                // 代为填写
                staffEmploymentApply.setIsSubmitForm(1);
                extracted(workerName, UserProvider.getUser().getTenantId(), userId, staffEmploymentApply.getCurrOrg(),permissionsUtils.getRequestModule());
            }
            if (StringUtils.isNotEmpty(workerName)){
                staffEmploymentApply.setWorkerName(workerName);

                syncWorkName(workerName, UserProvider.getUser().getTenantId(), userId);
            }
            certificateUserId = userId;
            staffEmploymentApply.setIdCardNum(idCardNum);
            staffEmploymentApplyService.updateById(staffEmploymentApply);
        }
        // 健康证同步
        certificateInstanceService.saveHealthCertificate(certificateUserId,healthCertificate,startHealthDate,endHealthDate);
    }
    @Transactional(rollbackFor = Exception.class)
    private void updateData(List<FtbPersonnelsStaffRegistrationFormData> formDataList) {
        formDataList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getId())) {
                baseMapper.updateById(item);
            } else {
                baseMapper.insert(item);
            }
        });
    }

    /**
     * 同步员工名称
     * @param workerName
     * @param tenantId
     * @param userId
     */
    private void syncWorkName(String workerName, String tenantId, String userId){
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        UpdateUserDTO userDTO = new UpdateUserDTO();
        userDTO.setRealName(workerName);
        userDTO.setTenantId(tenantId);
        v2UserApi.updateUserInfo(userId,userDTO);
    }

    @Override
    public Boolean checkActualJoiningDatePassed(String phone, String userId) {
        doJoiningDateVerification(phone, userId);
        return true;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveArchives(SaveFormDataReq req) {
        //查询花名册
        FtbPersonnelsStaffRoster rosterEntity = staffRosterService.queryRosterInfoByUserId(req.getUserId());
        String phone = rosterEntity.getPhone();
        if (StrUtil.isEmpty(req.getPhone())) {
            req.setPhone(phone);
        }

        List<SubFormFieldDto> inputFieldValueList = req.getFieldValueList();
        if (CollectionUtil.isEmpty(inputFieldValueList)) {
            throw new RuntimeException("提交数据为空");
        }
        // 姓名
        String workerUserName = inputFieldValueList.stream()
                .filter(item -> "workerName".equals(item.getId()))
                .findFirst()
                .map(SubFormFieldDto::getUserValue)
                .orElse(null);
        // 校验身份证号
        inputFieldValueList.stream().filter(item -> "idCardNum".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "idCardNum", a.getUserValue()) > 0) {
                throw new RuntimeException("身份证号已存在");
            }
            if (!RegexUtils.checkIdCard(a.getUserValue())) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            DateTime ageByIdCard = IdcardUtil.getBirthDate(a.getUserValue());
            if (ageByIdCard.isAfter(new Date())) {
                throw new RuntimeException("请输入正确的身份证号码");
            }
            // 姓名+身份证号校验
            IdCardVerificationResponse idCardVerificationResponse = personnelIdCardVerificationUtils.idCardVerification(a.getUserValue(),
                    workerUserName, UserProvider.getUser().getTenantId());
            personnelIdCardVerificationUtils.checkIdCardVerification(idCardVerificationResponse);
        });
        // 校验银行卡号
        inputFieldValueList.stream().filter(item -> "bankCardNo".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "bankCardNo", a.getUserValue()) > 0) {
                throw new RuntimeException("银行卡号已存在");
            }
        });
        // 校验公积金号
        inputFieldValueList.stream().filter(item -> "providentFundAccount".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "providentFundAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("公积金号已存在");
            }
        });
        // 校验社保账号
        inputFieldValueList.stream().filter(item -> "socialAccount".equals(item.getId()) && !StringUtils.isEmpty(item.getUserValue())).findFirst().ifPresent(a -> {
            if (baseMapper.verifyWhetherTheDataExists(req.getPhone(), "socialAccount", a.getUserValue()) > 0) {
                throw new RuntimeException("社保账号已存在");
            }
        });
        String workerNo = personnelOrgUtils.getPhoneFormInputForField(inputFieldValueList, "workerNo");
        if (StringUtils.isNotEmpty(workerNo)) {
            List<FtbPersonnelsStaffRoster> rosterList = staffRosterService.queryRosterInfoByWorkerId(workerNo);
            if (CollectionUtil.isNotEmpty(rosterList)) {
                if (rosterList.size() > 1) {
                    throw new RuntimeException("员工工号在系统中已经存在");
                }
                FtbPersonnelsStaffRoster roster = rosterList.get(0);
                if (!roster.getId().equals(rosterEntity.getId())) {
                    throw new RuntimeException("员工工号在系统中已经存在");
                }
            }
        }
        String currReportsTo = personnelOrgUtils.getPhoneFormInputForField(inputFieldValueList, "currReportsTo");
        if (StringUtils.isNotEmpty(currReportsTo) && rosterEntity.getUserId().equals(currReportsTo)) {
            throw new RuntimeException("入职的直属主管不能是自己");
        }
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = queryFormFieldList(false);
        if (CollectionUtil.isEmpty(formFeildList)) {
            log.error("未查询到字段");
            return;
        }
        Map<String, FtbPersonnelsRegistrationFormField> formFieldMap = formFeildList.stream().collect(Collectors.toMap(FtbPersonnelsRegistrationFormField::getId, Function.identity()));

        //写入formData数据
        List<FtbPersonnelsStaffRegistrationFormData> formFieldValueList = queryFormFieldValueList(null, rosterEntity.getId());
        Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap = personnelOrgUtils.convertFormValueMap(formFieldValueList);
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        FtbPersonnelsStaffRoster updateEntity = new FtbPersonnelsStaffRoster();
        //需要同步的数据
        String affiliated = "";
        String currRole = "";
        String headLogo = "";
        String flowerName = "";
        String workerName = "";
        String workerSex = "";
        String workerStatus = "";
        String actualProbationaryDate = "";
        String birthday = "";
        String idCardNum = "";
        //健康证几个字段
        String healthCertificate = "";
        String startHealthDate = "";
        String endHealthDate = "";
        Date now = new Date();
        String actualStartDate = personnelOrgUtils.getPhoneFormInputForField(inputFieldValueList, "actualStartDate");

        for (SubFormFieldDto subFormFieldDto : inputFieldValueList) {
            String field = subFormFieldDto.getId();
            if (StringUtils.isEmpty(field)) {
                throw new RuntimeException("字段id不能为空");
            }
            if ( (
                    StringUtils.isEmpty(subFormFieldDto.getUserValue())
                            || "[]".equals(subFormFieldDto.getUserValue())
            )) {
                subFormFieldDto.setUserValue("");
            }

            if (!AFFILIATED_GROUP_NAME.equals(field)) {
                FtbPersonnelsRegistrationFormField ftbPersonnelsRegistrationFormField = formFieldMap.get(field);
                if (null == ftbPersonnelsRegistrationFormField) {
                    throw new RuntimeException(field + "字段不存在");
                }
                if (ftbPersonnelsRegistrationFormField.getIsNeedFill() == 1 &&  (
                        StringUtils.isEmpty(subFormFieldDto.getUserValue())
                                || "[]".equals(subFormFieldDto.getUserValue())
                )) {
                    throw new RuntimeException(ftbPersonnelsRegistrationFormField.getName() + "不能为空");
                }
                Boolean isCheck = true;

                if (ftbPersonnelsRegistrationFormField.getIsUpdateWorker() == 1 && ftbPersonnelsRegistrationFormField.getIsUpdateManager() == 1) {
                    isCheck = false;
                }

                //如果是字符串判断长度不能超限
                if (isCheck == true && (ftbPersonnelsRegistrationFormField.getType() == 0 || ftbPersonnelsRegistrationFormField.getType() == 1)) {
                    Long limits = ftbPersonnelsRegistrationFormField.getLimits();
                    if (limits != null && limits.longValue() > 0) {
                        long length = StringUtils.length(subFormFieldDto.getUserValue());
                        if (length > limits.longValue()) {
                            throw new RuntimeException(ftbPersonnelsRegistrationFormField.getName() + "长度不能超过" + limits + "个字符");
                        }
                    }
                }
            }
            if ("phone".equals(subFormFieldDto.getId())) {
                continue;
            } else if ("flowerName".equals(subFormFieldDto.getId())) {
                flowerName = subFormFieldDto.getUserValue();
            } else if ("workerName".equals(subFormFieldDto.getId())) {
                workerName = subFormFieldDto.getUserValue();
            } else if ("workerSex".equals(subFormFieldDto.getId())) {
                workerSex = subFormFieldDto.getUserValue();
            } else if ("workerStatus".equals(subFormFieldDto.getId())) {
                workerStatus = subFormFieldDto.getUserValue();
            } else if ("actualProbationaryDate".equals(subFormFieldDto.getId())) {
                actualProbationaryDate = subFormFieldDto.getUserValue();
            } else if ("idCardNum".equals(subFormFieldDto.getId())) {
                idCardNum = subFormFieldDto.getUserValue();
            } else if ("birthday".equals(subFormFieldDto.getId())) {
                birthday = subFormFieldDto.getUserValue();
                checkBirthdayFormat(birthday);
            } else if ("currRole".equals(subFormFieldDto.getId())) {
                currRole = subFormFieldDto.getUserValue();
                if (StringUtils.isNotEmpty(currRole) && currRole.startsWith("{")) {
                    throw new RuntimeException("角色字段不能为json格式");
                }
            } else if ("headLogo".equals(subFormFieldDto.getId())) {
                headLogo = subFormFieldDto.getUserValue();
                if (StringUtils.isNotEmpty(headLogo) && !headLogo.startsWith("[")) {
                    throw new RuntimeException("提交的头像数据格式不正确");
                }
            } else if (AFFILIATED_GROUP_NAME.equals(subFormFieldDto.getId())) {
                affiliated = subFormFieldDto.getUserValue();
            } else if ("companyAge".equals(subFormFieldDto.getId())) {
                if (StringUtils.isNotEmpty(actualStartDate)
                        && null != rosterEntity
                        && (!rosterEntity.getWorkerStatus().equals("304") || !rosterEntity.getWorkerStatus().equals("305"))) {
                    long betweenDay = 0L;
                    DateTime parse = DateUtil.parse(actualStartDate, "yyyy-MM-dd");
                    if (now.after(parse)) {
                        betweenDay = DateUtil.betweenDay(parse, now, false);
                    }
                    subFormFieldDto.setUserValue(String.valueOf(betweenDay));
                }
            } else if ("healthCertificate".equals(subFormFieldDto.getId())) {
                healthCertificate = subFormFieldDto.getUserValue();
            } else if ("startHealthDate".equals(subFormFieldDto.getId())) {
                startHealthDate = subFormFieldDto.getUserValue();
            } else if ("endHealthDate".equals(subFormFieldDto.getId())) {
                endHealthDate = subFormFieldDto.getUserValue();
            }
            personnelOrgUtils.fillRoster(updateEntity, subFormFieldDto);
            FtbPersonnelsStaffRegistrationFormData oldFormData = formFieldValueMap.get(subFormFieldDto.getId());
            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            if (null != oldFormData) {
                formData.setId(oldFormData.getId());
            }
            formData.setRosterId(rosterEntity.getId());
            formData.setPhone(phone);
            formData.setFormFieldId(subFormFieldDto.getId());
            formData.setFormTypeId(subFormFieldDto.getFormTypeId());
            formData.setValue(subFormFieldDto.getUserValue());

            formDataList.add(formData);
        }
        // 同步主管、班组
        if (StringUtils.isNotEmpty(affiliated) && !"[]".equals(affiliated)) {
            List<List<SubMulitFieldValDto>> parseGroupData = personnelOrgUtils.parseGroupData(affiliated);
            List<WorkerGroupDataDto> workerGroupDataDtoList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(parseGroupData)) {
                for (List<SubMulitFieldValDto> parseGroupDatum : parseGroupData) {
                    WorkerGroupDataDto workerGroupDataDto = new WorkerGroupDataDto();
                    for (SubMulitFieldValDto subMulitFieldValDto : parseGroupDatum) {
                        if ("affiliatedReportsTo".equals(subMulitFieldValDto.getId())) {
                            workerGroupDataDto.setReportsTo(subMulitFieldValDto.getUserValue());
                        } else if ("team".equals(subMulitFieldValDto.getId())) {
                            workerGroupDataDto.setStoreTeamId(subMulitFieldValDto.getUserValue());
                        } else if ("affiliatedRank".equals(subMulitFieldValDto.getId())) {
                            workerGroupDataDto.setAffiliatedRank(subMulitFieldValDto.getUserValue());
                        } else if ("affiliatedPosition".equals(subMulitFieldValDto.getId())) {
                            workerGroupDataDto.setAffiliatedPosition(subMulitFieldValDto.getUserValue());
                        } else if ("affiliatedOrg".equals(subMulitFieldValDto.getId())) {
                            workerGroupDataDto.setAffiliatedOrg(subMulitFieldValDto.getUserValue());
                        }
                    }
                    workerGroupDataDtoList.add(workerGroupDataDto);
                }
            }
            //同步直属主管、班组
            if (CollectionUtil.isNotEmpty(workerGroupDataDtoList)) {
                //检验直属主管不能是自己
                for (WorkerGroupDataDto workerGroupDataDto : workerGroupDataDtoList) {
                    // 获取调动后的直属主管是否是被办理用户
                    if (StringUtils.isNotEmpty(workerGroupDataDto.getReportsTo())) {
                        // 是否环形依赖
                        ActionResult<List<UserBoundVO>> usersBoundAfterDirectSupervisor = v2UserApi.getUserPrimaryBoundBatch(List.of(workerGroupDataDto.getReportsTo()), null);
                        Boolean b = v2UserApi.willFormCycle(req.getUserId(), workerGroupDataDto.getReportsTo());
                        if (b && Objects.nonNull(usersBoundAfterDirectSupervisor.getData())) {
                            UserBoundVO data = usersBoundAfterDirectSupervisor.getData().get(0);
                            String errorMsg = "被办理人是" + data.getUserName() + "的直属主管，不能互为主管！";
                            throw new RuntimeException(errorMsg);
                        }
                    }
                    if (StringUtils.isNotEmpty(workerGroupDataDto.getReportsTo()) && req.getUserId().equals(workerGroupDataDto.getReportsTo())) {
                        throw new RuntimeException("直属主管不能是自己");
                    }
                    staffRosterService.checkReportsTo(workerGroupDataDto.getReportsTo());
                }
                personnelOrgUtils.sysUserBoundList(workerGroupDataDtoList, rosterEntity.getUserId());
            }
        }

        String inputHeadLogo = getInputHeadLogo(headLogo);
        if (StringUtils.isNotEmpty(inputHeadLogo)) {
            personnelOrgUtils.sysUserHeadLog(rosterEntity.getUserId(), inputHeadLogo);
        }
        //同步姓名 花名册等信息到组织架构
        Boolean isUpdateTenant = false;
        SaveUserManagerAddDTO dto = new SaveUserManagerAddDTO();
        dto.setUserId(rosterEntity.getUserId());
        if (StringUtils.isNotEmpty(workerName)) {
            dto.setRealName(workerName);
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(workerSex)) {
            dto.setGender(Integer.valueOf(workerSex));
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(inputHeadLogo)) {
            dto.setHeadIcon(inputHeadLogo);
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(flowerName)) {
            dto.setNickName(flowerName);
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(workerStatus)) {
            dto.setJobStatus(personnelOrgUtils.convertAccountStatus(workerStatus));
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(actualProbationaryDate)) {
            dto.setBecomeDate(DateUtil.parse(actualProbationaryDate, "yyyy-MM-dd"));
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(actualStartDate)) {
            dto.setEntryDate(DateUtil.parse(actualStartDate, "yyyy-MM-dd"));
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(birthday)) {
            dto.setBirthday(DateUtil.parse(birthday, "yyyy-MM-dd"));
            isUpdateTenant = true;
        }
        if (StringUtils.isNotEmpty(idCardNum)) {
            dto.setCertificatesNumber(idCardNum);
            dto.setCertificatesType("a745d425adbb4321880817661cae8910");
            isUpdateTenant = true;
        }

        if (isUpdateTenant) {
            personnelOrgUtils.sysTenantAccountBase(dto);
        }
        // 最后入库操作
        //写入数据库
        if (CollectionUtil.isNotEmpty(formDataList)) {
            String tenantId = UserProvider.getUser().getTenantId();
            threadPoolExecutor.execute(()-> {
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException(e);
                }
                List<FtbPersonnelsStaffRegistrationFormData> updateFormData = formDataList.stream().filter(item -> StringUtils.isNotEmpty(item.getId())).collect(Collectors.toList());
                this.updateBatchById(updateFormData);
                List<FtbPersonnelsStaffRegistrationFormData> insertFormData = formDataList.stream().filter(item -> StringUtils.isEmpty(item.getId())).collect(Collectors.toList());
                this.saveBatch(insertFormData);
            });
        }
        //同步数据到入职登记表中 并且 入职登记表已经提交
        updateEntity.setId(rosterEntity.getId());
        staffRosterService.updateById(updateEntity);
        // 健康证同步
        certificateInstanceService.saveHealthCertificate(req.getUserId(),healthCertificate,startHealthDate,endHealthDate);
    }

    /**
     * 检测出生日期格式
     *
     * @param birthday
     */
    private void checkBirthdayFormat(String birthday) {
        if (StringUtils.isNotEmpty(birthday)) {
            try {
                DateUtil.parse(birthday, "yyyy-MM-dd");
            } catch (Exception e) {
                throw new RuntimeException("出生日期格式不正确。正确格式如：1999-12-03");
            }
        }
    }


    /**
     * 查询所有字段
     *
     * @return
     */
    @Override
    public List<ExportFormTypeDto> queryAllFields() {
        //查询字段类型
        List<FtbPersonnelsRegistrationFormType> formTypeList = queryFormTypeList();
        if (CollectionUtil.isEmpty(formTypeList)) {
            return new ArrayList<>();
        }
        List<ExportFormTypeDto> formTypeDtoList = BeanUtil.copyToList(formTypeList, ExportFormTypeDto.class);
        //查询字段
        List<FtbPersonnelsRegistrationFormField> formFeildList = registrationFormFieldService.list(new QueryWrapper<FtbPersonnelsRegistrationFormField>()
                .lambda()
                .eq(FtbPersonnelsRegistrationFormField::getEnabledMark, 0) //1无效 0有效
                .eq(FtbPersonnelsRegistrationFormField::getStatus, 0) //0、启用  1、禁用
                .notIn(FtbPersonnelsRegistrationFormField::getType, 5, 6, 9)
                .orderByAsc(FtbPersonnelsRegistrationFormField::getSorts));

        if (CollectionUtil.isEmpty(formFeildList)) {
            return formTypeDtoList;
        }
        List<ExportFormFieldDto> fieldList = BeanUtil.copyToList(formFeildList, ExportFormFieldDto.class);
        //按照 formTypeId 分组
        Map<String, List<ExportFormFieldDto>> formTypeFieldMap = fieldList.stream().collect(Collectors.groupingBy(ExportFormFieldDto::getFormTypeId));
        List<ExportFormTypeDto> retList = new ArrayList<>();
        for (ExportFormTypeDto exportFormTypeDto : formTypeDtoList) {
            List<ExportFormFieldDto> exportFormFieldDtoList = formTypeFieldMap.get(exportFormTypeDto.getId());
            if (CollectionUtil.isNotEmpty(exportFormFieldDtoList)) {
                exportFormTypeDto.setFieldDtoList(exportFormFieldDtoList);
                retList.add(exportFormTypeDto);
            }
        }
        return retList;
    }

    @Override
    public void addRosterIdToFormData(String phone, String rosterId) {
        //同步入职登记表已经提交的员工信息
        LambdaUpdateWrapper<FtbPersonnelsStaffRegistrationFormData> wrapper = new LambdaUpdateWrapper<FtbPersonnelsStaffRegistrationFormData>()
                .set(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId)
                .eq(FtbPersonnelsStaffRegistrationFormData::getPhone, phone);
        baseMapper.update(new FtbPersonnelsStaffRegistrationFormData(), wrapper);
    }

    @Override
    public List<FtbPersonnelsStaffRegistrationFormData> queryHasHealthExpire() {
        return baseMapper.queryHasHealthExpire();
    }

    @Override
    public void deleteByRosterId(String rosterId) {
        if (StringUtils.isEmpty(rosterId)) {
            return;
        }
        QueryWrapper<FtbPersonnelsStaffRegistrationFormData> applay = new QueryWrapper<>();
        applay.lambda().eq(FtbPersonnelsStaffRegistrationFormData::getRosterId, rosterId);
        baseMapper.delete(applay);
    }


    @Override
    public void importUpdateData(Map<String, Object> dataMap, String phone, String rosterId, Map<String, FtbPersonnelsRegistrationFormField> formFieldMap, Map<String, FtbPersonnelsStaffRegistrationFormData> formFieldValueMap) {
        //查询字段已经有的值
        //组装数据
        List<FtbPersonnelsStaffRegistrationFormData> formDataList = new ArrayList<>();
        dataMap.forEach((k, v) -> {
            if (null == v) {
                return;
            }
            FtbPersonnelsRegistrationFormField field = formFieldMap.get(k);
            if (null == field) {
                dataMap.put(k, "");
                return;
            }

            FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
            FtbPersonnelsStaffRegistrationFormData fieldValue = formFieldValueMap.get(k);
            if (k.equals("workAddress")) {
                if (null != fieldValue && StringUtils.isNotEmpty(fieldValue.getValue())) {
                    if (fieldValue.getValue().startsWith("{")) {
                        WorkAddressDto workAddressDto = JSONUtil.toBean(fieldValue.getValue(), WorkAddressDto.class);
                        if (StringUtils.isNotEmpty(workAddressDto.getAddress())) {
                            dataMap.put(k, "");
                            return;
                        }
                    }
                }
            } else if (null != fieldValue && StringUtils.isNotEmpty(fieldValue.getValue())) {
                //dataMap.put(k, "");
                return;
            }
            if (null != fieldValue) {
                formData.setId(fieldValue.getId());
            }
            formData.setRosterId(rosterId);
            formData.setPhone(phone);
            formData.setFormFieldId(field.getId());
            formData.setFormTypeId(field.getFormTypeId());
            formData.setValue(v.toString());
            formDataList.add(formData);

        });

        //写入数据库
        if (CollectionUtil.isNotEmpty(formDataList)) {
            asyncBatchUpdateFormData(formDataList);
        }
    }

    @Override
    public void batchUpdateData(List<FtbPersonnelsStaffRegistrationFormData> formDataList) {
        saveOrUpdateBatch(formDataList);
    }


    @Deprecated(since = "代码重构后此代码废弃")
    private void asyncBatchUpdateFormData(List<FtbPersonnelsStaffRegistrationFormData> formDataList) {
        String tenantId = personnelOrgUtils.getTenantId();
        Map<String, String> header = personnelOrgUtils.getHeadersForLogin();
        // personnelAsyncServiceUtils.asyncBatchUpdateFormData(formDataList, tenantId, header);
    }

    /**
     * 触发入职日期选择框时，判断是否具备修改条件；当有以下限制时，不允许修改，且页面提示：当前员工已有考勤排班记录或薪资档案，不能修改。
     * （一）当前已有该员工的薪资档案，有则不能修改
     * （二）当前员工已有考勤数据，有则不能修改
     * 判断所选日期是否在转正/调岗/晋升日期以前，如果不是则不允许提交，提示：入职日期不能晚于转正/调岗/晋升日期，需判断所选日期是否在今天之后。
     * 如果是则不允许提交，提示：入职日期不能晚于今天
     */
    private void doJoiningDateVerification(String joiningDate, String userId) {
        if (StringUtils.isEmpty(joiningDate)) {
            throw new RuntimeException("实际入职日期不能为空");
        }
        Date actualStartDate = DateUtil.parse(joiningDate, "yyyy-MM-dd").toJdkDate();
        Date now = new Date();
        if (actualStartDate.after(now)) {
            throw new RuntimeException("入职日期不能晚于今天");
        }
        // 考勤校验
        ActionResult<Boolean> userIsScheduling = attendanceDailyRuleApi.userIsScheduling(UserProvider.getUser().getTenantId(), userId);
        if (userIsScheduling.getCode() == 200 && userIsScheduling.getData()) {
            throw new RuntimeException("当前员工已有考勤排班记录，不允许修改实际入职日期");
        }
        // 薪资校验
        Boolean salaryHistory = querySalaryApi.haveSalaryHistory(userId, UserProvider.getUser().getTenantId());
        if (Objects.nonNull(salaryHistory) && salaryHistory) {
            throw new RuntimeException("当前员工已有薪资记录，不允许修改实际入职日期");
        }
        // 转正日期判断
        Date userSRegularizationDate = baseMapper.queryTheUserSRegularizationDate(userId);
        if (Objects.nonNull(userSRegularizationDate) &&  actualStartDate.after(userSRegularizationDate)) {
            throw new RuntimeException("入职日期不能晚于转正日期");
        }
        // 调岗日期判断
        Date queryUserTransferDate = baseMapper.queryUserTransferDate(userId);
        if (Objects.nonNull(queryUserTransferDate) && actualStartDate.after(queryUserTransferDate)) {
            throw new RuntimeException("入职日期不能晚于调岗日期");
        }
        // 晋升日期判断
        Date queryUserPromotionDate = baseMapper.queryUserPromotionDate(userId);
        if (Objects.nonNull(queryUserPromotionDate)  && actualStartDate.after(queryUserPromotionDate)) {
            throw new RuntimeException("入职日期不能晚于晋升日期");
        }
    }

}
