package com.zcloud.basic.info.command;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.utils.AuthContext;
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.sun.xml.bind.v2.TODO;
import com.zcloud.basic.info.constant.RedisConstant;
import com.zcloud.basic.info.domain.enums.*;
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.Tools;
import com.zcloud.gbscommon.utils.ZcloudRedisUtil;
import com.zcloud.gbscommon.zcloudhidden.face.ZcloudHiddenFacade;
import com.zcloud.gbscommon.zcloudhidden.request.HiddenStatisticsListQry;
import com.zcloud.gbscommon.zcloudhidden.request.HiddenUpdateCmd;
import com.zcloud.gbscommon.zcloudhidden.response.HiddenListByUserCO;
import com.zcloud.gbscommon.zcloudrisk.facade.ZcloudRiskFacade;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

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

import static dm.jdbc.util.DriverUtil.log;


/**
 * web-app
 *
 * @Author zhangyue
 * @Date 2025-11-04 14:07:38
 */
@Component
@AllArgsConstructor
@Slf4j
public class UserUpdateExe {
    private final UserGateway userGateway;

    private final UserRepository userRepository;

    private final UserEmploymentLogGateway userEmploymentLogGateway;

    private final CorpInfoRepository corpInfoRepository;
    private final UserChangeRecordGateway userChangeRecordGateway;
    private final UserCorpRecordRepository userCorpRecordRepository;
    private final UserCorpRecordGateway userCorpRecordGateway;
    private final UserJobHandoverRepository userJobHandoverRepository;
    @DubboReference
    private UserFacade userFacade;
    private ZcloudRedisUtil zcloudRedisUtil;
    @DubboReference
    private ZcloudHiddenFacade zcloudHiddenFacade;
    @DubboReference
    private ZcloudRiskFacade zcloudRiskFacade;


