package com.kidgrow.usercenter.service.impl;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kidgrow.common.constant.CommonConstant;
import com.kidgrow.common.constant.DictionariesConstants;
import com.kidgrow.common.constant.SecurityConstants;
import com.kidgrow.common.context.ClientContextHolder;
import com.kidgrow.common.lock.DistributedLock;
import com.kidgrow.common.model.SysMenu;
import com.kidgrow.common.model.SysRole;
import com.kidgrow.common.model.SysUser;
import com.kidgrow.common.model.*;
import com.kidgrow.common.service.impl.SuperServiceImpl;
import com.kidgrow.common.utils.AesUtils;
import com.kidgrow.common.utils.DateUtils;
import com.kidgrow.common.utils.Pinyin4jUtil;
import com.kidgrow.oprationcenter.feign.ProductOrderService;
import com.kidgrow.redis.util.RedisUtils;
import com.kidgrow.sms.feign.SmsChuangLanService;
import com.kidgrow.sms.model.ConstantSMS;
import com.kidgrow.usercenter.mapper.*;
import com.kidgrow.usercenter.model.SysDoctor;
import com.kidgrow.usercenter.model.*;
import com.kidgrow.usercenter.service.*;
import com.kidgrow.usercenter.vo.HospitalDoctorListVo;
import com.kidgrow.usercenter.vo.UserRegVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
/**
* 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020
*
* @Description:
* @Project:
* @CreateDate: Created in 2020/2/13 16:33
* @Author: liuke
*/
@Slf4j
@Service
public class SysUserServiceImpl extends SuperServiceImpl implements ISysUserService {
private final static String LOCK_KEY_USERNAME = CommonConstant.LOCK_KEY_PREFIX + "username:";
@Autowired
private PasswordEncoder passwordEncoder;
@Resource
private ISysRoleUserService roleUserService;
@Resource
private ISysDictionariesService sysDictionariesService;
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Autowired
private ISysOrganizationService organizationService;
@Autowired
private ISysHospitalService hospitalService;
@Autowired
private ISysDepartmentService departmentService;
@Autowired
private ISysUserOrgService iSysUserOrgService;
@Autowired
private RedisUtils redisUtils;
@Autowired
private SmsChuangLanService smsChuangLanService;
@Autowired
private DistributedLock lock;
@Autowired
private SysDoctorMapper sysDoctorMapper;
@Autowired
private SysRoleMapper sysRoleMapper;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private SysOrganizationMapper sysOrganizationMapper;
@Autowired
private ProductOrderService productOrderService;
@Override
public LoginAppUser findByUsername(String username) {
SysUser sysUser = this.selectByUsername(username);
if (sysUser == null) {
return null;
} else {
return getLoginAppUser(sysUser);
}
}
@Override
public LoginAppUser findByOpenId(String username) {
SysUser sysUser = this.selectByOpenId(username);
if (sysUser == null) {
return null;
} else {
return getLoginAppUser(sysUser);
}
}
@Override
public LoginAppUser findByMobile(String username) {
SysUser sysUser = this.selectByMobile(username);
return getLoginAppUser(sysUser);
}
/**
* 获取登录用户的一系列信息 hrj 06-04修改
*
* @param sysUserNew
* @return
*/
@Override
public LoginAppUser getLoginAppUser(SysUser sysUserNew) {
log.error(sysUserNew.toString());
LoginAppUser loginAppUser = new LoginAppUser();
SysUser sysUser = this.baseMapper.selectById(sysUserNew);
if (sysUser != null) {
BeanUtils.copyProperties(sysUser, loginAppUser);
//获取用户所属组织机构列表
loginAppUser.setDefaultAuth(sysUser.getDefaultAuth());
List sysOrganizations = organizationService.findListByUserId(sysUser.getId());
//设置组织机构集合
if (sysOrganizations != null) {
loginAppUser.setOrganizations(sysOrganizations);
}
List sysRoles = roleUserService.findRolesByUserId(sysUser.getId());
// 设置角色
loginAppUser.setRoles(sysRoles);
if (!CollectionUtils.isEmpty(sysRoles)) {
Set roleIds = sysRoles.parallelStream().map(SuperEntity::getId).collect(Collectors.toSet());
List menus = roleMenuMapper.findMenusByRoleIds(roleIds, CommonConstant.PERMISSION);
if (!CollectionUtils.isEmpty(menus)) {
Set permissions = menus.parallelStream().map(p -> p.getPath())
.collect(Collectors.toSet());
// 设置权限集合
loginAppUser.setPermissions(permissions);
}
}
//医院信息
DoctorUserAll doctorUserAllVo = baseMapper.findDoctorUserAllData(sysUser.getId());
if (doctorUserAllVo != null) {
loginAppUser.setDoctorUserAllVO(doctorUserAllVo);
//是否医院管理员
loginAppUser.setHAdminUser(doctorUserAllVo.getIsAdminUser());
}
}
return loginAppUser;
}
/**
* 根据用户名查询用户
*
* @param username
* @return
*/
@Override
public SysUser selectByUsername(String username) {
String clientId = ClientContextHolder.getClient();
List users = baseMapper.selectList(
//new QueryWrapper().eq("username", username).eq("tenant_id", clientId)
new QueryWrapper().eq("username", username)
);
return getUser(users);
}
/**
* 根据手机号查询用户
*
* @param mobile
* @return
*/
@Override
public SysUser selectByMobile(String mobile) {
List users = baseMapper.selectList(
new QueryWrapper().eq("mobile", mobile)
);
return getUser(users);
}
/**
* 根据openId查询用户
*
* @param openId
* @return
*/
@Override
public SysUser selectByOpenId(String openId) {
List users = baseMapper.selectList(
new QueryWrapper().eq("open_id", openId)
);
return getUser(users);
}
private SysUser getUser(List users) {
SysUser user = null;
if (users != null && !users.isEmpty()) {
user = users.get(0);
}
return user;
}
/**
* 给用户设置角色
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void setRoleToUser(Long id, Set roleIds) {
SysUser sysUser = baseMapper.selectById(id);
if (sysUser == null) {
throw new IllegalArgumentException("用户不存在");
}
roleUserService.deleteUserRole(id, null);
if (!CollectionUtils.isEmpty(roleIds)) {
List roleUsers = new ArrayList<>(roleIds.size());
roleIds.forEach(roleId -> roleUsers.add(new SysRoleUser(id, roleId)));
roleUserService.saveBatch(roleUsers);
}
}
@Transactional(rollbackFor = Exception.class)
@Override
public ResultBody updatePassword(Long id, String oldPassword, String newPassword, Boolean isdefault) throws Exception {
SysUser sysUser = baseMapper.selectById(id);
if (StrUtil.isNotBlank(oldPassword)) {
oldPassword = AesUtils.desEncrypt(oldPassword).trim();
if (!passwordEncoder.matches(oldPassword, sysUser.getPassword())) {
return ResultBody.failed("旧密码错误!");
}
}
if (StrUtil.isBlank(newPassword)) {
newPassword = com.kidgrow.common.utils.RandomValueUtils.getRandom(6);
} else {
newPassword = AesUtils.desEncrypt(newPassword).trim();
}
SysUser user = new SysUser();
user.setId(id);
user.setPassword(passwordEncoder.encode(newPassword));
if (isdefault) {
user.setDefaultAuth(true);
} else {
user.setDefaultAuth(false);
}
baseMapper.updateById(user);
if (isdefault) {
return ResultBody.ok().msg("密码重置成功!").data(newPassword);
} else {
return ResultBody.ok().msg("密码修改成功!").data(true);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public ResultBody updateUserTel(Map params) throws Exception {
Long id = MapUtils.getLong(params, "id");
String oldTel = MapUtils.getString(params, "oldTel");
String newTel = AesUtils.desEncrypt(MapUtils.getString(params, "newTel")).trim();
String authCode = AesUtils.desEncrypt(MapUtils.getString(params, "authCode")).trim();
String userPassword =MapUtils.getString(params, "userPassword");
if (id > 0 && StringUtils.isNotBlank(oldTel) && StringUtils.isNotBlank(newTel) && StringUtils.isNotBlank(authCode) && StringUtils.isNotBlank(userPassword)) {
//检查验证码
if (CheckVerificationCode(ConstantSMS.PHONE_SMS, newTel, authCode)) {
//查询手机号是否已经存在
Map selectMap = new HashMap<>();
selectMap.put("mobile", newTel);
List sysUsersList = baseMapper.selectByMap(selectMap);
if (sysUsersList.size() > 0) {
return ResultBody.failed("该手机号已经存在!");
} else {
//验证旧手机号和密码
SysUser sysUser = baseMapper.selectById(id);
userPassword = AesUtils.desEncrypt(userPassword);
if (passwordEncoder.matches(userPassword, sysUser.getPassword()) && sysUser.getMobile().equals((oldTel))) {
//验证通过,修改手机号
SysUser user = new SysUser();
user.setId(id);
user.setMobile(newTel);
user.setUsername(newTel);
//修改doctor表
com.kidgrow.usercenter.model.SysDoctor sysDoctorModel = findDoctorByUserId(user.getId());
com.kidgrow.usercenter.model.SysDoctor newsysDoctorModel = new com.kidgrow.usercenter.model.SysDoctor();
if (sysDoctorModel != null) {
//理论上只有一个,如果有多个 只取第一个
sysDoctorModel.setId(sysDoctorModel.getId());
sysDoctorModel.setDoctorTel(newTel);
sysDoctorMapper.updateById(newsysDoctorModel);
}
if (baseMapper.updateById(user) > 0) {
//将Redis清除
redisUtils.hdel(ConstantSMS.PHONE_SMS, newTel);
return ResultBody.ok().msg("手机号修改成功!");
} else {
return ResultBody.failed("手机号修改失败!");
}
} else {
return ResultBody.failed("用户信息验证失败,请提供正确的手机号和密码!");
}
}
} else {
return ResultBody.failed("无效的验证码");
}
} else {
return ResultBody.failed("必须参数有误!");
}
}
@Override
public PageResult findUsers(Map params) {
Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List list = baseMapper.findList(page, params);
long total = page.getTotal();
if (total > 0&&list.size()>0) {
List userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
if (userIds.size()>0) {
List sysRoles = roleUserService.findRolesByUserIds(userIds);
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !ObjectUtils.notEqual(u.getId(), r.getUserId()))
.collect(Collectors.toList())));
}
}
return PageResult.builder().data(list).code(0).count(total).build();
}
@Override
public List findRolesByUserId(Long userId) {
return roleUserService.findRolesByUserId(userId);
}
@Override
public ResultBody updateEnabled(Map params) {
Long id = MapUtils.getLong(params, "id");
Boolean enabled = MapUtils.getBoolean(params, "enabled");
SysUser appUser = baseMapper.selectById(id);
if (appUser == null) {
return ResultBody.failed("用户不存在");
}
appUser.setEnabled(enabled);
appUser.setUpdateTime(new Date());
int i = baseMapper.updateById(appUser);
log.info("修改用户:{}", appUser);
return i > 0 ? ResultBody.ok().data(appUser).msg("更新成功") : ResultBody.failed("更新失败");
}
@Transactional(rollbackFor = Exception.class)
@Override
public ResultBody saveOrUpdateUser(SysUser sysUser) {
String defaultPassWord = com.kidgrow.common.utils.RandomValueUtils.getRandom(6);
if (sysUser.getId() == null) {
if (StringUtils.isBlank(sysUser.getType())) {
sysUser.setType(UserType.BACKEND.name());
}
sysUser.setPassword(passwordEncoder.encode(defaultPassWord));
sysUser.setEnabled(Boolean.TRUE);
}
String username = sysUser.getUsername();
boolean result = super.saveOrUpdateIdempotency(sysUser, lock
, LOCK_KEY_USERNAME + username, new QueryWrapper().eq("username", username)
, username + "已存在");
// boolean result=true;
//更新角色
if (result && StrUtil.isNotEmpty(sysUser.getRoleId())) {
roleUserService.deleteUserRole(sysUser.getId(), null);
List roleIds = Arrays.asList(sysUser.getRoleId().split(","));
if (!CollectionUtils.isEmpty(roleIds)) {
List roleUsers = new ArrayList<>(roleIds.size());
roleIds.forEach(roleId -> roleUsers.add(new SysRoleUser(sysUser.getId(), Long.parseLong(roleId.toString()))));
roleUserService.saveBatch(roleUsers);
}
}
sysUser.setPassword(defaultPassWord);
return result ? ResultBody.ok().data(sysUser).msg("操作成功") : ResultBody.failed("操作失败");
}
/**
* 删除用户
*
* @param id
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean delUser(Long id) {
//删除角色数据
roleUserService.deleteUserRole(id, null);
//删除组织对应数据
organizationService.deleteByUserId(id);
//删除医生数据
Map params = new HashMap<>();
params.put("user_id", id);
sysDoctorMapper.deleteByMap(params);
//删除用户数据
return baseMapper.deleteById(id) > 0;
}
@Override
public List findAllUsers(Map params) {
List sysUserExcels = new ArrayList<>();
List list = baseMapper.findList(new Page<>(1, -1), params);
for (SysUser sysUser : list) {
SysUserExcel sysUserExcel = new SysUserExcel();
BeanUtils.copyProperties(sysUser, sysUserExcel);
sysUserExcels.add(sysUserExcel);
}
return sysUserExcels;
}
@Override
public ResultBody findAll(Map map) {
List sysUsers = baseMapper.selectByMap(map);
return ResultBody.ok().data(sysUsers).msg("操作成功");
}
/**
* 获取当前用的 组织下的所有人员
*
* @param request
* @return
*/
@Override
public ResultBody getThisUserOrganizationUser(HttpServletRequest request) {
String id = request.getHeader(SecurityConstants.USER_ID_HEADER);
List sysUsers = new ArrayList<>();
if (StringUtils.isNotBlank(id)) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("user_id", id);
List list = iSysUserOrgService.list(queryWrapper);
if (list.size() > 0) {
List collect = list.stream().map(e -> e.getOrgId()).collect(Collectors.toList());
if (collect.size() > 0) {
queryWrapper = new QueryWrapper<>();
queryWrapper.in("org_id", collect);
List sysUserOrgs = iSysUserOrgService.list(queryWrapper);
List userIds = sysUserOrgs.stream().map(e -> e.getUserId()).collect(Collectors.toList());
QueryWrapper sysUserQueryWrapper = new QueryWrapper();
sysUserQueryWrapper.in("id", userIds.stream().distinct().collect(Collectors.toList()));
sysUsers = baseMapper.selectList(sysUserQueryWrapper);
}
}
} else {
return ResultBody.failed("暂无数据");
}
return ResultBody.ok().data(sysUsers);
}
@Override
public ResultBody findCountByMap(Map map) {
map.put("enable", 1);
map.put("isDel", 0);
Integer integer = baseMapper.selectCountByMap(map);
return ResultBody.ok().data(integer);
}
/**
* 验证手机验证码
*
* @param constantSMS
* @param phone
* @param inputCode
* @return
*/
public boolean CheckVerificationCode(String constantSMS, String phone, String inputCode) {
//获取缓存中的验证码对象
Object hget = redisUtils.hget(constantSMS, phone);
if (hget != null) {
//序列化验证码
JSONObject redisJson = JSON.parseObject(JSON.toJSONString(hget));
//拿取验证码
String verificationCodeObject = redisJson.get("verificationCode").toString();
//核对验证码
if (inputCode.equals(verificationCodeObject)) {
Object date = redisJson.get("endTime");
long time = DateUtils.parseDate(date.toString()).getTime();
Date dateNow = new Date();
long timeNow = dateNow.getTime();
return (timeNow <= time);
}
}
return false;
}
/**
* 通过手机号 修改密码
*
* @param map
* @return
*/
@Override
public ResultBody passwordByPhone(Map map) throws Exception {
//手机号,type,验证码,新密码
String phone = MapUtils.getString(map, "phone");
if (phone == null || "".equals(phone.trim())) {
return ResultBody.failed("请输入手机号");
}
String verificationCode = MapUtils.getString(map, "verificationCode");
if (verificationCode == null || "".equals(verificationCode.trim())) {
return ResultBody.failed("请输入验证码");
}
String newPass = MapUtils.getString(map, "newPass");
if (newPass == null || "".equals(newPass.trim())) {
return ResultBody.failed("请输入正确的密码");
}
phone = AesUtils.desEncrypt(phone.trim());
verificationCode = AesUtils.desEncrypt(verificationCode.trim());
newPass = AesUtils.desEncrypt(newPass.trim());
if (CheckVerificationCode(ConstantSMS.PASSWORD_SMS, phone, verificationCode)) {
//查询表
Map selectMap = new HashMap<>();
selectMap.put("mobile", phone);
List sysUsers = baseMapper.selectByMap(selectMap);
if (sysUsers.size() > 0) {
SysUser user = new SysUser();
user.setId(sysUsers.get(0).getId());
user.setPassword(passwordEncoder.encode(newPass));
baseMapper.updateById(user);
//将Redis 清除
redisUtils.hdel(ConstantSMS.PASSWORD_SMS, phone);
return ResultBody.ok();
} else {
return ResultBody.failed("暂无该手机号信息");
}
} else {
return ResultBody.failed("无效的验证码");
}
}
/**
* 通过手机号 注册验证
*
* @param map
* @return
*/
@Override
public ResultBody registerByPhone(Map map) {
//手机号,type,验证码,新密码
String phone = MapUtils.getString(map, "phone");
if (phone == null || "".equals(phone.trim())) {
return ResultBody.failed("请输入手机号");
}
if (phoneIsUsed(phone)) {
return ResultBody.failed("该手机号已经注册");
}
Map mapDto = new HashMap();
mapDto.put("phone", phone);
mapDto.put("type", ConstantSMS.REGISTER_SMS);
return smsChuangLanService.sendVerificationCode(mapDto);
}
/**
* 通过手机号修改 手机号
*
* @param map
* @return
*/
@Override
public ResultBody updatePhone(Map map, SysUser sysUser) {
String password = MapUtils.getString(map, "password");
if (StringUtils.isBlank(password)) {
return ResultBody.failed("请输入密码");
}
String phone = MapUtils.getString(map, "phone");
if (StringUtils.isBlank(phone)) {
return ResultBody.failed("请输入新手机号");
}
if (!sysUser.getMobile().equals(password)) {
return ResultBody.failed("请输入原手机号");
}
String verificationCode = MapUtils.getString(map, "verificationCode");
if (StringUtils.isBlank(verificationCode)) {
return ResultBody.failed("请输入验证码");
}
if (!passwordEncoder.matches(sysUser.getPassword(), password)) {
return ResultBody.failed("密码错误");
}
Object hget = redisUtils.hget(ConstantSMS.PHONE_SMS, map.get("phone").toString());
if (hget != null) {
JSONObject redisJson = JSON.parseObject(JSON.toJSONString(hget));
Object verificationCodeObject = redisJson.get("verificationCode");
if (verificationCode.equals(verificationCodeObject)) {
Object date = redisJson.get("endTime");
long time = DateUtils.parseDate(date.toString()).getTime();
Date dateNow = new Date();
long timeNow = dateNow.getTime();
if (timeNow <= time) {
//查询表
Map selectMap = new HashMap<>();
selectMap.put("mobile", phone);
List sysUsers = baseMapper.selectByMap(selectMap);
if (sysUsers.size() > 0) {
return ResultBody.failed("该手机号已经注册");
} else {
SysUser user = new SysUser();
user.setId(sysUser.getId());
user.setMobile(phone);
baseMapper.updateById(user);
//将Redis 清除
redisUtils.hdel(ConstantSMS.PHONE_SMS, phone);
return ResultBody.ok();
}
} else {
return ResultBody.failed("验证码超时");
}
} else {
return ResultBody.failed("验证码错误");
}
} else {
return ResultBody.failed("该手机号没有验证码");
}
}
@Override
public ResultBody findAppointUsers(Integer type) {
List list = baseMapper.findAppointUsers(type);
return ResultBody.ok().data(list);
}
/**
* 根据userid获取用户其它信息
*
* @param userId
* @return
*/
@Override
public ResultBody findDoctorUserAllData(Long userId) {
if (userId > 0) {
return ResultBody.ok().data(baseMapper.findDoctorUserAllData(userId));
}
return ResultBody.ok().data(null);
}
/**
* H端用户注册 管理员添加用户
*
* @param userRegVo
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public ResultBody doctorUserReg(UserRegVo userRegVo, SysUser sysUserd) throws Exception {
if (sysUserd.getId() == null) {
sysUserd = this.baseMapper.selectById(userRegVo.getUserId());
}
userRegVo.setPassword(AesUtils.desEncrypt(userRegVo.getPassword()).trim());
userRegVo.setUsername(AesUtils.desEncrypt(userRegVo.getUsername()).trim());
//检查手机号是否已经注册 H端登录名和手机号存一样的值
if (phoneIsUsed(userRegVo.getMobile())) {
return ResultBody.failed("该手机号已经注册");
}
//创建人id
Long createUserId = CommonConstant.CREATE_USER_ID;
//创建人名称
String createUserName = CommonConstant.CREATE_USER_NAME;
//销售服务人员
SysUser sysUserSale = baseMapper.selectById(CommonConstant.SALE_USER_ID);
//运营服务人员
SysUser sysUserOpration = baseMapper.selectById(CommonConstant.OPRATION_USER_ID);
//是否注册用户
Boolean isReg = false;
//业务成功
Boolean isSuccess = true;
//业务失败提示信息
String expMsg = "";
//系统内置的注册医院和科室的组织数据
Long organizationHos = 0L;
Long organizationDep = 0L;
//检查判断是注册 还是添加用户,注册用户先走基本数据建设 医院/科室
SysUserOrg sysUserOrgH = new SysUserOrg();
SysUserOrg sysUserOrgD = new SysUserOrg();
SysDictionaries sysDictionaries = new SysDictionaries();
SysDoctor sysDoctor = new SysDoctor();
if (userRegVo.getHospitalId() == null) {
isReg = true;
if (CheckVerificationCode(ConstantSMS.REGISTER_SMS, userRegVo.getMobile(), userRegVo.getVerification())) {
userRegVo.setDoctorState(true);
//写医院组织数据
SysOrganization sysOrganizationH = new SysOrganization();
sysOrganizationH.setOrgLevel(1);
sysOrganizationH.setOrgAttr(1);
sysOrganizationH.setOrgParentId(CommonConstant.ORG_PARENT_ID);
sysOrganizationH.setOrgName(userRegVo.getHospitalName());
sysOrganizationH.setCreateUserId(createUserId);
sysOrganizationH.setCreateUserName(createUserName);
if (organizationService.save(sysOrganizationH)) {
organizationHos=sysOrganizationH.getId();
//写科室组织数据
SysOrganization sysOrganizationD = new SysOrganization();
sysOrganizationD.setOrgLevel(2);
sysOrganizationD.setOrgAttr(2);
sysOrganizationD.setOrgParentId(sysOrganizationH.getId());
sysOrganizationD.setOrgName(userRegVo.getDepartmentName());
sysOrganizationD.setCreateUserId(createUserId);
sysOrganizationD.setCreateUserName(createUserName);
if (organizationService.save(sysOrganizationD)) {
organizationDep=sysOrganizationD.getId();
//写医院组织数据
SysHospital sysHospital = new SysHospital();
sysHospital.setHospitalName(userRegVo.getHospitalName());
sysHospital.setOrgId(sysOrganizationH.getId());
//注册的用户所在医院默认是试用状态
sysHospital.setHospitalState(0);
sysHospital.setCreateUserId(createUserId);
sysHospital.setCreateUserName(createUserName);
if (hospitalService.save(sysHospital)) {
userRegVo.setHospitalId(sysHospital.getId());
//保存科室数据
SysDepartment sysDepartment = new SysDepartment();
sysDepartment.setOrgId(sysOrganizationD.getId());
sysDepartment.setDepartmentName(userRegVo.getDepartmentName());
sysDepartment.setSaleUserId(sysUserSale.getId());
sysDepartment.setAccountsCount(1);
sysDepartment.setSaleUserName(sysUserSale.getNickname());
sysDepartment.setSaleUserTel(sysUserSale.getMobile());
sysDepartment.setServerUserId(sysUserOpration.getId());
sysDepartment.setServerUserTel(sysUserOpration.getMobile());
sysDepartment.setServerUserName(sysUserOpration.getNickname());
sysDepartment.setCreateUserId(createUserId);
sysDepartment.setCreateUserName(createUserName);
if (departmentService.save(sysDepartment)) {
userRegVo.setDepartmentId(sysDepartment.getId());
//自动充入系统指定的试用套餐
if (!saveProductDetail(sysHospital.getId(),
sysDepartment.getId(),
sysHospital.getHospitalName(),
sysDepartment.getDepartmentName())) {
isSuccess = false;
expMsg = "试用套餐充值失败";
}
} else {
isSuccess = false;
expMsg = "科室数据写入失败";
}
} else {
isSuccess = false;
expMsg = "医院数据写入失败";
}
} else {
isSuccess = false;
expMsg = "科室组织数据写入失败";
}
} else {
isSuccess = false;
expMsg = "医院组织数据写入失败";
}
} else {
return ResultBody.failed("无效的验证码");
}
}
//业务执行中途出错
if (isReg && !isSuccess) {
//注册过程失败
return ResultBody.failed(expMsg);
}
if (!isReg && departmetAccountsCount(userRegVo.getDepartmentId()) < 1) {
return ResultBody.failed("当前科室可创建账户数量已满");
}
//添加用户数据 如果没有输入密码,将会创建一个默认密码返回
String defaultPassWord = "";
SysUser sysUser = new SysUser();
sysUser.setUsername(userRegVo.getMobile());
sysUser.setMobile(userRegVo.getMobile());
if (StringUtils.isBlank(userRegVo.getPassword())) {
defaultPassWord = com.kidgrow.common.utils.RandomValueUtils.getRandom(6);
sysUser.setPassword(passwordEncoder.encode(defaultPassWord));
userRegVo.setPassword(defaultPassWord);
} else {
sysUser.setPassword(passwordEncoder.encode(userRegVo.getPassword()));
}
sysUser.setNickname(userRegVo.getNickname());
sysUser.setSex(userRegVo.getSex());
sysUser.setEnabled(true);
if (StringUtils.isNotBlank(userRegVo.getType())) {
sysUser.setType(userRegVo.getType());
} else {
sysUser.setType(UserType.DOCTOR.name());
}
sysUser.setHAdminUser(false);
if(isReg){
sysUser.setDefaultAuth(false);
}else{
sysUser.setDefaultAuth(true);
}
sysUser.setOpenId(userRegVo.getOpenId());
sysUser.setDel(false);
sysUser.setTenantId(CommonConstant.H_TENANT);
boolean u = this.save(sysUser);
SysRoleUser sysRoleUser = new SysRoleUser();
if (u) {
//保存角色用户绑定信息 sys_role_user
Map map = new HashMap<>();
map.put("code", CommonConstant.HOSPITAL_DOCTOR_CODE);
map.put("enabled", 1);
map.put("is_del", 0);
List sysRoles = sysRoleMapper.selectByMap(map);
if (sysRoles.size() > 0) {
//保存角色和用户绑定关系数据
SysRole sysRole = sysRoles.get(0);
sysRoleUser.setRoleId(sysRole.getId());
sysRoleUser.setUserId(sysUser.getId());
int insert = sysUserRoleMapper.insert(sysRoleUser);
if (insert > 0) {
//写入职务数据
if (StringUtils.isNotBlank(userRegVo.getDoctorRank())) {
//检查医生职务是否存在
Map selectMap = new HashMap<>();
selectMap.put("dictionariesNameAll", userRegVo.getDoctorRank().trim());
List dictionariesList = sysDictionariesService.findAll(selectMap);
boolean dicBool = false;
if (dictionariesList.size() > 0) {
for (int i = dictionariesList.size() - 1; i >= 0; i--) {
if (dictionariesList.get(i).getDictionariesName().trim().equals(userRegVo.getDoctorRank().trim())) {
userRegVo.setDoctorRankId(dictionariesList.get(i).getId());
dicBool = true;
break;
}
}
}
else {
//创建字典数据
sysDictionaries.setDictionariesClassId(DictionariesConstants.DOCTOR_RANK);
//将名称汉字转为拼音
String keyStr=Pinyin4jUtil.makeStringByStringSet(Pinyin4jUtil.getPinyin(userRegVo.getDoctorRank(), true));
if (keyStr.length()>50) {
keyStr=keyStr.substring(0,49);
}
sysDictionaries.setDictionariesKey(keyStr);
sysDictionaries.setDictionariesName(userRegVo.getDoctorRank());
sysDictionaries.setCreateUserId(createUserId);
sysDictionaries.setCreateUserName(createUserName);
dicBool = sysDictionariesService.save(sysDictionaries);
if (dicBool) {
userRegVo.setDoctorRankId(sysDictionaries.getId());
}
}
if (dicBool) {
//写用户组织关系表
SysHospital byId = hospitalService.getById(userRegVo.getHospitalId());
if(byId!=null){
organizationHos=byId.getOrgId();
}
List sysUserOrgList = new ArrayList();
sysUserOrgH.setUserId(sysUser.getId());
sysUserOrgH.setOrgId(organizationHos);
sysUserOrgH.setFromLevel(CommonConstant.SYSTEM_ORG_HOS_LEVEL);
sysUserOrgH.setFromId(userRegVo.getHospitalId());
sysUserOrgH.setCreateUserId(isReg ? createUserId : sysUserd.getId());
sysUserOrgH.setCreateUserName(isReg ? createUserName : sysUserd.getUsername());
sysUserOrgList.add(sysUserOrgH);
SysDepartment department = departmentService.getById(userRegVo.getDepartmentId());
if(department!=null){
organizationDep=department.getOrgId();
}
sysUserOrgD.setUserId(sysUser.getId());
sysUserOrgD.setOrgId(organizationDep);
sysUserOrgD.setFromId(userRegVo.getDepartmentId());
sysUserOrgD.setFromLevel(CommonConstant.SYSTEM_ORG_DEP_LEVEL);
sysUserOrgD.setCreateUserId(isReg ? createUserId : sysUserd.getId());
sysUserOrgD.setCreateUserName(isReg ? createUserName : sysUserd.getUsername());
sysUserOrgList.add(sysUserOrgD);
boolean uOrg = iSysUserOrgService.saveBatch(sysUserOrgList);
if (uOrg) {
//写入医生数据
sysDoctor.setUserId(sysUser.getId());
sysDoctor.setHospitalId(userRegVo.getHospitalId());
sysDoctor.setHospitalName(userRegVo.getHospitalName());
sysDoctor.setDepartmentId(userRegVo.getDepartmentId());
sysDoctor.setDepartmentName(userRegVo.getDepartmentName());
sysDoctor.setDoctorRank(userRegVo.getDoctorRank());
sysDoctor.setDoctorRankId(userRegVo.getDoctorRankId());
sysDoctor.setDoctorType(CommonConstant.H_DOCTOR_TYPE);
sysDoctor.setCreateUserId(isReg ? createUserId : sysUserd.getId());
sysDoctor.setCreateUserName(isReg ? createUserName : sysUserd.getUsername());
sysDoctor.setDoctorState(!isReg);
sysDoctor.setDoctorTel(userRegVo.getMobile());
sysDoctor.setDoctorName(userRegVo.getNickname());
sysDoctor.setServerUserId(isReg ? sysUserSale.getId() : sysUserd.getId());
sysDoctor.setServerUserName(isReg ? sysUserSale.getNickname() : sysUserd.getUsername());
sysDoctor.setIsAdminUser(false);
sysDoctor.setDoctorCcie(userRegVo.getDoctorCcie());
sysDoctor.setEnabled(true);
if (sysDoctorMapper.insert(sysDoctor) == 1) {
//非自主注册的 返回信息带密码
if (!isReg) {
sysUser.setPassword(userRegVo.getPassword());
} else {
sysUser.setPassword("");
}
} else {
isSuccess = false;
expMsg = "医生数据写入失败";
}
} else {
isSuccess = false;
expMsg = "用户组织数据写入失败";
}
} else {
isSuccess = false;
expMsg = "职称数据写入失败";
}
} else {
//没有职务数据
isSuccess = false;
expMsg = "没有职称数据";
}
} else {
isSuccess = false;
expMsg = "角色绑定数据写入失败";
}
} else {
isSuccess = false;
expMsg = "对应角色没有数据";
}
} else {
isSuccess = false;
expMsg = "用户数据写入失败";
}
/***返回数据***/
if (!isSuccess) {
return ResultBody.failed(expMsg);
} else {
return ResultBody.ok().data(sysUser);
}
}
/**
* feign客户端调用写入试用套餐
*
* @param hospitalId
* @param departmentId
* @param hospitalName
* @param departmentName
* @return
*/
private boolean saveProductDetail(Long hospitalId, Long departmentId, String hospitalName, String departmentName) {
Map params = new HashMap();
params.put("hospitalId", hospitalId);
params.put("departmentId", departmentId);
params.put("hospitalName", hospitalName);
params.put("departmentName", departmentName);
ResultBody resultBody = productOrderService.saveProductDetail(params);
return (boolean) resultBody.getData();
}
/**
* 获取医院科室下的所有H端有效的医生
*
* @param hospitalId
* @param departmentId
* @return
*/
@Override
public ResultBody hospitalDoctorList(Long hospitalId, Long departmentId, Boolean isIncluddel) {
if (hospitalId > 0 && departmentId > 0) {
List listVoList;
if (isIncluddel) {
listVoList = baseMapper.hospitalDoctorListAndDel(hospitalId, departmentId, CommonConstant.HOSPITAL_DOCTOR_ID, CommonConstant.HOSPITAL_ADMIN_ID);
} else {
listVoList = baseMapper.hospitalDoctorList(hospitalId, departmentId, CommonConstant.HOSPITAL_DOCTOR_ID, CommonConstant.HOSPITAL_ADMIN_ID);
}
listVoList.sort((e1,e2)->
e2.getUserId().compareTo(e1.getUserId())
);
return ResultBody.ok().data(listVoList);
} else {
return ResultBody.failed("医院数据有误");
}
}
/**
* 检查手机号是否已经注册 true存在 false不存在
*
* @param phone
* @return
*/
public boolean phoneIsUsed(String phone) {
Map selectMap = new HashMap<>();
selectMap.put("mobile", phone);
selectMap.put("is_del", 0);
selectMap.put("tenant_id", "hospital");
List sysUsers = baseMapper.selectByMap(selectMap);
return (sysUsers.size() > 0);
}
/**
* 检查科室有效剩余账户数量
*
* @param depatmentId
* @return
*/
public Integer departmetAccountsCount(Long depatmentId) {
SysDepartment sysDepartment = departmentService.getById(depatmentId);
if (sysDepartment == null) {
return 0;
} else {
Long sysHospitalId = HospitalIdByDepartmentId(depatmentId);
if (sysHospitalId > 0) {
List hospitalDoctorListVos = baseMapper.hospitalDoctorList(sysHospitalId, depatmentId, CommonConstant.HOSPITAL_DOCTOR_ID, CommonConstant.HOSPITAL_ADMIN_ID);
if (hospitalDoctorListVos != null) {
int doctorCount = hospitalDoctorListVos.size();
int accountCount = sysDepartment.getAccountsCount().intValue();
int liveCount = accountCount - doctorCount;
return liveCount;
} else {
return 0;
}
} else {
return 0;
}
}
}
/**
* 根据部门的id获取所属医院id
*
* @return
*/
public Long HospitalIdByDepartmentId(Long departmentId) {
Long hospitalId = -1L;
SysDepartment sysDepartment = departmentService.getById(departmentId);
if (sysDepartment != null) {
//先获取科室的组织数据
SysOrganization sysOrganization = sysOrganizationMapper.selectById(sysDepartment.getOrgId());
if (sysOrganization != null) {
//获取上级组织id
sysOrganization = sysOrganizationMapper.selectById(sysOrganization.getOrgParentId());
if (sysOrganization != null) {
//根据组织id获取上级医院id
Map selectMap = new HashMap<>();
selectMap.put("org_id", sysOrganization.getId());
List sysHospitalList = hospitalService.listByMap(selectMap);
if (sysHospitalList != null && sysHospitalList.size() > 0) {
//取第一个
hospitalId = sysHospitalList.get(0).getId();
}
}
}
}
return hospitalId;
}
/**
* 检查用户登录名是否已经注册 true存在 false不存在
*
* @param userName
* @return
*/
private boolean userNameIsUsed(String userName) {
Map selectMap = new HashMap<>();
selectMap.put("username", userName);
List sysUsers = baseMapper.selectByMap(selectMap);
return (sysUsers.size() > 0);
}
public com.kidgrow.usercenter.model.SysDoctor findDoctorByUserId(Long userId) {
Map doctorMap = new HashMap<>();
doctorMap.put("user_id", userId);
doctorMap.put("enabled", 1);
doctorMap.put("is_del", 0);
List sysDoctorList = sysDoctorMapper.selectByMap(doctorMap);
if (sysDoctorList.size() > 0) {
return sysDoctorList.get(0);
}
return new com.kidgrow.usercenter.model.SysDoctor();
}
/**
* 检查手机号是注册用户还是正式用户
*
* @param userTel
* @return
*/
public ResultBody isRegUser(String userTel) {
if (StringUtils.isNotBlank(userTel)) {
List users = baseMapper.selectList(
new QueryWrapper().eq("username", userTel)
);
if (users != null && users.size() == 1) {
SysUser sysUser = users.get(0);
if (sysUser.getCreateUserId() == CommonConstant.CREATE_USER_ID && sysUser.getCreateUserName().equals(CommonConstant.CREATE_USER_NAME)) {
return ResultBody.ok().data(true);
}
return ResultBody.ok().data(false);
} else {
return ResultBody.failed("用户数据有误!");
}
} else {
return ResultBody.failed("必要参数有误!");
}
}
@Override
public ResultBody jiaMipython(String password) {
String encode = passwordEncoder.encode(password);
return ResultBody.ok().data(encode);
}
@Override
public boolean deleteNoContact(Long id) {
//删除医生数据
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", id);
List sysDoctors = sysDoctorMapper.selectList(queryWrapper);
if (!sysDoctors.isEmpty()) {
sysDoctors.forEach(e -> {
e.setIsDel(true);
sysDoctorMapper.updateById(e);
});
}
//删除用户数据
return baseMapper.deleteById(id) > 0;
}
}