GarUserServiceImpl.java 27.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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
package com.trash.garbage.service.impl;

import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
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.dropPointInfo.domain.DropPointInfo;
import com.trash.dropPointInfo.service.IDropPointInfoService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.disposalSite.domain.DisposalSite;
import com.trash.disposalSite.service.IDisposalSiteService;
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.domain.GarUserReq;
import com.trash.garbage.pojo.domain.GarUserReqDetail;
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.SMSUtils;
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;

    @Resource
    private SMSUtils smsUtils;

    @Autowired
    private GarAddressService garAddressService;

    @Autowired
    private IDisposalSiteService disposalSiteService;

    @Autowired
    private IDriverService driverService;

    @Autowired
    private ITransportationEnterpriseService enterpriseService;

    @Autowired
    private IDropPointInfoService dropPointInfoService;

    @Resource
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;


    @Override
    public LoginVo login(LoginDto loginDto) {
        LoginVo vo = new LoginVo();
                
        if(loginDto.getSignin() == 1){
        	 QueryWrapper<GarUser> qw = new QueryWrapper<>();
             GarUser nUser = null;
	         qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
	         nUser = this.getOne(qw);
        	if (nUser != null) {
                throw new UsernameNotFoundException("当前用户已存在!");
            }
        }
        
        vo.setLoginPhone(loginDto.getTel());
        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, "解密失败");
            }
        }

        GarUser nUser = null;
        if (loginDto.getSignin() != 1 && StringUtils.isNotEmpty(loginDto.getNickname())) {
            QueryWrapper<GarUser> qw = new QueryWrapper<>();
            qw.lambda().eq(GarUser::getGarUserName, loginDto.getNickname());
            nUser = this.getOne(qw);
            if (Objects.isNull(nUser)) {
                throw new UsernameNotFoundException("当前用户不存在!");
            }
            if (!new BCryptPasswordEncoder().matches(loginDto.getPassword(), nUser.getPassword())) {
                throw new UsernameNotFoundException("密码错误!");
            }
            loginDto.setTel(nUser.getGarUserTel());
        } else {
            QueryWrapper<GarUser> qw = new QueryWrapper<>();
            qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
            if(loginDto.getCode() == null && loginDto.getPassword() != null){
                qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
                if(loginDto.getSignin() != 1){
                    nUser = this.getOne(qw);
                    if (Objects.isNull(nUser)) {
                        throw new UsernameNotFoundException("当前用户不存在!");
                    }
                    if(!new BCryptPasswordEncoder().matches(loginDto.getPassword(),nUser.getPassword())){
                        throw new UsernameNotFoundException("密码错误!");
                    }
                }
            }else{
                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, "验证码错误!!");
                }
                nUser = this.getOne(qw);
            }
        }

        if (Objects.isNull(nUser)) {
            // 不存在就创建用户
            nUser = new GarUser();
            nUser.setGarUserTel(loginDto.getTel());
            nUser.setGarUserDelFlag(GlobalStatus.DEL_FLAG_NO);
            
            if(loginDto.getSignin() == 1){
            	nUser.setGarUserName(loginDto.getNickname());
            	nUser.setPassword(new BCryptPasswordEncoder().encode(loginDto.getPassword()));
            }
            
            nUser.setGarUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
        }
        

        
        //是否是投放点用户
        List<DropPointInfo> list = dropPointInfoService.selectDropPointInfoListByPhone(loginDto.getTel());
        vo.setTestUser(CollectionUtil.isNotEmpty(list));

        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);


        GarUserReq userReq = reqGarUser(loginDto.getTel());

        LoginVo.RuleVo ruleVo = new LoginVo.RuleVo();
        ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
        vo.setRuleVos(new ArrayList<>(Arrays.asList(ruleVo)));
        // 运输驾驶员
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getDrivers())) {
            GarUserReqDetail detail = userReq.getDrivers().get(0);
//            TransportationEnterprise enterprise = enterpriseService.selectTransportationEnterpriseById(driverVo.getCompanyId());
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getCompanyName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription());
            nUser.setGarUserType(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription());
            nUser.setGarUserName(detail.getName());
            vo.getRuleVos().add(ruleVo);
            vo.setName(detail.getName());
        }

        // 企业负责人 TODO
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getCompanies())) {
            GarUserReqDetail detail = userReq.getCompanies().get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getCompanyName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription());
            nUser.setGarUserType(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription());
            nUser.setGarUserName(detail.getCompanyName());
            vo.getRuleVos().add(ruleVo);
        }

        // 处理场所 TODO
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getEarthsites())) {
            GarUserReqDetail detail = userReq.getEarthsites().get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription());
            nUser.setGarUserType(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription());
            nUser.setGarUserName(detail.getName());
            vo.getRuleVos().add(ruleVo);

        }
        for (LoginVo.RuleVo r : vo.getRuleVos()){
            //排除驾驶员、企业负责人、处理场所
            if(r.getUserType().equals(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription()) || r.getUserType().equals(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription()) || r.getUserType().equals(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription())){
                vo.setTestUser(true);
            }
        }
        
        
        this.saveOrUpdate(nUser);
        return vo;
    }
    @Override
    public String updatePassword(LoginDto loginDto) {
        QueryWrapper<GarUser> qw = new QueryWrapper<>();
        qw.lambda().eq(GarUser::getGarUserTel, loginDto.getTel());
        GarUser user = this.getOne(qw);

        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("当前用户不存在!");
        }

        if (!new BCryptPasswordEncoder().matches(loginDto.getOldPassword(), user.getPassword())) {
            throw new BizException(ResultCode.CODE_400, "原密码错误!");
        }

        LambdaUpdateWrapper<GarUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GarUser::getGarUserId, user.getGarUserId())
                .set(GarUser::getPassword, new BCryptPasswordEncoder().encode(loginDto.getNewPassword()));

        this.update(updateWrapper);

        return "密码修改成功!";
    }


    @Override
    public String sendVerify(String tel) throws ClientException {
        //随机生成6位数字验证码
        String validateCode = ValidateCodeUtil.generatorCode(4);
        //给用户发送验证码
        smsUtils.sendMessage(tel, validateCode.toString());
        // 保存redis
        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();
        GarUserReq userReq = reqGarUser(tel);

        LoginVo.RuleVo ruleVo = new LoginVo.RuleVo();
        ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.NORMAL_USER.getDescription());
        vo.setRuleVos(new ArrayList<>(Arrays.asList(ruleVo)));
        // 运输驾驶员
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getDrivers())) {
            GarUserReqDetail detail = userReq.getDrivers().get(0);
//            TransportationEnterprise enterprise = enterpriseService.selectTransportationEnterpriseById(driverVo.getCompanyId());
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getCompanyName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DRIVER_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
            vo.setName(detail.getName());
        }

        // 企业负责人 TODO
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getCompanies())) {
            GarUserReqDetail detail = userReq.getCompanies().get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getCompanyName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.RESPONSIBLE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);
        }

        // 处理场所 TODO
        if (Objects.nonNull(userReq) && CollectionUtil.isNotEmpty(userReq.getEarthsites())) {
            GarUserReqDetail detail = userReq.getEarthsites().get(0);
            ruleVo = new LoginVo.RuleVo();
            ruleVo.setTransportCompanyName(detail.getName());
            ruleVo.setUserType(GlobalStatus.GarUserStatusEnum.DISPOSAL_SITE_USER.getDescription());
            vo.getRuleVos().add(ruleVo);

        }