    @Transactional(rollbackFor = Exception.class)
    public void execute(UserUpdateCmd userUpdateCmd) {
        //pc端不允许修改固定和流动状态
        userUpdateCmd.setFlowFlag(null);

        UserE userE = new UserE();
        BeanUtils.copyProperties(userUpdateCmd, userE);
        // 对比用户老数据与要修改数据，查看是否涉及调岗及入职
        UserDO userDO = userRepository.getInfoById(userUpdateCmd.getId());
        UserE oldUserE = new UserE();
        BeanUtils.copyProperties(userDO, oldUserE);
        //   boolean transferPositionFlag = userE.verifyTransferPosition(oldUserE, userE);
        boolean transferFlowFlag = userE.verifyTransferFlow(oldUserE, userE);
        if (transferFlowFlag) {
            List<UserCorpRecordDO> userCorpRecordDOList = userCorpRecordRepository.getInfoListByUserId(userDO.getId());
            if (CollUtil.isNotEmpty(userCorpRecordDOList)) {
                throw new BizException("该用户尚有未离职企业，不能修人员流动状态");
            }

        }
        if(!Objects.equals(userE.getUserIdCard(), userDO.getUserIdCard())){
            //判断
            userRepository.checkUserIdCard(userUpdateCmd.getId(),userUpdateCmd.getUserIdCard());
        }

        CorpInfoDO corpInfoDO = corpInfoRepository.getById(userDO.getCorpinfoId());
        if(corpInfoDO != null){
            if(corpInfoDO.getType() == CorpTypeEnum.serviceProvider.getCode()
                    || corpInfoDO.getType() == CorpTypeEnum.cargoOwner.getCode()
                    || corpInfoDO.getType() == CorpTypeEnum.portUnit.getCode()){
                // 先把其他相关方的账号找出来
                List<UserDO> userByPhoneList = userRepository.listByPhone(userDO.getPhone());
                List<Long> userIds = userByPhoneList.stream().map(UserDO::getId).collect(Collectors.toList());

                // pc端当前相关方企业修改
                boolean res = userGateway.update(userE);
                    if(!Objects.equals(userE.getPhone(), userDO.getPhone())
                            || !Objects.equals(userE.getEmail(), userDO.getEmail())
                            || !Objects.equals(userE.getName(), userDO.getName())
                         || !Objects.equals(userE.getDepartmentId(), userDO.getDepartmentId())){
                    // 判断底座是否有该用户信息，如果没有则不调用底座
                    SingleResponse<UserDetailCO> detail = null;
                    try {
                        log.info("updateXgf,GBS获取用户信息{}", userE.getId());
                        detail = userFacade.getDetail(userE.getId());
                        log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));
                    } catch (Exception e) {
                        log.error("updateXgf,GBS获取用户信息失败: {}", e.getMessage());
                    }
                    if(detail.getData() != null){
                        // 调用底座修改账号
                        userE.resetPassword(corpInfoDO.getType());
                        userGateway.updateInfoAndPasswordByGBS(userE);
                        if(!userE.getPhone().equals(userDO.getPhone())){
                            // 修改账号了，需要重置密码
                            UserE u = new UserE();
                            u.resetPassword(corpInfoDO.getType());
                            for (Long userId : userIds) {
                                userRepository.changePassword(userId, u.getPassword());
                            }
                        }
                    }
                }

                // 相关方同步修改
                boolean res2 = userGateway.updateByIds(userE, userIds);

                if (!res || !res2) {
                    throw new BizException("修改失败");
                }
            }else {
                // 企业端/监管端
                boolean res = userGateway.update(userE);
                if(!Objects.equals(userE.getPhone(), userDO.getPhone())
                        || !Objects.equals(userE.getEmail(), userDO.getEmail())
                        || !Objects.equals(userE.getName(), userDO.getName())
                        || !Objects.equals(userE.getRoleId(), userDO.getRoleId())
                || !Objects.equals(userE.getDepartmentId(), userDO.getDepartmentId())){
                    // 判断底座是否有该用户信息，如果没有则不调用底座
                    SingleResponse<UserDetailCO> detail = null;
                    try {
                        log.info("updateXgf,GBS获取用户信息{}", userE.getId());
                        detail = userFacade.getDetail(userE.getId());
                        log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));
                    } catch (Exception e) {
                        log.error("updateXgf,GBS获取用户信息失败: {}", e.getMessage());
                    }
                    if(detail.getData() != null){
                        // 调用底座修改账号
                        userGateway.updateInfoAndPasswordByGBS(userE);
                        userE.resetPassword(corpInfoDO.getType());
                        if(!userE.getPhone().equals(userDO.getPhone())){
                            // 账号修改了，需要重置密码
                            UserE u = new UserE();
                            u.resetPassword(corpInfoDO.getType());
                            userRepository.changePassword(userDO.getId(), u.getPassword());
                        }
                    }
                }
                // 保存履职记录
                if (!res) {
                    throw new BizException("修改失败");
                }
            }
        }else {
            throw new BizException("未找到该用户所属企业");
        }



      /*  if (transferPositionFlag) {
            //保存用户变更记录
            CorpInfoDO corpInfoDO = corpInfoRepository.getById(userE.getCorpinfoId());
            if (corpInfoDO != null && !ObjectUtils.isEmpty(corpInfoDO.getCorpName())) {
                corpName = corpInfoDO.getCorpName();
            }
            DepartmentDO departmentDO = departmentRepository.getById(userE.getDepartmentId());
            if (UserFlowFlagEnum.FLOW.getCode().equals(userDO.getFlowFlag())) {
                //获取
                UserCorpE userCorpE = new UserCorpE();
                BeanUtils.copyProperties(infoByUserId, userCorpE);
                oldUserE.setDepartmentId(infoByUserId.getDepartmentId());
                oldUserE.setOldFlowInfo(userCorpE);
            }
            // 增加用户变更记录
            UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
            userChangeRecordE.initUserUpdate(userE, oldUserE, corpName, departmentDO.getName());
            userChangeRecordGateway.add(userChangeRecordE);
            //TODO 处理未完成的工作


        }*/

    }

    @Transactional(rollbackFor = Exception.class)
    public void editData(UserQryCmd userUpdateCmd) {
        List<UserDO> userDOList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(userUpdateCmd.getPostId())){
            Long[] dd = new Long[]{
                    2044063902693593088L


            };
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("id", dd);
            userDOList = userRepository.list(queryWrapper);
        } else {

            Long[] dd = new Long[]{
                    2044063128479600640L,
                    2044063130157322240L,
                    2044063131436584960L,
                    2044063134028664832L,
                    2044063136746573824L,
                    2044063145072267264L,
                    2044063151921565696L,
                    2044063153364406272L,
                    2044063154748526592L,
                    2044063158569537536L,
                    2044063159794274304L,
                    2044063505375563776L,
                    2044063507149754368L,
                    2044063511138537472L,
                    2044063513051140096L,
                    2044063514351374336L,
                    2044063516767293440L,
                    2044063519271292928L,
                    2044063527332745216L,
                    2044063535813627904L,
                    2044063538644783104L,
                    2044063546525880320L,
                    2044063547779977216L,
                    2044063551496130560L,
                    2044063552787976192L,
                    2044063555484913664L,
                    2044063559549194240L,
                    2044063560841039872L,
                    2044063564733353984L,
                    2044063565995839488L,
                    2044063571540709376L,
                    2044063576691314688L,
                    2044063577895079936L,
                    2044063579174342656L,
                    2044063581690925056L,
                    2044063582928244736L,
                    2044063584132009984L,
                    2044063585360941056L,
                    2044063586602455040L,
                    2044063590578655232L,
                    2044063594949120000L,
                    2044063599084703744L,
                    2044063607523643392L,
                    2044063611885719552L,
                    2044063613093679104L,
                    2044063623411666944L,
                    2044063625815003136L,
                    2044063628503552000L,
                    2044063631099826176L,
                    2044063632467169280L,
                    2044063633733849088L,
                    2044063639136112640L,
                    2044063648980144128L,
                    2044063650494287872L,
                    2044063659780476928L,
                    2044063664595537920L,
                    2044063671021211648L,
                    2044063672275308544L,
                    2044063673516822528L,
                    2044063677522382848L,
                    2044063679988633600L,
                    2044063681330810880L,
                    2044063687605489664L,
                    2044063689023164416L,
                    2044063690205958144L,
                    2044063693968248832L,
                    2044063695633387520L,
                    2044063703455764480L,
                    2044063704818913280L,
                    2044063707205472256L,
                    2044063708413431808L,
                    2044063719578669056L,
                    2044063720748879872L,
                    2044063723148021760L,
                    2044063725744295936L,
                    2044063727140999168L,
                    2044063733457620992L,
                    2044063736095838208L,
                    2044063741267415040L,
                    2044063748087353344L,
                    2044063750650073088L,
                    2044063753124712448L,
                    2044063756840865792L,
                    2044063758342426624L,
                    2044063762184409088L,
                    2044063764914900992L,
                    2044063767288877056L,
                    2044063770472353792L,
                    2044063773106376704L,
                    2044063779485913088L,
                    2044063783692800000L,
                    2044063796250546176L,
                    2044063800348381184L,
                    2044063801703141376L,
                    2044063802873352192L,
                    2044063805343797248L,
                    2044063808971870208L,
                    2044063810133692416L,
                    2044063812587360256L,
                    2044063813782736896L,
                    2044063816211238912L,
                    2044063817599553536L,
                    2044063818908176384L,
                    2044063826499866624L,
                    2044063827678466048L,
                    2044063830190854144L,
                    2044063831386230784L,
                    2044063833957339136L,
                    2044063839128915968L,
                    2044063843293859840L,
                    2044063844522790912L,
                    2044063849832779776L,
                    2044063855088242688L,
                    2044063865225875456L,
                    2044063869009137664L,
                    2044063873304104960L,
                    2044063907684814848L,
                    2044063911543574528L

            };
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("id", dd);
             userDOList = userRepository.list(queryWrapper);
        }


        for (UserDO userDO : userDOList){
            com.jjb.saas.system.client.user.request.UserUpdateCmd updateCmd = new com.jjb.saas.system.client.user.request.UserUpdateCmd();
            updateCmd.setId(userDO.getId());
            updateCmd.setAccount(userDO.getUsername());
            updateCmd.setMobile(userDO.getPhone());
            RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
            roleDeptAddCmd.setRoleId(2008483240551297026L);
            roleDeptAddCmd.setDeptId(userDO.getDepartmentId());
            List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
            updateCmd.setRoleDepts(roleDeptAddCmdList);
            log.info("GBS修改用户开始,用户信息:{}", JSONUtil.toJsonStr(updateCmd));
            Response response = userFacade.update(updateCmd);
            log.info("GBS修改用户结束,用户id:{},结果:{}", JSONUtil.toJsonStr(response));
        }


    }

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

        // 根据手机号查询用户信息
        List<UserDO> listByPhone = userRepository.getListByPhone(cmd.getPhone(),null);
        if(CollUtil.isEmpty(listByPhone)){
            throw new BizException("手机号不存在");
        }
        UserE userE = new UserE();
        userE.checkPassword(cmd.getNewPassword(), cmd.getConfirmPassword());
        //TODO 需要修改
        if (!"369258".equals(cmd.getPhoneCode())) {
            // 获取redis验证码
            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());
        }
        BeanUtils.copyProperties(cmd, userE);
        userE.setId(listByPhone.get(0).getId());
        userE.encryptionPassword();
        userGateway.updatePassword(userE);

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updatePasswordFromApp(AppUserUpdatePassWordCmd cmd) {
        //新密码和旧密码不能相同
        if (cmd.getPassword().equals(cmd.getNewPassword())) {
            throw new BizException("新密码不能与旧密码相同");
        }
        UserE userE = new UserE();
        userE.checkPassword(cmd.getNewPassword(), cmd.getConfirmPassword());

        BeanUtils.copyProperties(cmd, userE);
        userE.encryptionPassword();
        userGateway.updatePassword(userE);
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public void executeChangePassword(Long id) {
        UserE userE = new UserE();
        UserDO userDO = userRepository.getById( id);
        CorpInfoDO corpInfoDO = corpInfoRepository.getById(userDO.getCorpinfoId());
        userE.resetPassword(corpInfoDO.getType());
        userRepository.changePassword(id, userE.getPassword());
    }


    @Transactional(rollbackFor = Exception.class)
    public Response executeUpdatePassword(UserUpdatePassWordCmd userUpdatePassWordCmd) {
        UserE userE = new UserE();
        BeanUtils.copyProperties(userUpdatePassWordCmd, userE);
        userE.encryptionPassword();
        return userGateway.updatePassword(userE);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserFaceUrl(UserUpdateFaceUrlCmd cmd) {
        UserDO userDO = userRepository.getInfoById(cmd.getId());
        if (userDO == null) {
            throw new BizException("未找到该用户");
        }
        userRepository.updateFaceByPhone(cmd.getUserAvatarUrl(),userDO.getPhone());
//        UserDO userDO = new UserDO();
//        BeanUtils.copyProperties(cmd, userDO);
//        return userRepository.updateFaceUrl(userDO);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void executeResignation(UserResignationCmd userResignationCmd) {
        //获取用户信息,并更新离职状态为离职
        UserDO userDO = userRepository.getInfoById(userResignationCmd.getUserId());
        //
        UserE userE = null;
        Long corpinfoId = userResignationCmd.getCorpinfoId() == null ? AuthContext.getTenantId() : userResignationCmd.getCorpinfoId();
        userE = new UserE();
        BeanUtils.copyProperties(userDO, userE);
        Integer employmentFlagBefore = userDO.getEmploymentFlag();
        userE.setEmploymentFlag(UserEmploymentFlagEnum.RESIGNATION.getCode());
        userGateway.update(userE);
        if (userE == null) {
            return;
        }

        //修改企业入职记录

        UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserId(userDO.getId(), corpinfoId, UserEmploymentFlagEnum.ON.getCode());
        UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
        if (userCorpRecordDO != null) {
            BeanUtils.copyProperties(userCorpRecordDO, userCorpRecordE);
            userCorpRecordE.executeResignation(userCorpRecordE, userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
            userCorpRecordGateway.update(userCorpRecordE);
        } else {
            userCorpRecordE.initResignation(userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
            userCorpRecordGateway.add(userCorpRecordE);
        }

        // 增加用户变更记录
        UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
        userChangeRecordE.executeResignation(userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode(), employmentFlagBefore);
        userChangeRecordGateway.add(userChangeRecordE);
        // 处理未完成工作
        List<UserJobHandoverDO> allJob = getUserJob(userDO.getId(), corpinfoId, userChangeRecordE.getUserChangeRecordId());
        if (CollUtil.isNotEmpty(allJob)) {
            userJobHandoverRepository.saveBatch(allJob);
//        // 离职发送,循环调用，失败的话，返回失败，
            ResignatioChangeJob(allJob);
        }

        // gbs 处理离职
        UserUpdateQuitCmd quitCmd = new UserUpdateQuitCmd();
        quitCmd.setId(userDO.getId());
        log.info("GBS离职处理开始,用户id:{},企业id:{}", userDO.getId(), corpinfoId);
        Response quit = userFacade.quit(quitCmd);
        if(!quit.isSuccess()){
            throw new IllegalArgumentException("GBS离职处理失败,用户id:"+userDO.getId()+",错误信息:"+quit.getErrMessage());
        }
        log.info("GBS离职处理结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(quit));
    }


    @Transactional(rollbackFor = Exception.class)
    public void executeReviewStatus(UserReviewStatusCmd userReviewStatusCmd) {
        //获取用户信息,并更新审核状态
        UserDO userDO = userRepository.getInfoById(userReviewStatusCmd.getUserId());
        //
        if (UserEmploymentFlagEnum.ENTRY_AUDIT.getCode().equals(userReviewStatusCmd.getEmploymentFlag())) {
            //入职待审核
            ReviewEntryAudit(userDO, userReviewStatusCmd);
        } else if (UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode().equals(userReviewStatusCmd.getEmploymentFlag())) {
            //就是离职待审核
            ReviewResignationAudit(userDO, userReviewStatusCmd);
        }

    }

    /**
     * 离职
     *
     * @param userDO
     * @param userReviewStatusCmd
     */
    private void ReviewResignationAudit(UserDO userDO, UserReviewStatusCmd userReviewStatusCmd) {
        Integer reviewStatus = userReviewStatusCmd.getReviewStatus();
        Integer employmentFlag = UserChangeRecordStatusEnum.APPROVED.getCode().equals(reviewStatus) ? UserEmploymentFlagEnum.RESIGNATION.getCode() : UserEmploymentFlagEnum.ON.getCode();
        UserE userE = null;
        Long corpinfoId = userReviewStatusCmd.getCorpinfoId() == null ? AuthContext.getTenantId() : userReviewStatusCmd.getCorpinfoId();
     /*   if (UserFlowFlagEnum.FLOW.getCode().equals(userDO.getFlowFlag())) {
            userE = userCorpRepository.executeReviewStatus(userDO.getId(), corpinfoId, employmentFlag);
        } else {*/
        userE = new UserE();
        BeanUtils.copyProperties(userDO, userE);
        userE.setEmploymentFlag(employmentFlag);
        userGateway.update(userE);
//        }
//        if (userE == null) {
//            return;
//        }
        UserE userEOld = new UserE();
        BeanUtils.copyProperties(userDO, userEOld);
        if (UserChangeRecordStatusEnum.APPROVED.getCode().equals(reviewStatus)) {
            //修改企业入职记录
            UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserStatus(userDO.getId(), corpinfoId, UserChangeRecordStatusEnum.PENDING.getCode());
            UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
            if (userCorpRecordDO != null) {
                BeanUtils.copyProperties(userCorpRecordDO, userCorpRecordE);
                userCorpRecordE.executeResignation(userCorpRecordE, userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
                userCorpRecordGateway.update(userCorpRecordE);
            } else {
                userCorpRecordE.initResignation(userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
                userCorpRecordGateway.add(userCorpRecordE);
            }
            UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
            userChangeRecordE.executeReviewStatus(userEOld, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
            userChangeRecordGateway.add(userChangeRecordE);

            //处理未完成的工作
            List<UserJobHandoverDO> allJob = userJobHandoverRepository.getListByChangerRecordId(userChangeRecordE.getUserChangeRecordId());
            if (CollUtil.isNotEmpty(allJob)) {
                ResignatioChangeJob(allJob);
            }
            log.info("GBS离职处理开始,用户id:{}", userDO.getId());
            UserUpdateQuitCmd quitCmd = new UserUpdateQuitCmd();
            quitCmd.setId(userDO.getId());
            Response quit = userFacade.quit(quitCmd);
            if(!quit.isSuccess()){
                throw new IllegalArgumentException("GBS离职处理失败,用户id:"+userDO.getId()+",错误信息:"+quit.getErrMessage());
            }
            log.info("GBS离职处理结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(quit));
        } else {
            //驳回
            UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserStatus(userDO.getId(), corpinfoId, UserChangeRecordStatusEnum.PENDING.getCode());
            UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
            if (userCorpRecordDO != null) {
                BeanUtils.copyProperties(userCorpRecordDO, userCorpRecordE);
                userCorpRecordE.executeResignation(userCorpRecordE, userE, UserEmploymentFlagEnum.ON.getCode(), UserChangeRecordStatusEnum.REJECTED.getCode());
                userCorpRecordGateway.update(userCorpRecordE);
            } else {
                userCorpRecordE.initResignation(userE, UserEmploymentFlagEnum.ON.getCode(), UserChangeRecordStatusEnum.REJECTED.getCode());
                userCorpRecordGateway.add(userCorpRecordE);
            }
            UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
            userChangeRecordE.executeReviewStatus(userEOld, UserEmploymentFlagEnum.ON.getCode(), UserChangeRecordStatusEnum.REJECTED.getCode());
            userChangeRecordGateway.add(userChangeRecordE);
            //将未完成的工作删除
            userJobHandoverRepository.deleteUserJob(userDO.getId(), corpinfoId);
        }
    }

    //入职待审核
    private void ReviewEntryAudit(UserDO userDO, UserReviewStatusCmd userReviewStatusCmd) {
        Integer reviewStatus = userReviewStatusCmd.getReviewStatus();
        // 驳回需要待处理，
        Integer employmentFlag = UserChangeRecordStatusEnum.APPROVED.getCode().equals(reviewStatus) ? UserEmploymentFlagEnum.ON.getCode() : UserEmploymentFlagEnum.NOT_ON.getCode();
        UserE userE = null;
        Long corpinfoId = userReviewStatusCmd.getCorpinfoId() == null ? AuthContext.getTenantId() : userReviewStatusCmd.getCorpinfoId();
       /* if (UserFlowFlagEnum.FLOW.getCode().equals(userDO.getFlowFlag())) {
            userE = userCorpRepository.executeReviewStatus(userDO.getId(), corpinfoId, employmentFlag);
        } else {*/
        userE = new UserE();
        BeanUtils.copyProperties(userDO, userE);
        userE.setEmploymentFlag(employmentFlag);
        Long roleId = userRepository.getDefaultRoleId();
        userE.setRoleId(roleId);
        userGateway.update(userE);
//        }
        if (userE == null) {
            return;
        }
        UserE userEOld = new UserE();
        BeanUtils.copyProperties(userDO, userEOld);
        if (UserChangeRecordStatusEnum.APPROVED.getCode().equals(reviewStatus)) {
            //增加用户入职企业.  驳回不增加下边信息
            UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserStatus(userDO.getId(), corpinfoId, UserChangeRecordStatusEnum.PENDING.getCode());
            UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
            if (userCorpRecordDO != null) {
                BeanUtils.copyProperties(userCorpRecordDO, userCorpRecordE);
                userCorpRecordE.executeEntryAudit(userCorpRecordE, userE, UserEmploymentFlagEnum.ON.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
                userCorpRecordE.setStartTime(LocalDateTime.now());
                userCorpRecordGateway.update(userCorpRecordE);
            }
            // 增加用户变更记录 ,获取变更记录
            UserChangeRecordE userChangeRecordE = new UserChangeRecordE();

            userChangeRecordE.executeReviewStatus(userEOld, UserEmploymentFlagEnum.ON.getCode(), UserChangeRecordStatusEnum.APPROVED.getCode());
            userCorpRecordE.setStartTime(LocalDateTime.now());
            userChangeRecordGateway.add(userChangeRecordE);
            SingleResponse<UserDetailCO> detail = null;
            try{
                log.info("GBS获取用户信息开始,用户id:{}", userDO.getId());
                 detail = userFacade.getDetail(userDO.getId());
                log.info("GBS获取用户信息结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(detail));
            }catch (Exception e){
                e.printStackTrace();
                log.info("GBS获取用户信息异常,用户id:{},错误信息:{}", userDO.getId(), e.getMessage());
//                throw new BizException("GBS获取用户信息异常");
            }

            if (detail!=null && detail.isSuccess() && detail.getData() != null ) {
                if( !detail.getData().getJobStatusEnum()){
                   //离职，重新入职
                    UserUpdateQuitCmd userUpdateQuitCmd = new UserUpdateQuitCmd();
                    userUpdateQuitCmd.setId(userDO.getId());
                    log.info("executeXgf,GBS恢复用户入职请求: {}",JSONUtil.toJsonStr(userUpdateQuitCmd));
                    try{
                        Response response = userFacade.restoreJob(userUpdateQuitCmd);
                        log.info("executeXgf,GBS恢复用户入职返回: {}",JSONUtil.toJsonStr(response));
                    }catch (Exception e){
                        log.info("executeXgf,GBS恢复用户入职异常: {}",e.getMessage());
                    }
                }else{
                    //在职，不处理
                }
            }else{
                com.jjb.saas.system.client.user.request.UserAddCmd userAddCmd = new com.jjb.saas.system.client.user.request.UserAddCmd();
                userAddCmd.setAccount(userDO.getPhone());
                userAddCmd.setName(userDO.getName());
                RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
                roleDeptAddCmd.setRoleId(roleId);
                roleDeptAddCmd.setDeptId(userDO.getDepartmentId());
                List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
                userAddCmd.setRoleDepts(roleDeptAddCmdList);
//            userAddCmd.setTenantId(userDO.getCorpinfoId());
                userAddCmd.setPassword(userDO.getPassword());
                userAddCmd.setId(userDO.getId());
                log.info("GBS入职处理开始,用户id:{},请求参数:{}", userDO.getId(), JSONUtil.toJsonStr(userAddCmd));
                SingleResponse<Long> gbsResult = userFacade.add(userAddCmd);
//            gbsResult.
                log.info("GBS入职处理结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(gbsResult));
                if(!gbsResult.isSuccess()){
                    throw new IllegalArgumentException("GBS入职处理失败,用户id:"+userDO.getId()+",错误信息:"+gbsResult.getErrMessage());
                }
                userDO.setId(gbsResult.getData());
            }
        } else {
            //驳回
            //驳回
            UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserStatus(userDO.getId(), corpinfoId, UserChangeRecordStatusEnum.PENDING.getCode());
            UserCorpRecordE userCorpRecordE = new UserCorpRecordE();
            if (userCorpRecordDO != null) {
                BeanUtils.copyProperties(userCorpRecordDO, userCorpRecordE);
                userCorpRecordE.executeEntryAudit(userCorpRecordE, userE, UserEmploymentFlagEnum.NOT_ON.getCode(), UserChangeRecordStatusEnum.REJECTED.getCode());
                userCorpRecordGateway.update(userCorpRecordE);
            }
            UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
            userChangeRecordE.executeReviewStatus(userEOld, UserEmploymentFlagEnum.NOT_ON.getCode(), UserChangeRecordStatusEnum.REJECTED.getCode());
            userChangeRecordGateway.add(userChangeRecordE);
        }

    }

    public void appUserResignation(AppUserResignationCmd appUserResignationCmd) {
        //更新状态，添加记录
        UserDO userDO = userRepository.getInfoById(appUserResignationCmd.getId());
        if (userDO == null) {
            throw new IllegalArgumentException("用户信息不存在");
        }
        UserE userE = null;
        Long corpinfoId = appUserResignationCmd.getCorpinfoId() == null ? AuthContext.getTenantId() : appUserResignationCmd.getCorpinfoId();
        Integer employmentFlagBefore = null;
        userE = new UserE();
        BeanUtils.copyProperties(userDO, userE);
        employmentFlagBefore = userDO.getEmploymentFlag();
        userE.setEmploymentFlag(UserEmploymentFlagEnum.RESIGNATION_AUDIT.getCode());
        userGateway.update(userE);

        UserCorpRecordDO userCorpRecordDO = userCorpRecordRepository.getInfoByUserId(userDO.getId(), corpinfoId, UserEmploymentFlagEnum.ON.getCode());
        userCorpRecordDO.setStatus(UserChangeRecordStatusEnum.PENDING.getCode());
        userCorpRecordDO.setResignationReason(appUserResignationCmd.getResignationReason());
        userCorpRecordRepository.updateById(userCorpRecordDO);
        //插入变更记录
        UserChangeRecordE userChangeRecordE = new UserChangeRecordE();
        userChangeRecordE.executeResignation(userE, UserEmploymentFlagEnum.RESIGNATION.getCode(), UserChangeRecordStatusEnum.PENDING.getCode(), employmentFlagBefore);
        userChangeRecordE.setResignationReason(appUserResignationCmd.getResignationReason());
        userChangeRecordGateway.add(userChangeRecordE);
        // 处理未完成工作
        List<UserJobHandoverDO> allJob = getUserJob(userDO.getId(), corpinfoId, userChangeRecordE.getUserChangeRecordId());
        if (CollUtil.isNotEmpty(allJob)) {
            userJobHandoverRepository.saveBatch(allJob);
        }
    }

    private List<UserJobHandoverDO> getUserJob(Long userId, Long corpinfoId, String userChangeRecordId) {
        List<UserJobHandoverDO> allJob = new ArrayList<>();
        //隐患id
        HiddenStatisticsListQry hiddenStatisticsListQry = new HiddenStatisticsListQry();
        hiddenStatisticsListQry.setUserId(userId);
        //隐患要求传入企业id
        hiddenStatisticsListQry.setDeptId(corpinfoId);
        List<HiddenListByUserCO> hiddenListCOList = null;
        try {

            log.info("获取用户隐患信息, userId: {}, corpinfoId: {}", userId, corpinfoId);
            MultiResponse<HiddenListByUserCO> hiddenListCOMultiResponse = zcloudHiddenFacade.listByUserId(hiddenStatisticsListQry);
            log.info("获取用户隐患信息返回, userId: {}, corpinfoId: {}, data: {}", userId, corpinfoId, JSONUtil.toJsonStr(hiddenListCOList));
            hiddenListCOList = hiddenListCOMultiResponse.getData();
        } catch (Exception e) {
            log.error("获取用户隐患信息异常, userId: {}, corpinfoId: {}", userId, corpinfoId, e);
        }
        if (CollUtil.isNotEmpty(hiddenListCOList)) {
            hiddenListCOList.forEach(info -> {
                UserJobHandoverDO userJobHandoverDO = new UserJobHandoverDO();
                userJobHandoverDO.setUserJobHandoverId(Tools.get32UUID());
                userJobHandoverDO.setUserId(userId);
                userJobHandoverDO.setWorkProject(info.getWorkProject());
                userJobHandoverDO.setWorkContent(info.getWorkContent());
                userJobHandoverDO.setForeignKey(info.getHiddenId());
                userJobHandoverDO.setWorkType(UserJobHandoverWorkTypeEnum.HIDDENINFO.getCode());
                userJobHandoverDO.setUserChangeRecordId(userChangeRecordId);
                userJobHandoverDO.setCorpinfoId(corpinfoId);
                allJob.add(userJobHandoverDO);
            });
        }
        //风险辨识检查
       /* ListManagerQry listManagerQry = new ListManagerQry();
        listManagerQry.setUserId(userId);
        listManagerQry.setCorpinfoId(corpinfoId);
        List<ListManagerListByUserCO> riskManagerCOList = null;
        try {
            log.info("获取用户风险辨识检查信息, userId: {}, corpinfoId: {}", userId, corpinfoId);
            MultiResponse<ListManagerListByUserCO> riskManagerCOResponse = zcloudRiskFacade.listManagerByUserId(listManagerQry);
            log.info("获取用户风险辨识检查信息返回, userId: {}, corpinfoId: {}, data: {}", userId, corpinfoId, JSONUtil.toJsonStr(riskManagerCOResponse));
            riskManagerCOList = riskManagerCOResponse.getData();
        } catch (Exception e) {
            log.error("获取用户风险辨识检查信息异常, userId: {}, corpinfoId: {}", userId, corpinfoId, e);
        }
        if (CollUtil.isNotEmpty(riskManagerCOList)) {
            riskManagerCOList.forEach(info -> {
                UserJobHandoverDO userJobHandoverDO = new UserJobHandoverDO();
                userJobHandoverDO.setUserJobHandoverId(Tools.get32UUID());
                userJobHandoverDO.setUserId(userId);
                userJobHandoverDO.setWorkProject(info.getWorkProject());
                userJobHandoverDO.setWorkContent(info.getWorkContent());
                userJobHandoverDO.setForeignKey(info.getListManagerId());
                userJobHandoverDO.setWorkType(UserJobHandoverWorkTypeEnum.RISK.getCode());
                userJobHandoverDO.setUserChangeRecordId(userChangeRecordId);
                userJobHandoverDO.setCorpinfoId(corpinfoId);
                allJob.add(userJobHandoverDO);
            });
        }*/
        return allJob;
    }

    private void ResignatioChangeJob(List<UserJobHandoverDO> allJob) {
        allJob.forEach(info -> {
            //取消工作
            UserJobHandoverWorkTypeEnum workTypeEnum = UserJobHandoverWorkTypeEnum.getByCode(info.getWorkType());
            switch (workTypeEnum) {
                case HIDDENINFO:
                    HiddenUpdateCmd cmd = new HiddenUpdateCmd();
                    cmd.setUserId(info.getUserId());
                    //隐患信息，需要传入企业id
                    cmd.setDeptId(info.getCorpinfoId());
                    zcloudHiddenFacade.updateHiddenByUserId(cmd);
                    userJobHandoverRepository.processUserJobHandover(info.getUserChangeRecordId());
                    //隐患出异常是直接抛异常
                    break;
//                case RISK:
//                    ListManagerStatusUpdateCmd riskCmd = new ListManagerStatusUpdateCmd();
//                    riskCmd.setUserId(info.getUserId());
//                    riskCmd.setCorpinfoId(info.getCorpinfoId());
//                    zcloudRiskFacade.updateListManagerStatusByUserId(riskCmd);
//                    userJobHandoverRepository.processUserJobHandover(info.getUserChangeRecordId());
                //风险辨识检查出异常是直接抛异常
//                    break;
            }

        });


    }


}
