GarUserServiceImpl.java 18.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
package com.trash.garbage.service.impl;

import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import com.trash.disposalSite.domain.DisposalSite;
import com.trash.disposalSite.service.IDisposalSiteService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.trash.common.core.domain.entity.SysRole;
import com.trash.common.core.domain.entity.SysUser;
import com.trash.common.core.domain.model.LoginUser;
import com.trash.common.core.redis.RedisCache;
import com.trash.common.utils.SecurityUtils;
import com.trash.common.utils.StringUtils;
import com.trash.driver.domain.vo.DriverVo;
import com.trash.driver.service.IDriverService;
import com.trash.enterprise.domain.TransportationEnterprise;
import com.trash.enterprise.service.ITransportationEnterpriseService;
import com.trash.framework.web.service.TokenService;
import com.trash.garbage.config.WxConfig;
import com.trash.garbage.custom.BizException;
import com.trash.garbage.global.GlobalRedisProperties;
import com.trash.garbage.global.GlobalStatus;
import com.trash.garbage.global.ResultCode;
import com.trash.garbage.mapper.GarUserMapper;
import com.trash.garbage.pojo.domain.GarAddress;
import com.trash.garbage.pojo.domain.GarUser;
import com.trash.garbage.pojo.dto.AddressDto;
import com.trash.garbage.pojo.dto.LoginDto;
import com.trash.garbage.pojo.vo.LoginVo;
import com.trash.garbage.service.GarAddressService;
import com.trash.garbage.service.GarUserService;
import com.trash.garbage.utils.JwtUtils;
import com.trash.garbage.utils.ValidateCodeUtil;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;

/**
 * @author 20412
 * @description 针对表【gar_user(建筑垃圾-用户表)】的数据库操作Service实现
 * @createDate 2023-11-20 16:03:15
 */
