package com.zcloud.basic.info.persistence.repository.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.PageResponse;
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.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jjb.saas.auth.client.account.facade.AccountFacade;
import com.jjb.saas.auth.client.account.request.AccountPasswordCheckCmd;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.framework.event.producer.RemoteEventPublisher;
import com.jjb.saas.framework.repository.common.PageHelper;
import com.jjb.saas.framework.repository.repo.impl.BaseRepositoryImpl;
import com.jjb.saas.system.client.role.facade.RoleFacade;
import com.jjb.saas.system.client.role.response.RoleCO;
import com.jjb.saas.system.client.user.facade.UserFacade;
import com.jjb.saas.system.client.user.request.*;
import com.jjb.saas.system.client.user.response.UserDetailCO;
import com.zcloud.basic.info.domain.enums.CorpTypeEnum;
import com.zcloud.basic.info.domain.enums.MenuEnum;
import com.zcloud.basic.info.domain.enums.UserEmploymentFlagEnum;
import com.zcloud.basic.info.domain.enums.UserTypeEnum;
import com.zcloud.basic.info.domain.model.UserE;
import com.zcloud.basic.info.persistence.dataobject.DepartmentLeaderStatictiscDO;
import com.zcloud.basic.info.persistence.dataobject.UserCorpInfoDO;
import com.zcloud.basic.info.persistence.dataobject.UserDO;
import com.zcloud.basic.info.persistence.dataobject.UserImgDO;
import com.zcloud.basic.info.persistence.mapper.UserMapper;
import com.zcloud.basic.info.persistence.repository.UserRepository;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.gbscommon.utils.Query;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.zcloudimgfiles.facade.ZcloudImgFilesFacade;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

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

