package com.zcloud.basic.info.command;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.config.client.dicttree.facade.ConfDictTreeFacade;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.message.client.message.facede.MessageFacade;
import com.jjb.saas.message.client.message.request.MessageSendCmd;
import com.jjb.saas.message.client.message.request.MessageTargetCmd;
import com.jjb.saas.system.client.user.facade.UserFacade;
import com.jjb.saas.system.client.user.request.RoleDeptAddCmd;
import com.jjb.saas.system.client.user.request.UserUpdateQuitCmd;
import com.jjb.saas.system.client.user.response.UserDetailCO;
import com.zcloud.basic.info.command.convertor.UserCoConvertor;
import com.zcloud.basic.info.command.query.CorpInfoQueryExe;
import com.zcloud.basic.info.constant.RedisConstant;
import com.zcloud.basic.info.domain.config.CodeConfig;
import com.zcloud.basic.info.domain.enums.CorpTypeEnum;
import com.zcloud.basic.info.domain.enums.UserEmploymentFlagEnum;
import com.zcloud.basic.info.domain.enums.UserFlowFlagEnum;
import com.zcloud.basic.info.domain.gateway.*;
import com.zcloud.basic.info.domain.model.*;
import com.zcloud.basic.info.dto.*;
import com.zcloud.basic.info.persistence.dataobject.*;
import com.zcloud.basic.info.persistence.repository.*;
import com.zcloud.gbscommon.utils.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhangyue
 * @Date 2025-11-04 14:07:21
 */