@Service
@Transactional
public class GarUserServiceImpl extends ServiceImpl<GarUserMapper, GarUser>
        implements GarUserService {
    @Resource
    private WxConfig wxConfig;

    @Autowired
    private GarAddressService garAddressService;

    @Autowired
    private IDisposalSiteService disposalSiteService;

    @Autowired
    private IDriverService driverService;

    @Autowired
    private ITransportationEnterpriseService enterpriseService;


    @Resource
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;


    @Override
    public LoginVo login(LoginDto loginDto) {
        LoginVo vo = new LoginVo();

        if (Objects.isNull(loginDto)) {
            throw new UsernameNotFoundException("当前用户不存在!");
        }
        // 微信登录
        if (loginDto.getLoginType().equals(GlobalStatus.GarUserStatusEnum.WX_LOGIN.getStatus())) {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getSecret() + "&js_code=" + loginDto.getWxCode() + "&grant_type=authorization_code";
            String body = HttpUtil.createGet(url).header("cache-control", "no-cache").execute().body();
            JSONObject open = JSONObject.parseObject(body);
            String sessionKey = open.getString("session_key");
            try {
                loginDto.setTel(decrypt(loginDto.getEncryptedData(), sessionKey, loginDto.getIv()));
            } catch (Exception e) {
                throw new BizException(ResultCode.CODE_500, "解密失败");
            }
        }
        // 验证码验证
        String code = redisCache.getCacheObject(GlobalRedisProperties.REDIS_USER_CODE.getValue() + loginDto.getTel());
        if (loginDto.getCode() == null || !loginDto.getCode().equals(code)) {
            throw new BizException(ResultCode.CODE_400, "验证码错误!!");
        }
        // 查询用户
        QueryWrapper<GarUser> qw = new QueryWrapper<>();
        qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
        GarUser nUser = this.getOne(qw);
        if (Objects.isNull(nUser)) {
            // 不存在就创建用户
            nUser = new GarUser();
            nUser.setGarUserTel(loginDto.getTel());
            nUser.setGarUserDelFlag(GlobalStatus.DEL_FLAG_NO);
            nUser.setGarUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
            this.save(nUser);
        }
        LoginUser loginUser = new LoginUser();
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        loginUser.setAuthorities(authorities);
        Set<String> set = new HashSet<String>();
        SysUser user = new SysUser();
        user.setUserId(nUser.getGarUserId());
        user.setUserName(nUser.getGarUserName());
        user.setPhonenumber(loginDto.getTel());
        loginUser.setUser(user);
        set.add("*:*:*");
        SysRole role = new SysRole();
        role.setRoleKey("admin");
        ArrayList<SysRole> roles = new ArrayList<SysRole>();
        roles.add(role);
        user.setRoles(roles);
        loginUser.setPermissions(set);
        String token = JwtUtils.createToken(nUser.getGarUserId(), nUser.getGarUserTel());
        loginUser.setToken(token);
        tokenService.refreshToken(loginUser);
        vo.setToken(token);
        DriverVo driver = new DriverVo();
        driver.setPhoneNo(loginDto.getTel());
        List<DriverVo> driverList = driverService.selectDriverList(driver);
        LoginVo.RuleVo ruleVo = new LoginVo.RuleVo();
        ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
        vo.setRuleVos(new ArrayList<>(Arrays.asList(ruleVo)));
        // 运输驾驶员
        if (CollectionUtil.isNotEmpty(driverList)) {
            DriverVo driverVo = driverList.get(0);
            TransportationEnterprise enterprise = enterpriseService.selectTransportationEnterpriseById(driverVo.getCompanyId());
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(enterprise.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }

        // 企业负责人 TODO
        TransportationEnterprise transportationEnterprise = new TransportationEnterprise();
        transportationEnterprise.setServicePhone(loginDto.getTel());
        List<TransportationEnterprise> enterpriseList = enterpriseService.selectTransportationEnterpriseList(transportationEnterprise);
        if (CollectionUtil.isNotEmpty(enterpriseList)) {
            TransportationEnterprise enterprise = enterpriseList.get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(enterprise.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }

        // 处理场所 TODO
        // 查询条件
        DisposalSite site = new DisposalSite();
        site.setConstructionUnitPersonPhone(loginDto.getTel());
        List<DisposalSite> disposalSites = disposalSiteService.selectDisposalSiteList(site);
        if (CollectionUtil.isNotEmpty(disposalSites)) {
            DisposalSite disposalSite = disposalSites.get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(disposalSite.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }
        return vo;
    }

    @Override
    public String sendVerify(String tel) throws ClientException {
        //随机生成6位数字验证码
        String validateCode = ValidateCodeUtil.generatorCode(4);
        //给用户发送验证码
//        SMSUtils.sendMessage("", tel, validateCode.toString(), "");
        // 保存redis
        System.out.println("code:" + validateCode);
        redisCache.setCacheObject(GlobalRedisProperties.REDIS_USER_CODE.getValue() + tel, validateCode, 60, TimeUnit.SECONDS);
        return validateCode;
    }

    @Override
    public List<GarAddress> queryAddress(String type) {
        LoginUser user = SecurityUtils.getLoginUser();
        String garUserId = user.getUser().getUserId();
        LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
        qw.eq(GarAddress::getGarUserId, garUserId);
        if (GlobalStatus.QUERY_ADDRESS_TYPE_CURRENT.equals(type)) {
            qw.eq(GarAddress::getGarUserDefault, GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue());
            GarAddress one = garAddressService.getOne(qw);
            return Arrays.asList(one);
        }
        return garAddressService.list(qw);
    }

    @Override
    public String saveAddress(AddressDto dto) {
        LoginUser userCustom = SecurityUtils.getLoginUser();
        // 限制地址数
        LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
        qw.eq(GarAddress::getGarUserId, userCustom.getUser().getUserId());
        List<GarAddress> list = garAddressService.list(qw);
        if (list.size() > 19) {
            throw new BizException(ResultCode.CODE_201, "新增地址数已达上线,请删除地址后新增地址或编辑已有地址!");
        }
        GarAddress address = new GarAddress();
        address.setGarUserId(userCustom.getUser().getUserId());
        address.setGarUserAddress(dto.getAddressArea());
        address.setGarUserDefault(dto.getDefaultFlag() ? GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue() : GlobalStatus.GarAddressStatus.NORMAL_ADDRESS.getValue());
        address.setGarUserContactName(dto.getContactPerson());
        address.setGarUserContactTel(dto.getContactIphoneNumber());
        address.setGarRemark(dto.getAddressDetail());
        address.setGarLongitude(dto.getGarLongitude());
        address.setGarLatitude(dto.getGarLatitude());
        address.setGarCoordinate(dto.getGarCoordinate());
        handleCurrentAddress(address);
        garAddressService.save(address);
        return "新增地址成功!";
    }

    @Override
    public String updateAddress(AddressDto dto) {
        GarAddress address = new GarAddress();
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        address.setGarAddressId(dto.getGarAddressId());
        address.setGarUserId(userId);
        address.setGarUserAddress(dto.getAddressArea());
        address.setGarRemark(dto.getAddressDetail());
        address.setGarUserDefault(dto.getDefaultFlag() ? GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue() : GlobalStatus.GarAddressStatus.NORMAL_ADDRESS.getValue());
        handleCurrentAddress(address);
        address.setGarUserContactName(dto.getContactPerson());
        address.setGarUserContactTel(dto.getContactIphoneNumber());
        LambdaUpdateWrapper<GarAddress> up = new LambdaUpdateWrapper<>();
        up.eq(GarAddress::getGarUserId, address.getGarUserId())
                .eq(GarAddress::getGarAddressId, address.getGarAddressId());
        garAddressService.update(address, up);
        return "地址修改成功!";
    }

    private void handleCurrentAddress(GarAddress address) {
        if (address.getGarUserDefault().equals(GlobalStatus.GarAddressStatus.CURRENT_ADDRESS.getValue())) {
            LambdaUpdateWrapper<GarAddress> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(GarAddress::getGarUserId, address.getGarUserId())
                    .set(GarAddress::getGarUserDefault, GlobalStatus.GarAddressStatus.NORMAL_ADDRESS.getValue());
            garAddressService.update(wrapper);
        }
    }

    @Override
    public String deleteAddress(String addressId) {
        String garUserId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<GarAddress> qw = new LambdaQueryWrapper<>();
        qw.eq(GarAddress::getGarUserId, garUserId)
                .eq(GarAddress::getGarAddressId, addressId);
        garAddressService.remove(qw);
        return "删除成功!";
    }

    @Override
    public void updateUserInfo(GarUser user) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaUpdateWrapper<GarUser> uw = new LambdaUpdateWrapper<>();
        uw.eq(GarUser::getGarUserId, userId)
                .set(GarUser::getGarUserType, user.getGarUserType())
                .set(GarUser::getGarUserName, user.getGarUserName())
                .set(GarUser::getGarUserCarNum, user.getGarUserCarNum());
        update(uw);
    }

    @Override
    public String logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        tokenService.delLoginUser(token);
        return "退出登录";
    }

    @Override
    public PageInfo queryListByUserPages(GarUser garUser) {
        LambdaQueryWrapper<GarUser> qw = createQueryWrapperByUser(garUser);
        List<GarUser> userList = list(qw);
        PageInfo<GarUser> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public List<GarUser> queryListByUser(GarUser garUser) {
        LambdaQueryWrapper<GarUser> qw = createQueryWrapperByUser(garUser);
        return list(qw);
    }

    @Override
    public LoginVo queryRole() {
        LoginVo vo = new LoginVo();
        String tel = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        DriverVo driver = new DriverVo();
        driver.setPhoneNo(tel);
        List<DriverVo> driverList = driverService.selectDriverList(driver);
        LoginVo.RuleVo ruleVo = new LoginVo.RuleVo();
        ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
        vo.setRuleVos(new ArrayList<>(Arrays.asList(ruleVo)));
        // 运输驾驶员
        if (CollectionUtil.isNotEmpty(driverList)) {
            DriverVo driverVo = driverList.get(0);
            TransportationEnterprise enterprise = enterpriseService.selectTransportationEnterpriseById(driverVo.getCompanyId());
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(enterprise.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }

        // 企业负责人 TODO
        TransportationEnterprise transportationEnterprise = new TransportationEnterprise();
        transportationEnterprise.setServicePhone(tel);
        List<TransportationEnterprise> enterpriseList = enterpriseService.selectTransportationEnterpriseList(transportationEnterprise);
        if (CollectionUtil.isNotEmpty(enterpriseList)) {
            TransportationEnterprise enterprise = enterpriseList.get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(enterprise.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }

        // 处理场所 TODO
        // 查询条件
        DisposalSite site = new DisposalSite();
        site.setConstructionUnitPersonPhone(tel);
        List<DisposalSite> disposalSites = disposalSiteService.selectDisposalSiteList(site);
        if (CollectionUtil.isNotEmpty(disposalSites)) {
            DisposalSite disposalSite = disposalSites.get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(disposalSite.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }
        return vo;
    }

    private LambdaQueryWrapper<GarUser> createQueryWrapperByUser(GarUser garUser) {
        return new LambdaQueryWrapper<GarUser>()
                .eq(StringUtils.isNotEmpty(garUser.getGarUserId()), GarUser::getGarUserId, garUser.getGarUserId())
                .eq(StringUtils.isNotEmpty(garUser.getGarUserType()), GarUser::getGarUserType, garUser.getGarUserType())
                .eq(StringUtils.isNotEmpty(garUser.getGarUserName()), GarUser::getGarUserName, garUser.getGarUserName())
                .eq(StringUtils.isNotEmpty(garUser.getGarUserTel()), GarUser::getGarUserTel, garUser.getGarUserTel())
                .eq(StringUtils.isNotEmpty(garUser.getGarRemark()), GarUser::getGarRemark, garUser.getGarRemark());

    }


    /**
     * 微信小程序解密
     *
     * @param encrypted
     * @param session_key
     * @param iv
     * @return
     * @throws Exception
     */
    private String decrypt(String encrypted, String session_key, String iv) throws Exception {
        byte[] encrypData = Base64.decodeBase64(encrypted);
        byte[] ivData = Base64.decodeBase64(iv);
        byte[] sessionKey = Base64.decodeBase64(session_key);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        // 解析解密后的字符串
        return new String(cipher.doFinal(encrypData), "UTF-8");
    }

    public WxConfig getWxConfig() {
        return wxConfig;
    }

    public void setWxConfig(WxConfig wxConfig) {
        this.wxConfig = wxConfig;
    }

    public GarAddressService getGarAddressService() {
        return garAddressService;
    }

    public void setGarAddressService(GarAddressService garAddressService) {
        this.garAddressService = garAddressService;
    }

    public RedisCache getRedisCache() {
        return redisCache;
    }

    public void setRedisCache(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    public TokenService getTokenService() {
        return tokenService;
    }

    public void setTokenService(TokenService tokenService) {
        this.tokenService = tokenService;
    }


}