/**
 * web-infrastructure
 *
 * @Author zhangyue
 * @Date 2025-11-04 14:07:37
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserRepositoryImpl extends BaseRepositoryImpl<UserMapper, UserDO> implements UserRepository {
    private final UserMapper userMapper;

    @DubboReference(check = false)
    private UserFacade userFacade;
    @DubboReference(check = false)
    private RoleFacade roleFacade;

    @DubboReference(check = false)
    private AccountFacade accountFacade;
    @Autowired
    private RemoteEventPublisher remoteEventPublisher;

    @Override
    public PageResponse<UserDO> listPage(Map<String, Object> params) {


//        ZcloudImgFilesQryCmd zcloudImgFilesQryCmd = new ZcloudImgFilesQryCmd();
//        MultiResponse<ZcloudImgFilesCO> s = zcloudImgFilesFacade.listAll(zcloudImgFilesQryCmd);
//        TodoTaskAddCmd todoTaskAddCmd = new TodoTaskAddCmd();
//        todoTaskAddCmd.setUserId(AuthContext.getCurrentUser().getUserId());
//        String busId = UuidUtil.get32UUID();
//        System.out.println(busId);
//        todoTaskAddCmd.setBusId(busId);
//        todoTaskAddCmd.setAppKey("9f41187e801e4de5843b1a9a3fe4318e");
//        todoTaskAddCmd.setTitle(DateUtil.getSdfTimes());
//        todoTaskAddCmd.setLevelEnum("IMPATIENT");
//        todoTaskAddCmd.setBusTypeEnum("ssss");
//        todoTaskAddCmd.setBusCode("wowowowo");
//        todoTaskAddCmd.setButtonName("查看");
//        todoTaskAddCmd.setContent("这是content");
//        todoTaskAddCmd.setDetailUrl("/basicInfo/container/supervision/supervision/user/list?gbs_native=true&gbs_client_id=GWJZH&paginationKeys=current,pageSize&paginationValues=1,20");
//        busTodoTaskFacade.addTask(todoTaskAddCmd);
//        HandelTaskAddCmd handelTaskAddCmd = new HandelTaskAddCmd();
//        handelTaskAddCmd.setUserId(AuthContext.getCurrentUser().getUserId());
//        handelTaskAddCmd.setBusId("08ce77d4d7fa4291bc65d62cdbbd24a1");
//        handelTaskAddCmd.setBusCode("wowowowo");
//        busTodoTaskFacade.handleTask(handelTaskAddCmd);

        if (params.get("inDepartmentId") != null) {
            Long[] inDepartmentIds = (Long[]) params.get("inDepartmentId");
            if (inDepartmentIds == null || inDepartmentIds.length == 0) {
                params.remove("inDepartmentId");
            }
        }

        IPage<UserDO> iPage = new Query<UserDO>().getPage(params);
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper = PageQueryHelper.createPageQueryWrapper(queryWrapper, params, "u.");
        queryWrapper.eq("u.delete_enum", "FALSE");
        if (!ObjectUtils.isEmpty(params.get("noMain"))) {
            queryWrapper.apply("u.id != u.corpinfo_id");
        }

        queryWrapper.orderByAsc("u.sort").orderByDesc("u.create_time");
        String menuPerms = "";
        if (!ObjectUtils.isEmpty(params.get("menuPath"))) {
            menuPerms = MenuEnum.getMenuKeyByPath(params.get("menuPath").toString());
        }
        IPage<UserDO> result = userMapper.selectUserPage(iPage, queryWrapper, menuPerms);
        return PageHelper.pageToResponse(result, result.getRecords());
    }

    @Override
    public PageResponse<UserDO> pageByNopermission(Map<String, Object> params) {
        if (params.get("inDepartmentId") != null) {
            Long[] inDepartmentIds = (Long[]) params.get("inDepartmentId");
            if (inDepartmentIds == null || inDepartmentIds.length == 0) {
                params.remove("inDepartmentId");
            }
        }
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        List<Integer> enterpriseType = CorpTypeEnum.getCodesByEnterpriseType((Integer) params.get("enterpriseType"));
        if (CollUtil.isNotEmpty(enterpriseType)) {
            params.remove("enterpriseType");
            queryWrapper.in("c.type", enterpriseType);
            queryWrapper.eq("c.use_flag", 1);
        }
        List<Integer> inType = (List<Integer>) params.get("inType");
        if (CollUtil.isNotEmpty(inType)) {
            queryWrapper.in("c.type", inType);
            queryWrapper.eq("c.use_flag", 1);
        }
        params.remove("inType");
        IPage<UserDO> iPage = new Query<UserDO>().getPage(params);

        queryWrapper = PageQueryHelper.createPageQueryWrapper(queryWrapper, params, "u.");
        queryWrapper.eq("u.delete_enum", "FALSE");
        if (!ObjectUtils.isEmpty(params.get("noMain"))) {
            queryWrapper.apply("u.id != u.corpinfo_id");
        }


        queryWrapper.orderByAsc("c.corp_order").orderByAsc("u.sort").orderByDesc("u.create_time");
        IPage<UserDO> result = userMapper.pageByNopermission(iPage, queryWrapper);
        return PageHelper.pageToResponse(result, result.getRecords());
    }

    @DubboReference
    private ZcloudImgFilesFacade zcloudImgFilesFacade;

//    @DubboReference
//    private MessageFacade messageFacade;
//
//    @DubboReference
//    private BusTodoTaskFacade busTodoTaskFacade;

//    @DubboReference
//    private ZcloudDepartmentFacade zcloudDepartmentFacade;

    @Override
    public List<UserDO> listAll(Map<String, Object> params) {
//        SSOUser ssoUsexr = AuthContext.getCurrentUser();
//        String sd = zcloudDepartmentFacade.getFullName(1999009782763397120L);
//        List<Long> ids = new ArrayList<>();
//        ids.add(1999009782763397120L);
//        Map<Long, String> sd1 = zcloudDepartmentFacade.listFullName(ids);
        if (!ObjectUtils.isEmpty(params.get("employmentFlag"))) {
            params.put("employmentFlag", params.get("employmentFlag"));
        }
        if (!ObjectUtils.isEmpty(params.get("isMyCorp"))) {
            SSOUser ssoUser = AuthContext.getCurrentUser();
            params.put("corpinfoId", ssoUser.getTenantId());
        }
        return userMapper.selectListAll(params);
    }

    @Override
    public Long getCountByCorpInfoId(Long id) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("corpinfo_id", id);
        queryWrapper.ne("id", id);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public Boolean checkUserDepartment(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("department_id", id);
        Long userCount = userMapper.selectCount(queryWrapper);
        if (userCount > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkUserDepartment(Long[] ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("department_id", ids);
        Long userCount = userMapper.selectCount(queryWrapper);
        if (userCount > 0) {
            return true;
        }
        return false;
    }

    @Override
    public UserDO getInfoById(Long id) {

        return userMapper.getInfoById(id);
    }

    @Override
    public UserDO getInfoByUserName(String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        return userMapper.getInfoByUserName(params);
    }

    @Override
    public Response countUser(Map<String, Object> params) {
        if (!ObjectUtils.isEmpty(params.get("username"))) {
            Map<String, Object> verifyParam = new HashMap<>();
            verifyParam.put("username", params.get("username"));
            verifyParam.put("id", params.get("id"));
            Integer count = userMapper.countUser(verifyParam);
            if (count > 0) {
                return Response.buildFailure("用户名已经存在，请联系管理员");
            }
        }
        if (!ObjectUtils.isEmpty(params.get("phone"))) {
            Map<String, Object> verifyParam = new HashMap<>();
            verifyParam.put("phone", params.get("phone"));
            verifyParam.put("id", params.get("id"));
            //手机号验证改成提交时验证
         /*   Integer count = userMapper.countUser(verifyParam);
            if (count > 0) {
                return Response.buildFailure("手机号已经存在，请联系管理员");
            }*/
        }
        if (!ObjectUtils.isEmpty(params.get("userIdCard"))) {
            //放在提交的时候校验
          /*  Map<String, Object> verifyParam = new HashMap<>();
            verifyParam.put("userIdCard", params.get("userIdCard"));
            verifyParam.put("id", params.get("id"));
            Integer count = userMapper.countUser(verifyParam);
            if (count > 0) {
                return Response.buildFailure("身份证号已经存在，请联系管理员");
            }*/
        }

        return Response.buildSuccess();
    }

    @Override
    public List<UserDO> listByPostId(Long postId) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId);
        queryWrapper.eq("delete_enum", "FALSE");
        queryWrapper.orderByAsc("sort").orderByDesc("create_time");
        List userPostList = this.list(queryWrapper);
        return userPostList;
    }

    @Override
    public List<UserDO> listByPostIds(Long[] postIds) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper();
        queryWrapper.in("post_id", postIds);
        queryWrapper.eq("delete_enum", "FALSE");
        queryWrapper.orderByAsc("sort").orderByDesc("create_time");
        List<UserDO> userPostList = this.list(queryWrapper);
        return userPostList;
    }

    @Override
    public List<UserDO> listByCorpInfoId(Long corpInfoId) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper();
        queryWrapper.eq("corpinfo_id", corpInfoId);
        queryWrapper.eq("delete_enum", "FALSE");
        queryWrapper.orderByAsc("sort").orderByDesc("create_time");
        return list(queryWrapper);
    }

    @Override
    public void addCorpUser(UserE userE) {
        UserDO userDo = new UserDO();
        BeanUtils.copyProperties(userE, userDo);
        if (userDo.getUserId() == null) {
            userDo.setUserId(Tools.get32UUID());
        }
        // 新增企业时，主账号默认入职
        userDo.setEmploymentFlag(1);
        save(userDo);
        userE.setId(userDo.getId());
    }

    @Override
    public void saveUser(UserDO userDO) {
        if (StringUtils.isEmpty(userDO.getUsername())) {
            userDO.setUsername(userDO.getPhone());
        }

        UserAddCmd userAddCmd = new UserAddCmd();
        userAddCmd.setAccount(userDO.getUsername());
        userAddCmd.setName(userDO.getName());
        userAddCmd.setPassword(userDO.getPassword());
        RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
        roleDeptAddCmd.setRoleId(userDO.getRoleId());
        roleDeptAddCmd.setDeptId(userDO.getDepartmentId());
        List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
        userAddCmd.setRoleDepts(roleDeptAddCmdList);
        log.info("GBS新增用户开始,用户信息:{}", JSONUtil.toJsonStr(userAddCmd));
        SingleResponse<Long> gbsResult = userFacade.add(userAddCmd);
        log.info("GBS新增用户结束,用户id:{},结果:{}", gbsResult.getData(), JSONUtil.toJsonStr(gbsResult));
        if (!gbsResult.isSuccess()) {
            throw new RuntimeException("GBS新增用户失败,用户id:" + gbsResult.getData());
        }
        userDO.setId(gbsResult.getData());
        if (userDO.getSort() == null) {
            userDO.setSort(9999);
        }
        // 新增用户默认在职
        userDO.setEmploymentFlag(1);
        save(userDO);
    }

    @Override
    public void saveUserYanshi(UserDO userDO) {
        if (StringUtils.isEmpty(userDO.getUsername())) {
            userDO.setUsername(userDO.getPhone());
        }

        UserAddCmd userAddCmd = new UserAddCmd();
        userAddCmd.setAccount(userDO.getUsername());
        userAddCmd.setName(userDO.getName());
        userAddCmd.setTenantId(userDO.getTenantId());
        userAddCmd.setPassword(userDO.getPassword());
        RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
        roleDeptAddCmd.setRoleId(userDO.getRoleId());
        roleDeptAddCmd.setDeptId(userDO.getDepartmentId());
        List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
        userAddCmd.setRoleDepts(roleDeptAddCmdList);
        log.info("GBS新增用户开始,用户信息:{}", JSONUtil.toJsonStr(userAddCmd));
        SingleResponse<Long> gbsResult = userFacade.add(userAddCmd);
        log.info("GBS新增用户结束,用户id:{},结果:{}", gbsResult.getData(), JSONUtil.toJsonStr(gbsResult));
        if (!gbsResult.isSuccess()) {
            throw new RuntimeException("GBS新增用户失败,用户id:" + gbsResult.getData());
        }
        userDO.setId(gbsResult.getData());
        if (userDO.getSort() == null) {
            userDO.setSort(9999);
        }
        // 新增用户默认在职
        userDO.setEmploymentFlag(1);
        save(userDO);
    }

    @Override
    public void saveRegisterUser(UserDO userDO) {
        if (StringUtils.isEmpty(userDO.getUsername())) {
            userDO.setUsername(userDO.getPhone());
        }

//        userDO.setId(Tools);
        if (userDO.getSort() == null) {
            userDO.setSort(9999);
        }
        // 新增用户默认 3-未入职
        userDO.setEmploymentFlag(UserEmploymentFlagEnum.NOT_ON.getCode());
        // 默认不是主账号
        userDO.setMainCorpFlag(0);
        userDO.setUserId(Tools.get32UUID());
        // 相关方
        userDO.setCorpinfoId(null);
        // 默认是相关方
        userDO.setUserType(UserTypeEnum.XGF.getCode());
        save(userDO);
    }

    @Override
    public void saveOnboardingUser(UserE userE) {
        if (StringUtils.isEmpty(userE.getUsername())) {
            userE.setUsername(userE.getPhone());
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userE, userDO);
        save(userDO);
        userE.setId(userDO.getId());
    }

    @Override
    public void saveUserXgf(UserDO userDO) {
        if (StringUtils.isEmpty(userDO.getUsername())) {
            userDO.setUsername(userDO.getPhone());
        }
//        userDO.setId(gbsResult.getData());

        if (userDO.getSort() == null) {
            userDO.setSort(9999);
        }
        save(userDO);
        UserAddCmd userAddCmd = new UserAddCmd();
        userAddCmd.setAccount(userDO.getUsername());
        userAddCmd.setName(userDO.getName());
        RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
        roleDeptAddCmd.setRoleId(userDO.getRoleId());
        roleDeptAddCmd.setDeptId(userDO.getDepartmentId());
        List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
        userAddCmd.setRoleDepts(roleDeptAddCmdList);
        userAddCmd.setId(userDO.getId());
        userAddCmd.setPassword(userDO.getPassword());
        log.info("GBS新增用户开始,用户信息:{}", JSONUtil.toJsonStr(userAddCmd));
        SingleResponse<Long> gbsResult = userFacade.add(userAddCmd);
        log.info("GBS新增用户结束,用户id:{},结果:{}", gbsResult.getData(), JSONUtil.toJsonStr(gbsResult));
        if (!gbsResult.isSuccess()) {
            throw new RuntimeException("GBS新增用户失败,用户id:" + gbsResult.getData());
        }

    }

    @Override
    public void updateInfoById(UserDO userDO) {
        updateById(userDO);
        UserUpdateCmd userUpdateCmd = new UserUpdateCmd();
        userUpdateCmd.setId(userDO.getId());
        userUpdateCmd.setAccount(userDO.getUsername());
        userUpdateCmd.setName(userDO.getName());
        log.info("GBS更新用户开始,用户信息:{}", JSONUtil.toJsonStr(userUpdateCmd));
        Response response = userFacade.update(userUpdateCmd);
        log.info("GBS更新用户结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(response));
    }

    @Override
    public void deleteUserById(Long id) {
        UpdateWrapper<UserDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .eq("delete_enum", "FALSE")
                .set("delete_enum", "TRUE");
        update(updateWrapper);
        userFacade.delete(id);
    }

    @Override
    public void changePassword(Long id, String password) {
        //修改这个手机号下所有密码
        UserDO userDO = getById(id);
        if (userDO == null) {
            return;
        }
        String phone = userDO.getPhone();

        List<UserDO> userDOList = getListByPhone(phone, null);
        for (UserDO userDO1 : userDOList) {
            userChangePassword(userDO1.getId(), password);
        }
    }

    private void userChangePassword(Long id, String password) {
        //更新本地密码
        UserDO userDOUpdate = new UserDO();
        userDOUpdate.setId(id);
        userDOUpdate.setPassword(password);
        updateById(userDOUpdate);
        SingleResponse<UserDetailCO> detail = null;
        try {
            log.info("updateXgf,GBS获取用户信息{}", id);
            detail = userFacade.getDetail(id);
            log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));
        } catch (Exception e) {
            log.error("updateXgf,GBS获取用户信息失败: {}", e.getMessage());
        }
        if (detail.getData() != null) {
            //更新gbs密码
            UserUpdatePasswordCmd userUpdatePasswordCmd = new UserUpdatePasswordCmd();
            userUpdatePasswordCmd.setId(id);
            userUpdatePasswordCmd.setPassword(password);
            log.info("更新用户密码id：{}", id);
            Response response = userFacade.updatePassword(userUpdatePasswordCmd);
            log.info("更新密码结果：{}", response);
        }

    }

    @Override
    public void updateUserName(UserDO userDO) {
        updateById(userDO);
        if (!ObjectUtils.isEmpty(userDO.getName())) {
            UserUpdateCmd userUpdateCmd = new UserUpdateCmd();
            userUpdateCmd.setId(userDO.getId());
            userUpdateCmd.setName(userDO.getName());
            userUpdateCmd.setAccount(userDO.getName());
            log.info("GBS更新用户开始,用户信息:{}", JSONUtil.toJsonStr(userUpdateCmd));
            Response response = userFacade.update(userUpdateCmd);
            log.info("GBS更新用户结束,用户id:{},结果:{}", userDO.getId(), JSONUtil.toJsonStr(response));
        }
    }

    @Override
    public Map<Long, String> getDepartmentLeaderByDepartmentId(List<Long> departmentIds) {
        List<DepartmentLeaderStatictiscDO> departmentLeaderList = userMapper.getDepartmentLeaderByDepartmentId(departmentIds);
        Map<Long, String> departmentLeaderMap = departmentLeaderList.stream()
                .collect(Collectors.toMap(DepartmentLeaderStatictiscDO::getDepartmentId, DepartmentLeaderStatictiscDO::getDepartmentLeaderNameList));
        return departmentLeaderMap;
    }

    @Override
    public Long getDefaultRoleId() {
        MultiResponse<RoleCO> multiResponse = roleFacade.listRoles();
        if (multiResponse.isSuccess()) {
            List<RoleCO> roleCOList = multiResponse.getData();
            for (RoleCO roleCO : roleCOList) {
                if (roleCO.getRoleName().contains("普通用户") || roleCO.getRoleName().contains("个人账号")) {
                    return roleCO.getId();
                }
            }
        }
        return null;
    }

    @Override
    public Map<String, Long> getRoleMap() {
        MultiResponse<RoleCO> multiResponse = roleFacade.listRoles();
        if (multiResponse.isSuccess()) {

            return multiResponse.getData().stream()
                    .collect(Collectors.toMap(RoleCO::getRoleName, RoleCO::getId));
        }
        return null;
    }

    @Override
    public Response updatePassword(UserDO userDO) {
        UserDO oldUserDO = getById(userDO.getId());
        //  TODO 验证老密码是否正确
        if (userDO.getPassword() != null && !userDO.getPassword().equals("")) {
            SingleResponse<UserDetailCO> detail = null;
            try {
                log.info("updateXgf,GBS获取用户信息{}", userDO.getId());
                detail = userFacade.getDetail(userDO.getId());
                log.info("updateXgf,GBS获取用户信息返回: {}", JSONUtil.toJsonStr(detail));
            } catch (Exception e) {
                log.error("updateXgf,GBS获取用户信息失败: {}", e.getMessage());
            }
            if (detail.getData() != null) {
                AccountPasswordCheckCmd accountPasswordCheckCmd = new AccountPasswordCheckCmd();
                accountPasswordCheckCmd.setUserId(userDO.getId());
                accountPasswordCheckCmd.setPassword(userDO.getPassword());
                log.info("updateXgf,GBS验证用户密码请求:{}", JSONUtil.toJsonStr(accountPasswordCheckCmd));
                SingleResponse<Long> response = accountFacade.checkPassword(accountPasswordCheckCmd);
                log.info("updateXgf,GBS验证用户密码返回:{}", JSONUtil.toJsonStr(response));
                if (!response.isSuccess()) {
                    throw new BizException("原密码不正确");
                }
            } else {
                //验证本地密码
                UserE userE = new UserE();
                Boolean checkUserPassword = userE.checkUserEncryptionPassword(userDO.getPassword(), oldUserDO.getPassword());
                log.info("updateXgf,验证用户本地密码结果:{}", checkUserPassword);
                if (!checkUserPassword) {
                    throw new BizException("密码错误");
                }
            }
        } else {
            log.info("updateXgf,密码为空，不进行密码验证");
        }

        //修改多个密码
        String phone = oldUserDO.getPhone();

        List<UserDO> userDOList = getListByPhone(phone, null);
        for (UserDO userDO1 : userDOList) {
            userChangePassword(userDO1.getId(), userDO.getNewPassword());
        }
        return Response.buildSuccess();

    }

    @Override
    public Boolean updateFaceUrl(UserDO userDO) {
        return updateById(userDO);
    }

    @Override
    public List<UserDO> listByPhone(String phone) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return list(queryWrapper);
    }

    @Override
    public UserDO getEncryInfo(UserE userE) {
        //   验证老密码是否正确
        AccountPasswordCheckCmd accountPasswordCheckCmd = new AccountPasswordCheckCmd();
        accountPasswordCheckCmd.setUserId(AuthContext.getUserId());
        accountPasswordCheckCmd.setPassword(userE.getPassword());
        SingleResponse<Long> response = accountFacade.checkPassword(accountPasswordCheckCmd);
        if (!response.isSuccess()) {
            throw new BizException("密码错误");
        }
        return getById(userE.getId());
    }

    @Override
    public Boolean checkUserPassWordEncryInfo(String password) {
        //   验证老密码是否正确
        AccountPasswordCheckCmd accountPasswordCheckCmd = new AccountPasswordCheckCmd();
        accountPasswordCheckCmd.setUserId(AuthContext.getUserId());
        accountPasswordCheckCmd.setPassword(password);
        SingleResponse<Long> response = accountFacade.checkPassword(accountPasswordCheckCmd);
        if (!response.isSuccess()) {
            return false;
        }
        return true;
    }

    @Override
    public PageResponse<UserDO> listXgf(Map<String, Object> params) {
        IPage<UserDO> iPage = new Query<UserDO>().getPage(params);
        String menuPerms = "";
        if (!ObjectUtils.isEmpty(params.get("menuPath"))) {
            menuPerms = MenuEnum.getMenuKeyByPath(params.get("menuPath").toString());
        }
        IPage<UserDO> result = userMapper.listXgf(iPage, params, menuPerms);
        return PageHelper.pageToResponse(result, result.getRecords());
    }

    @Override
    public UserDO getByPhoneAndIdCard(String phone, String idCardNumber) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("user_id_card", idCardNumber);
        return getOne(queryWrapper);
    }

    @Override
    public void checkUserIdCard(Long id, String userIdCard) {
        Map<String, Object> verifyParam = new HashMap<>();
        verifyParam.put("userIdCard", userIdCard);
        verifyParam.put("id", id);
        Integer count = userMapper.countUser(verifyParam);
        if (count > 0) {
            throw new BizException("身份证号已经存在，请联系管理员");
        }
    }

    @Override
    public List<UserDO> getListByPhone(String phone, List<Integer> employmentFlagList) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        if (CollUtil.isNotEmpty(employmentFlagList)) {
            queryWrapper.in("employment_flag", employmentFlagList);
        }
        queryWrapper.eq("phone", phone);
        queryWrapper.orderByAsc("create_time");
        return list(queryWrapper);
    }

    @Override
    public List<UserDO> getByIdCard(String userIdCard, List<Integer> employmentFlagList) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        if (CollUtil.isNotEmpty(employmentFlagList)) {
            queryWrapper.in("employment_flag", employmentFlagList);
        }
        queryWrapper.eq("user_id_card", userIdCard);
        queryWrapper.orderByAsc("create_time");
        return list(queryWrapper);
    }

    @Override
    public List<UserCorpInfoDO> getListByUserIds(List<Long> userIds) {
        return userMapper.getListByUserIds(userIds);
    }

    @Override
    @Transactional
    public void updateXgf(UserE userE) {
        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 != null && detail.isSuccess() && detail.getData() != null && !detail.getData().getJobStatusEnum()) {
            UserUpdateQuitCmd userUpdateQuitCmd = new UserUpdateQuitCmd();
            userUpdateQuitCmd.setId(userE.getId());
            log.info("updateXgf,GBS恢复用户入职请求: {}", JSONUtil.toJsonStr(userUpdateQuitCmd));
            Response response = userFacade.restoreJob(userUpdateQuitCmd);
            log.info("updateXgf,GBS恢复用户入职返回: {}", JSONUtil.toJsonStr(response));
        } else {
            com.jjb.saas.system.client.user.request.UserAddCmd userAddCmd = new com.jjb.saas.system.client.user.request.UserAddCmd();
            userAddCmd.setAccount(userE.getUsername());
            userAddCmd.setName(userE.getName());
//            userAddCmd.setPassword(userE.getPassword());
            RoleDeptAddCmd roleDeptAddCmd = new RoleDeptAddCmd();
            roleDeptAddCmd.setRoleId(userE.getRoleId());
            roleDeptAddCmd.setDeptId(userE.getDepartmentId());
            List<RoleDeptAddCmd> roleDeptAddCmdList = Collections.singletonList(roleDeptAddCmd);
            userAddCmd.setRoleDepts(roleDeptAddCmdList);
            userAddCmd.setId(userE.getId());
            log.info("GBS新增用户开始,用户信息:{}", JSONUtil.toJsonStr(userAddCmd));
            SingleResponse<Long> gbsResult = userFacade.add(userAddCmd);
            log.info("GBS新增用户结束,用户id:{},结果:{}", gbsResult.getData(), JSONUtil.toJsonStr(gbsResult));
            if (!gbsResult.isSuccess()) {
                throw new RuntimeException("GBS新增用户失败,用户id:" + gbsResult.getData());
            }
        }
    }

    @Override
    public void deletedUserByPhone(String phone) {
        userMapper.deletedUserByPhone(phone);
    }

    @Override
    public UserDO getUserIdByPhone(String phone) {
        return userMapper.getUserIdByPhone(phone);
    }

    @Override
    public void updateFaceByPhone(String userAvatarUrl, String phone) {

        userMapper.updateFaceByPhone(userAvatarUrl, phone);
    }

    @Override
    public void deleteByCorpInfoId(Long corpInfoId) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("corpinfo_id", corpInfoId);
        updateWrapper.set("delete_enum", "TRUE");
        update(updateWrapper);
    }

    @Override
    public List<UserImgDO> listBase64ByUrl(Map<String, Object> params) {
        return userMapper.listBase64ByUrl(params);
    }

    @Override
    public List<UserDO> getUserListByUserId(String foreignKey) {
            QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", foreignKey);
            queryWrapper.eq("delete_enum", "FALSE");
            UserDO one = getOne(queryWrapper);

            if (one == null || StringUtils.isEmpty(one.getPhone())) {
                return new ArrayList<>();
            }

            QueryWrapper<UserDO> queryWrapperList = new QueryWrapper<>();
            queryWrapperList.eq("phone", one.getPhone());
            queryWrapperList.eq("delete_enum", "FALSE");
            queryWrapperList.orderByAsc("create_time");
            return list(queryWrapperList);
    }
}