@Component
@AllArgsConstructor
@Slf4j
public class UserAddExe {
    private final UserGateway userGateway;
    private final UserExpandInfoGateway userExpandInfoGateway;
    private UserCoConvertor userCoConvertor;
    private final UserEmploymentLogGateway userEmploymentLogGateway;
    private final CorpInfoRepository corpInfoRepository;
    private final DepartmentRepository departmentRepository;
    private final PostRepository postRepository;
    private final UserRepository userRepository;
    @DubboReference
    private ConfDictTreeFacade confDictTreeFacade;
    @DubboReference
    private final MessageFacade messageFacade;
    private final CorpInfoQueryExe corpInfoQueryExe;
    private final UserChangeRecordGateway userChangeRecordGateway;
    private final UserCorpRecordGateway userCorpRecordGateway;
    private ZcloudRedisUtil zcloudRedisUtil;
    private final UserCorpRecordRepository userCorpRecordRepository;
    @DubboReference(check = false)
    private UserFacade userFacade;
    //    private final String sourceCode;
//    @Value("${seng.message:MS000087}")
//    public void setSourceCode(String sourceCode) {
//        this.sourceCode = sourceCode;
//    }
    private final CodeConfig codeConfig;
    private final UserExpandInfoRepository userExpandInfoRepository;
    private final ImgFilesRepository imgFilesRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(UserAddCmd cmd) {
        Boolean b = corpInfoQueryExe.verifyCorpInfo();
        if (!b) {
            throw new BizException("请先完善企业信息");
        }
        SSOUser ssoUser = AuthContext.getCurrentUser();
        Long tenantId = ssoUser.getTenantId();
        UserE userE = new UserE();
        BeanUtils.copyProperties(cmd, userE);
        userE.initAdd(tenantId, userE);
        //校验身份证是否存在
        List<UserDO> userDOList = userRepository.getByIdCard(userE.getUserIdCard(), null);
        if (CollUtil.isNotEmpty(userDOList)) {
            List<UserE> userEList = userCoConvertor.convertDOsToEs(userDOList);
            userE.checkIdCardExist(userEList);
        }
        //校验手机号
        List<Integer> employmentFlagList = Arrays.asList(UserEmploymentFlagEnum.ON.getCode(), UserEmploymentFlagEnum.ENTRY_AUDIT.getCode(), UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode());
        List<UserDO> userList = userRepository.getListByPhone(userE.getPhone(), employmentFlagList);
        if (CollUtil.isNotEmpty(userList)) {
            List<UserE> userEList = userCoConvertor.convertDOsToEs(userList);
            userE.checkPhone(userEList);
        }

        CorpInfoDO corpInfoDO = corpInfoRepository.getById(userE.getCorpinfoId());
        String corpName = null;
        UserEmploymentLogE userEmploymentLogE = new UserEmploymentLogE();
        BeanUtils.copyProperties(userE, userEmploymentLogE);
        boolean res = false;
        if (ObjectUtils.isEmpty(userE.getRoleId())) {
            Long roleId = userRepository.getDefaultRoleId();
            if (roleId == null) {
                throw new BizException("未创建默认通用角色，请联系管理员");
            }
            userE.setRoleId(roleId);
        }
        try {
            userE.setUserType(CorpTypeEnum.getUserTypeByCode(corpInfoDO.getType()));

            userE.resetPassword(corpInfoDO.getType());
            res = userGateway.add(userE);
            if (corpInfoDO != null && !ObjectUtils.isEmpty(corpInfoDO.getCorpName())) {
                corpName = corpInfoDO.getCorpName();
            }
            userEmploymentLogE.initAdd(userEmploymentLogE, corpName, userE.getId());
            userEmploymentLogGateway.add(userEmploymentLogE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executeRegister(AppUserRegisterCmd cmd) {

        UserE userE = new UserE();
        userE.checkPassword(cmd.getNewPassword(), cmd.getConfirmPassword());

        // TODO 需要修改 获取redis验证码
        if (!"369258".equals(cmd.getPhoneCode()) && !"dev".equals(codeConfig.getProfile())) {

            Object phoneCodeObj = zcloudRedisUtil.get(RedisConstant.PHONE_CODE_KEY + cmd.getPhone());
            if (phoneCodeObj == null || !phoneCodeObj.toString().equals(cmd.getPhoneCode())) {
                throw new BizException("验证码已过期或错误");
            }
            zcloudRedisUtil.del(RedisConstant.PHONE_CODE_KEY + cmd.getPhone());
        }
        //验证手机号重复
        // 12.29,不验证手机号（用户名）是否重复
//        UserDO userDO = userRepository.getByPhone(cmd.getPhone());
//        if(userDO != null){
//            throw new BizException("手机号已注册");
//        }

//          注册的时候，底座不创建用户，所以在user表插入一条用户数据即可（企业id，部门id，岗位为空）
//        CorpInfoDO corpInfoDO = corpInfoRepository.getCorpInfoByCorpName("相关方通用租户");
//        if(corpInfoDO == null){
//            throw new BizException("未创建相关方通用租户");
//        }
        List<UserDO> userList = userRepository.getListByPhone(cmd.getPhone(), null);
        if (CollUtil.isNotEmpty(userList)) {
            throw new BizException("手机号已注册");
        }

        BeanUtils.copyProperties(cmd, userE);
        userE.setPassword(cmd.getNewPassword());
        userE.encryptionPassword();
        userGateway.register(userE);

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executeRegisterYanshi(AppUserRegisterCmd cmd) {

        UserE userE = new UserE();

        BeanUtils.copyProperties(cmd, userE);
        userE.checkPassword(cmd.getNewPassword(), cmd.getConfirmPassword());
        //校验手机号
        List<Integer> employmentFlagList = Arrays.asList(UserEmploymentFlagEnum.ON.getCode(), UserEmploymentFlagEnum.ENTRY_AUDIT.getCode(), UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode());
        List<UserDO> userList = userRepository.getListByPhone(userE.getPhone(), employmentFlagList);
        if (CollUtil.isNotEmpty(userList)) {
            List<UserE> userEList = userCoConvertor.convertDOsToEs(userList);
            userE.checkPhone(userEList);
        }
        // TODO 需要修改 获取redis验证码
        if (!"369258".equals(cmd.getPhoneCode()) && !"dev".equals(codeConfig.getProfile())) {

            Object phoneCodeObj = zcloudRedisUtil.get(RedisConstant.PHONE_CODE_KEY + cmd.getPhone());
            if (phoneCodeObj == null || !phoneCodeObj.toString().equals(cmd.getPhoneCode())) {
                throw new BizException("验证码已过期或错误");
            }
            zcloudRedisUtil.del(RedisConstant.PHONE_CODE_KEY + cmd.getPhone());
        }

        userE.setUserId(Tools.get32UUID());
        userE.setTenantId(2046785341004177408L);
        userE.setCorpinfoId(2046785341004177408L);
        userE.setEmploymentFlag(1);
        userE.setPassword(Sm2Util.encryptHex(MD5.md5(cmd.getNewPassword()), userE.getPublicKey()));
        userE.setName(cmd.getPhone());
        userE.setUsername(cmd.getPhone());
        userE.setDepartmentId(2046785341004177408L);
        userE.setUserType(2);
        userE.setPostId(2048945839900323842L);
        userE.setOrgId(2046785341004177408L);
        userE.setRoleId(2008483569812549634L);
        userE.setMainCorpFlag(0);
        userE.setPersonnelType("aqglry");
        userE.setPersonnelTypeName("安全管理人员");
        userE.setEmploymentFlag(1);
        userE.setRzFlag(0);
        userGateway.addYanshi(userE);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executePerfectUserInfo(AppUserInfoCmd cmd) {

        UserE userE = new UserE();
        BeanUtils.copyProperties(cmd, userE);
        // 3-相关方
        userE.setUserType(3);
        UserDO userDO = userRepository.getById(cmd.getId());
        if (userDO == null) {
            throw new BizException("用户不存在");
        }
//       12.29 不校验身份证号
//        userRepository.checkUserIdCard(cmd.getId(),cmd.getUserIdCard());

        UserExpandInfoDO userExpandInfoDO = userExpandInfoRepository.getInfoByPhone(userDO.getPhone());
        if (userExpandInfoDO!=null &&userExpandInfoDO.getFlowFlag() != null && !userExpandInfoDO.getFlowFlag().equals(cmd.getFlowFlag())) {
                // 流动转固定
            List<UserDO> listByPhone = userRepository.getListByPhone(userDO.getPhone(), Arrays.asList(UserEmploymentFlagEnum.ON.getCode(), UserEmploymentFlagEnum.ENTRY_AUDIT.getCode(), UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode()));

            if (CollUtil.isNotEmpty(listByPhone) ) {
                throw new BizException("存在未离职信息，不能修改人员流动状态");
            }
        }
        if(AuthContext.getTenantId()==null){
            //没有企业，可以修改
            if(userExpandInfoDO ==  null){
                //新增
                UserExpandInfoE userExpandInfoE = new UserExpandInfoE();
                userExpandInfoE.setUserExpandInfoId(userDO.getId().toString());
                userExpandInfoE.setPhone(userDO.getPhone());
                userExpandInfoE.setFlowFlag(cmd.getFlowFlag());
                userExpandInfoGateway.add(userExpandInfoE);
            }else{
                if(cmd.getFlowFlag()!=null && !userExpandInfoDO.getFlowFlag().equals(cmd.getFlowFlag())) {
                    UserExpandInfoE userExpandInfoE = new UserExpandInfoE();
                    userExpandInfoE.setId(userExpandInfoDO.getId());
                    userExpandInfoE.setPhone(userDO.getPhone());
                    userExpandInfoE.setFlowFlag(cmd.getFlowFlag());
                    userExpandInfoGateway.update(userExpandInfoE);
                }
            }


        }else{
            if(userExpandInfoDO != null && !userExpandInfoDO.getFlowFlag().equals(cmd.getFlowFlag())){
                throw new BizException("该用户存在未离职信息，不能修改人员流动状态");
            }
        }
        userE.setPhone(userDO.getPhone());
        //修改手机号下除flowFlag的其他数据信息
        userE.setFlowFlag(null);
        userGateway.updateByPhone(userE);


        // 底座同步修改姓名和邮箱
        if (StringUtils.isNotEmpty(userDO.getName())) {
           if (!Objects.equals(userDO.getName(), cmd.getName()) || !Objects.equals(userDO.getEmail(), cmd.getEmail())) {
                // 判断底座是否有该用户信息，如果没有则不调用底座
                SingleResponse<UserDetailCO> detail = null;
                try {
                    log.info("updateXgf,GBS获取用户信息{}", userE.getId());
                    detail = userFacade.getDetail(cmd.getId());
                    log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));
                } catch (Exception e) {
                    log.error("updateXgf,GBS获取用户信息失败: {}", e.getMessage());
                }
                if(detail.getData() != null){
                    UserE u = new UserE();
                    u.setId(cmd.getId());
                    u.setName(cmd.getName());
                    u.setEmail(cmd.getEmail());
                    u.setPhone(userDO.getPhone());
                    userGateway.updateByAppGBS(u);
                }
            }
        }


        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean executeOnboarding(AppUserOnboardingCmd cmd) {

        /**
         * 1. 根据id，查询用户信息
         * 2. 如果该用户没有企业id，则正常入职
         * 3. 如果该用户有企业id
         * 3.1 判断该用户是流动还是固定用户
         * 3.2 如果是固定用户，则判断有未离职信息（入职，入职待审核，离职待审核）并提示（可能多条），
         *      3.2.1 如果都已离职，判断在当前企业是否有账号，
         *      3.2.2 如果有则将离职状态改为入职待审批，
         *      3.2.3 如果没有则创建一条新user数据
         * 3.3 如果是流动用户，
         * 3.3.1 如果在当前企业有账号，则判断有未离职信息则提示，如果已离职，则将离职状态改为入职待审批
         * 3.3.2 如果在当前企业没有账号，则创建一条新user数据
         * 3.3.3 新user数据的基础信息通过手机号查询该用户的其他全的信息获取过来（有身份证号信息的取第一个）
         */

        UserDO userDO = userRepository.getById(cmd.getId());

        if (userDO == null) {
            throw new BizException("用户不存在");
        }

        UserE userE = new UserE();
        UserExpandInfoDO userExpandInfoDO = userExpandInfoRepository.getInfoByPhone(userDO.getPhone());
        if (userDO.getCorpinfoId() == null) {
            BeanUtils.copyProperties(cmd, userE);

            // user表状态变为入职待审核
            userE.setEmploymentFlag(UserEmploymentFlagEnum.ENTRY_AUDIT.getCode());
            userE.setFlowFlag(userExpandInfoDO.getFlowFlag());
            userGateway.update(userE);
        } else {
            // 用户有企业id

            Integer flowFlag = userExpandInfoDO.getFlowFlag();
            if (UserFlowFlagEnum.FIXED.getCode().equals(flowFlag)) {
                // 固定用户
                String username = userDO.getUsername();
                List<UserDO> userDOS = userRepository.listByPhone(username);
                // 3.2
                if (CollUtil.isNotEmpty(userDOS)) {
                    userDOS.forEach(u -> {
                        if (UserEmploymentFlagEnum.ON.getCode().equals(u.getEmploymentFlag())
                                || UserEmploymentFlagEnum.ENTRY_AUDIT.getCode().equals(u.getEmploymentFlag())
                                || UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode().equals(u.getEmploymentFlag())) {
                            throw new BizException("该固定用户存在未离职信息，无法入职");
                        }
                    });
                }
                // 3.2.1    3.2.2
                // 在当前企业是否有账号标识，false-没有，true-有
                boolean corpFlag = false;
                if (CollUtil.isNotEmpty(userDOS)) {
                    for (UserDO u : userDOS) {
                        if (cmd.getCorpinfoId().equals(u.getCorpinfoId())) {
                            // 在当前企业有账号
                            u.setEmploymentFlag(UserEmploymentFlagEnum.ENTRY_AUDIT.getCode());
                            BeanUtils.copyProperties(u, userE);
                            userE.initFormOnboarding(cmd.getCorpinfoId(), cmd.getDepartmentId(), cmd.getPostName(), null);
                            userE.setFlowFlag(flowFlag);
                            userGateway.update(userE);
                            corpFlag = true;
                            break;
                        }
                    }
                }
                // 3.2.3
                if (!corpFlag) {
                    // 在当前企业没有账号
                    // 找到第一个 userIdCard 有值（非空且非空字符串）的数据
                    Optional<UserDO> firstUserWithIdCard = userDOS.stream()
                            .filter(user -> user.getUserIdCard() != null && !user.getUserIdCard().trim().isEmpty())
                            .findFirst();

                    if (firstUserWithIdCard.isPresent()) {
                        UserDO user = firstUserWithIdCard.get();
                        String oldUserId = user.getUserId();
                        BeanUtils.copyProperties(user, userE);
                        userE.setId(null);
                        userE.initFormOnboarding(cmd.getCorpinfoId(), cmd.getDepartmentId(), cmd.getPostName(), Tools.get32UUID());
                        userE.setFlowFlag(flowFlag);
                        userRepository.saveOnboardingUser(userE);
                        // 复制身份证照片
                        copyIdCardPhotos(oldUserId, userE.getUserId());
                    } else {
                        // 没有找到符合条件的用户
                        throw new BizException("当前用户不存在完整用户信息");
                    }
                }
            } else {
                // 流动用户
                String username = userDO.getUsername();
                List<UserDO> userDOS = userRepository.listByPhone(username);
                // 在当前企业是否有账号标识，false-没有，true-有
                boolean corpFlag = false;
                for (UserDO u : userDOS) {
                    if (cmd.getCorpinfoId().equals(u.getCorpinfoId())) {
                        // 在当前企业有账号
                        if (!UserEmploymentFlagEnum.NOT_ON.getCode().equals(u.getEmploymentFlag()) && !UserEmploymentFlagEnum.RESIGNATION.getCode().equals(u.getEmploymentFlag())) {
                            throw new BizException("该用户在当前企业存在未离职信息，无法重新入职");
                        }
                        // user表状态变为入职待审核
                        BeanUtils.copyProperties(u, userE);
                        userE.initFormOnboarding(cmd.getCorpinfoId(), cmd.getDepartmentId(), cmd.getPostName(), null);
                        userE.setFlowFlag(flowFlag);
                        userGateway.update(userE);
                        corpFlag = true;
                        break;
                    }
                }
                if (!corpFlag) {
                    // 在当前企业没有账号
                    // 找到第一个 userIdCard 有值（非空且非空字符串）的数据
                    Optional<UserDO> firstUserWithIdCard = userDOS.stream()
                            .filter(user -> user.getUserIdCard() != null && !user.getUserIdCard().trim().isEmpty())
                            .findFirst();

                    if (firstUserWithIdCard.isPresent()) {
                        UserDO user = firstUserWithIdCard.get();
                        String oldUserId = user.getUserId();
                        BeanUtils.copyProperties(user, userE);
                        userE.setId(null);
                        userE.initFormOnboarding(cmd.getCorpinfoId(), cmd.getDepartmentId(), cmd.getPostName(), Tools.get32UUID());
                        userE.setFlowFlag(flowFlag);
                        userRepository.saveOnboardingUser(userE);
                        // 复制身份证照片
                        copyIdCardPhotos(oldUserId, userE.getUserId());
                    } else {
                        // 没有找到符合条件的用户
                        throw new BizException("当前用户不存在完整用户信息");
                    }
                }
            }
        }

        // 插入user_corp_record表
        UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
        userCorpRecordE.initAddFromApp(userE, cmd.getCorpinfoName(), cmd.getDepartmentName());
        userCorpRecordGateway.add(userCorpRecordE);

        // 插入user_change_record表
        UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
        userChangeRecordE.initUserAddFromApp(userE, cmd.getCorpinfoName(), cmd.getDepartmentName());
        userChangeRecordGateway.add(userChangeRecordE);

        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean executeSendPhoneCode(UserVerifyPhoneCmd cmd) {
        // 生成6位验证码
        String phoneCode = RandomUtil.randomNumbers(6);
        Object phoneCodeCountObj = zcloudRedisUtil.get(RedisConstant.PHONE_CODE_COUNT + DateUtil.getDays() + ":" + cmd.getPhone());
        if (phoneCodeCountObj != null) {
            Integer phoneCodeCount = (Integer) phoneCodeCountObj;
            if (phoneCodeCount >= 20) {
                throw new BizException("今天验证码已发送次数已超过20次");
            }
        }

        boolean sendFlag = sendMessage(cmd.getPhone(), phoneCode);
        if (sendFlag) {
            // 发送成功
            // 放入到redis里
            zcloudRedisUtil.set(RedisConstant.PHONE_CODE_KEY + cmd.getPhone(), phoneCode, 60 * 15);
            // 设置新的验证码发送次数
            zcloudRedisUtil.set(RedisConstant.PHONE_CODE_COUNT + DateUtil.getDays() + ":" + cmd.getPhone(),
                    phoneCodeCountObj == null ? 1 : (Integer) phoneCodeCountObj + 1,
                    60 * 60 * 24);
            return true;
        }

        return false;
    }

    // 组装发送短信
    public boolean sendMessage(String phone, String phoneCode) {
        MessageSendCmd messageSendCmd = new MessageSendCmd();
        messageSendCmd.setBusinessId(UuidUtil.get32UUID());
        MessageTargetCmd messageTargetCmd = new MessageTargetCmd();
        messageTargetCmd.setMobile(phone);
        messageSendCmd.setTargetCmd(messageTargetCmd);
        messageSendCmd.setSourceCode(codeConfig.getMessage());
        messageSendCmd.setNeedTokenEnum(false);
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("code", phoneCode);
        messageSendCmd.setParams(sendParams);
        SingleResponse<Boolean> d = messageFacade.send(messageSendCmd);
        System.out.println( d.toString());
        return d == null ? false : d.getData();
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean executeXgf(UserXgfAddCmd cmd) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        Long tenantId = ssoUser.getTenantId();
        UserE userE = new UserE();
        BeanUtils.copyProperties(cmd, userE);
        userE.initAdd(tenantId, userE);
        CorpInfoDO corpInfoDO = corpInfoRepository.getById(userE.getCorpinfoId());
        userE.setUserType(CorpTypeEnum.getUserTypeByCode(corpInfoDO.getType()));
        Long roleId = userRepository.getDefaultRoleId();
        if (roleId == null) {
            throw new BizException("未创建默认通用角色，请联系管理员");
        }
        userE.setRoleId(roleId);
        List<Integer> employmentFlagList = Arrays.asList(UserEmploymentFlagEnum.ON.getCode(), UserEmploymentFlagEnum.ENTRY_AUDIT.getCode(), UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode());

        //校验身份证是否存在
        List<UserDO> userDOList = userRepository.getByIdCard(userE.getUserIdCard(), null);
        if (CollUtil.isNotEmpty(userDOList)) {
            List<UserE> userEList = userCoConvertor.convertDOsToEs(userDOList);
            userE.checkIdCardExist(userEList);
        }

        //校验手机号

        List<UserDO> userList = userRepository.getListByPhone(userE.getPhone(), null);
        Boolean addFlag = true;
        UserDO userDOUpdate = null;
        if (CollUtil.isNotEmpty(userList)) {
//            UserExpandInfoDO userExpandInfoDO = userExpandInfoRepository.getInfoByPhone(userE.getPhone());

            if (UserFlowFlagEnum.FIXED.getCode().equals(cmd.getFlowFlag())) {
                //获取在职企业信息
                userList.forEach(u -> {
                    if (UserEmploymentFlagEnum.ON.getCode().equals(u.getEmploymentFlag())
                            || UserEmploymentFlagEnum.ENTRY_AUDIT.getCode().equals(u.getEmploymentFlag())
                            || UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode().equals(u.getEmploymentFlag())) {
                        throw new BizException("该固定用户存在未离职信息，无法添加");
                    }
                });
                Optional<UserDO> optionalUserDO = userList.stream().filter(u -> AuthContext.getTenantId().equals(u.getCorpinfoId()) || u.getCorpinfoId() == null).findFirst();
                if (optionalUserDO.isPresent()) {
                    addFlag = false;
                    userDOUpdate = optionalUserDO.get();
                }
            } else {
                List<UserE> userEList = userCoConvertor.convertDOsToEs(userList);
                userE.checkXGfPhone(userEList);
                Optional<UserDO> optionalUserDO = userList.stream()
                        .filter(u -> AuthContext.getTenantId().equals(u.getCorpinfoId()) || u.getCorpinfoId() == null)
                        .findFirst();
                if (optionalUserDO.isPresent()) {
                    addFlag = false;
                    userDOUpdate = optionalUserDO.get();
                }
            }
            //userE.setUserId(userList.get(0).getUserId());
            userE.setPassword( userList.get(0).getPassword());

        }

        boolean res = false;
        if (addFlag) {
            try {
                res = userGateway.addXgf(userE);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (!res) {
                throw new BizException("保存失败");
            }

            userExpandInfoRepository.updateByPhone(cmd.getPhone(),cmd.getFlowFlag());

        } else {
            userGateway.updateXgf(userE, userDOUpdate.getId());
            //修改
            userExpandInfoRepository.updateByPhone(userE.getPhone(),userE.getFlowFlag());
        }


        //页面相关保存user_corp
        /**
         * 非流动人员用户只能在一个企业，
         * 同步gbs，流动人员企业固定
         */
        DepartmentDO departmentDO = departmentRepository.getById(userE.getDepartmentId());

        //增加用户入职企业
        UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
        BeanUtils.copyProperties(cmd, userCorpRecordE);
        userCorpRecordE.initAdd(userE, corpInfoDO.getCorpName(), departmentDO.getName());
        userCorpRecordGateway.add(userCorpRecordE);

        // 增加用户变更记录
        UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
        BeanUtils.copyProperties(cmd, userChangeRecordE);
        userChangeRecordE.initUserAdd(userE, corpInfoDO.getCorpName(), departmentDO.getName());
        userChangeRecordGateway.add(userChangeRecordE);


        return true;
    }


    public void addCorpInfo(CorpInfoAddCmd cmd) {
    }

    /**
     * 复制身份证照片从老用户到新用户
     * @param oldUserId 老用户UUID
     * @param newUserId 新用户UUID
     */
    private void copyIdCardPhotos(String oldUserId, String newUserId) {
        Map<String, Object> params = new HashMap<>();
        params.put("eqForeignKey", newUserId.toString());
        params.put("eqType", 14);
        params.put("eqDeleteEnum", "FALSE");
        List<ImgFilesDO> newExistImgFiles = imgFilesRepository.listAll(params);
        if (CollUtil.isNotEmpty(newExistImgFiles)) {
            return;
        }
        params.put("eqForeignKey", oldUserId.toString());
        List<ImgFilesDO> oldImgFiles = imgFilesRepository.listAll(params);
        if (CollUtil.isNotEmpty(oldImgFiles)) {
            List<ImgFilesDO> newImgFiles = oldImgFiles.stream().map(img -> {
                ImgFilesDO newImg = new ImgFilesDO();
                BeanUtils.copyProperties(img, newImg);
                newImg.setId(null);
                newImg.setImgFilesId(Tools.get32UUID());
                newImg.setForeignKey(newUserId.toString());
                return newImg;
            }).collect(Collectors.toList());
            imgFilesRepository.saveBatch(newImgFiles);
        }
    }
}