//        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;
    }

    @Override
    public GarUser queryGarUserByTel(String tel) {
        LambdaQueryWrapper<GarUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GarUser::getGarUserTel, tel);
        List<GarUser> garUsers = list(wrapper);
        return CollectionUtils.isEmpty(garUsers) ? null : garUsers.get(0);
    }

    @Override
    public String reqGarUserOfStr(String phone) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneNo", phone);
        return com.trash.garbage.utils.HttpUtil.doGet("/api/gpsservice/cs/authority/getInfoByPhoneNo", paramMap);
    }

    @Override
    public GarUserReq reqGarUser(String phone) {
        String json = reqGarUserOfStr(phone);
        if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
            return null;
        }

        JSONObject jo = JSON.parseObject(json);
        if (!org.apache.commons.lang3.StringUtils.equals(jo.getString("code"), "200")) {
            return null;
        }

        if (Objects.nonNull(jo.get("result")) && jo.get("result") instanceof JSONObject) {
            JSONObject result = (JSONObject) jo.get("result");
            GarUserReq userReq = new GarUserReq();
            userReq.setCompanies(combationGarUserReqDetail(result, "companies"));
            userReq.setDrivers(combationGarUserReqDetail(result, "drivers"));
            userReq.setEarthsites(combationGarUserReqDetail(result, "earthSites"));

            return userReq;
        }

        return null;
    }

    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;
    }

    private List<GarUserReqDetail> combationGarUserReqDetail(JSONObject result, String key) {
        if (Objects.isNull(result)) {
            return Collections.emptyList();
        }
        if (Objects.nonNull(result.get(key)) && result.get(key) instanceof JSONArray) {
            JSONArray array = (JSONArray) result.get(key);
            List<GarUserReqDetail> details = new ArrayList<>();
            for (Object object : array) {
                if (Objects.nonNull(object)) {
                    JSONObject jo = (JSONObject) object;

                    GarUserReqDetail detail = new GarUserReqDetail();
                    detail.setId(jo.getString("id"));
                    detail.setName(jo.getString("name"));
                    detail.setPhoneNo(jo.getString("phoneNo"));
                    detail.setCompanyName(jo.getString("companyName"));
                    detail.setAbbreviation(jo.getString("abbreviation"));
                    detail.setLegalRepresentative(jo.getString("legalRepresentative"));
                    detail.setLegalRepresentativePhone(jo.getString("legalRepresentativePhone"));
                    detail.setSafetyPeopleName(jo.getString("safetyPeopleName"));
                    detail.setSafetyManagerName(jo.getString("safetyManagerName"));
                    detail.setSafetyManagerPhone(jo.getString("safetyManagerPhone"));
                    detail.setServicePhone(jo.getString("servicePhone"));

                    details.add(detail);
                }
            }
            return details;
        }
        return Collections.emptyList();
    }


}