package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.constant.RedisConstant;
import com.om.entity.dto.*;
import com.om.entity.po.*;
import com.om.entity.po.VciInfo;
import com.om.entity.vo.*;
import com.om.exception.BadReqException;
import com.om.exception.BizException;
import com.om.exception.CustomerAuthenticationException;
import com.om.mapper.DeviceMapper;
import com.om.mapper.UserMapper;
import com.om.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 应用用户信息表 服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-01-29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    IUserVciService userVciService;

    @Resource
    UserMapper userMapper;

    @Resource
    IVciInfoService vciInfoService;

    @Resource
    HttpServletRequest request;

    @Resource
    private IClientService clientService;

    @Resource
    private IDistributorService distributorService;

    @Resource
    private IDeviceService deviceService;


    @Override
    @Transactional
    public Result login(UserLoginDTO dto) {
        //从dto中获取数据
        String username = dto.getUsername();
        String password = dto.getPassword();
        String clientNum = dto.getClientNum();
        String deviceSn = dto.getDeviceSn();
        Integer type = dto.getType();
        String appVersion = dto.getAppVersion();
        String deviceToken = dto.getDeviceToken();

        //判断数据是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(clientNum) ||
                StringUtils.isBlank(deviceSn) || type == null) {
            return Result.fail("未获取到数据").result(ResultCode.NO_DATA);
        }
        //根据用户名查询用户
        User user = this.lambdaQuery()
                .eq(User::getUsername, username)
                .one();

        //判断用户是否存在
        if (BeanUtil.isEmpty(user)) {
            return Result.fail("用户不存在").result(ResultCode.USER_NO_EXIST);
        }


        //密码加密
        try {
            password = AesUtil.Encrypt(password);
        } catch (Exception e) {
            throw new BizException("密码加密出错", ResultCode.PASSWORD_ENCRYPT_ERROR);
        }
        //判断密码是否正确
        if (!StringUtils.equals(password, user.getPassword())) {
            return Result.fail("密码错误").result(ResultCode.PASSWORD_ERROR);
        }

        Client client = clientService.lambdaQuery()
                .eq(Client::getNumber, clientNum)
                .one();
        if (BeanUtil.isEmpty(client)) {
            throw new BadReqException("该客户端不存在");
        }
        client.setDeviceToken(deviceToken);
        clientService.updateById(client);

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("u_id", user.getId());
        claims.put("deviceSn", deviceSn);
        claims.put("appVersion", appVersion);
        claims.put("clientNum", clientNum);

        String guid = AesUtil.generateGuid(claims);
        //封装vo返回
        UserLoginVO userLoginVO = new UserLoginVO();
        // 查询 该用户所属的 维修厂
        Integer distributorId = user.getDistributorId();//用户所属的维修厂id
        Distributor distributor = distributorService.getById(distributorId);
        BeanUtil.copyProperties(distributor, userLoginVO);

        // 查询用户 所绑定的vci设备
        List<UserVci> userVciList = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, user.getId())
                .list();

        if (!BeanUtil.isEmpty(userVciList)) {
            List<VciInfoVO> vciInfoVOList = new ArrayList<>();
            int defaultCount = 0;
            for (UserVci userVci : userVciList) {
                VciInfoVO vciInfoVO = new VciInfoVO();
                Integer vciInfoId = userVci.getVciInfoId();
                VciInfo vciInfo = vciInfoService.getById(vciInfoId);
                if (BeanUtil.isEmpty(vciInfo)) {
                    throw new BadReqException("该VCI设备不存在");
                }
                if (userVci.getIsDefault() == 1) {
                    userLoginVO.setVciSn(vciInfo.getVciNum());
                    defaultCount++;
                }
                vciInfoVO.setVciNum(vciInfo.getVciNum());
                vciInfoVO.setState(String.valueOf(vciInfo.getState()));
                vciInfoVO.setPairingPwd(vciInfo.getPairingPwd());
                vciInfoVO.setBluetoothAddress(vciInfo.getBluetoothAddress());
                vciInfoVO.setIsDefault(String.valueOf(userVci.getIsDefault()));

                vciInfoVOList.add(vciInfoVO);
            }
            userLoginVO.setVciInfoList(vciInfoVOList);
        }


        //设置userLoginVO
        userLoginVO.setUsername(username);
        userLoginVO.setPassword(password);
        userLoginVO.setGuid(guid);
        if (user.getState() == 0) {
            return Result.fail("用户被禁用").result(ResultCode.USER_DISABLED);
        }
        if (type == 1) {
            user.setDeviceSn(deviceSn);
            userMapper.updateById(user);

            Device one = deviceService.lambdaQuery()
                    .eq(Device::getDeviceSn, deviceSn)
                    .eq(Device::getUsername, username)
                    .one();
            if (BeanUtil.isEmpty(one)) {
                Device device = new Device();
                device.setDeviceSn(deviceSn);
                device.setUsername(username);
                device.setCreateTime(LocalDateTime.now());
                device.setClientNum(clientNum);
                deviceService.save(device);
            }


        }
        if (StringUtils.isBlank(user.getDeviceSn())) {
            return Result.ok(userLoginVO).message("账号尚未激活").result(ResultCode.USER_NO_ACTIVATE);
        }
        //查询平板设备
        Device device = deviceService.lambdaQuery()
                .eq(Device::getDeviceSn, dto.getDeviceSn())
                .eq(Device::getUsername, username)
                .one();

        //  绑定 客户端编号 和 设备 序列号  ( 判断type是登录（0）还是激活（1） )
        if (BeanUtil.isEmpty(device)) {
            return Result.ok(userLoginVO).message("账号尚未激活").result(ResultCode.USER_NO_ACTIVATE);
        }

        return Result.ok(userLoginVO);
    }

    @Override
    @Transactional
    public Result add(UserAddVO user) {
        User addUser = new User();
        BeanUtil.copyProperties(user, addUser);

        String username = user.getUsername();
        User one = this.lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (BeanUtil.isNotEmpty(one)) {
            throw new BadReqException("该用户已存在");
        }

        if (addUser.getUsername() == null || addUser.getPassword() == null) {
            return Result.error();
        }
        String password = addUser.getPassword();
        //密码加密
        try {
            password = AesUtil.Encrypt(password);
        } catch (Exception e) {
            throw new BizException("密码加密出错", ResultCode.PASSWORD_ENCRYPT_ERROR);
        }


        addUser.setPassword(password);
        Integer distributorId = user.getDistributorId();
        //根据id查询维修厂
        if (user.getDistributorId() != null) {
            Distributor distributor = distributorService.getById(distributorId);
            if (BeanUtil.isEmpty(distributor)) {
                throw new BadReqException("该维修厂不存在");
            }
            addUser.setDistributorName(distributor.getCompany());
        }


        String deviceSn = user.getDeviceSn();

        if (StringUtils.isNotBlank(deviceSn)) {
            Device device = deviceService.lambdaQuery()
                    .eq(Device::getDeviceSn, deviceSn)
                    .one();
            if (!BeanUtil.isEmpty(device)) {
                device.setUsername(user.getUsername());
                deviceService.updateById(device);
            }

        }
        this.save(addUser);
        List<String> vciSns = user.getVciSn();
        if (!vciSns.isEmpty()) {
            List<UserVci> userVciList = new ArrayList<>();
            int i = 1;
            for (String vciSn : vciSns) {
                UserVci userVci = new UserVci();
                //根据vciSn查询
                VciInfo vciInfo = vciInfoService.lambdaQuery()
                        .eq(VciInfo::getVciNum, vciSn)
                        .one();
                if (vciInfo == null) {
                    throw new BadReqException("该VCI设备不存在");
                }
                userVci.setVciInfoId(vciInfo.getId());
                userVci.setUserId(addUser.getId());
                if (i==1){
                    userVci.setIsDefault(1);
                }else {
                    userVci.setIsDefault(0);
                }
                userVciList.add(userVci);
                i++;
            }
            userVciService.saveBatch(userVciList);
        }
        return Result.ok();
    }

    @Override
    @Transactional
    public Result delete(Integer id) {
        if (id == null) {
            return Result.error().message("id不存在");
        }
        User user = this.getById(id);
        if (BeanUtil.isEmpty(user)) {
            throw new BadReqException("该客户端账号不存在");
        }

        //查询 user_vci 表
        List<UserVci> userVciList = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, user.getId())
                .list();
        if (!userVciList.isEmpty()) {
            List<Integer> userVciIds = userVciList.stream().map(c -> c.getId()).collect(Collectors.toList());
            userVciService.removeByIds(userVciIds);
        }

        //查询 设备表
        Device device = deviceService.lambdaQuery()
                .eq(Device::getUsername, user.getUsername())
                .one();

        if (!BeanUtil.isEmpty(device)) {
            device.setUsername("");
            deviceService.updateById(device);
        }
        boolean deleteById = this.removeById(id);
        if (deleteById == false) {
            return Result.error().message("删除失败");
        }
        return Result.ok();
    }

    @Override
    public Result getListByUserId(Integer userId) {
        User user = getById(userId);

        LambdaQueryWrapper<UserVci> vciLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vciLambdaQueryWrapper.eq(UserVci::getUserId, userId);
        List<UserVci> list = userVciService.list(vciLambdaQueryWrapper);
        Integer[] vciId = new Integer[list.size()];
        String[] vciNum = new String[list.size()];

        for (int i = 0; i < list.size(); i++) {
            LambdaQueryWrapper<VciInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VciInfo::getVciNum, list.get(i).getVciInfoId());
            VciInfo vciInfo = vciInfoService.getOne(queryWrapper);
            vciId[i] = vciInfo.getId();
            vciNum[i] = vciInfo.getVciNum();
        }
        UserVciNumVO userVciNumVO = new UserVciNumVO();
        userVciNumVO.setVciId(vciId);
        userVciNumVO.setVciNum(vciNum);


        return Result.ok(userVciNumVO);
    }

    @Override
    public Result<UserQueryPageVO> getPageList(UserQueryPageDTO dto) {
        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();
        String searchUsername = dto.getSearchUsername();
        String searchPhone = dto.getSearchPhone();

        Page<User> page = this.lambdaQuery()
                .like(searchUsername != null, User::getUsername, searchUsername)
                .like(searchPhone != null, User::getTel, searchPhone)
                .orderByDesc(User::getCreateTime)
                .page(new Page<>(pageIndex, pageSize));

        UserQueryPageVO vo = new UserQueryPageVO();
        vo.setCurrent((int) page.getCurrent());
        vo.setSize((int) page.getSize());
        vo.setPages((int) page.getPages());
        vo.setTotal((int) page.getTotal());
        if (searchUsername != null || searchPhone != null) {
            vo.setSearchCount(true);
        }
        List<User> records = page.getRecords();
        List<UserPageVO> userPageVOList = new ArrayList<>();
        if (!records.isEmpty()){
            for (User record : records) {
                UserPageVO userPageVO = new UserPageVO();
                BeanUtil.copyProperties(record, userPageVO);

                String password = userPageVO.getPassword();
                try {
                    password = AesUtil.Decrypt(password);
                } catch (Exception e) {
                    throw new BizException("密码解密失败");
                }
                userPageVO.setPassword(password);
                List<VciInfo> vciInfoList = getVciByUserId(record.getId()).getData();
                if (vciInfoList != null && !vciInfoList.isEmpty()) {
                    List<String> vciSns = vciInfoList.stream().map(c -> c.getVciNum()).collect(Collectors.toList());
                    userPageVO.setVciSn(vciSns);
                }
                userPageVOList.add(userPageVO);
            }
        }

        vo.setRecords(userPageVOList);

        return Result.ok(vo);
    }

    @Override
    public Result<UserVO> getByUserId(Integer userId) {
        User user = this.getById(userId);
        if (user == null) {
            throw new BadReqException("该用户不存在");
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);

        List<UserVci> userVciList = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, user.getId())
                .list();
        if (!userVciList.isEmpty()) {
            List<Integer> vciIds = userVciList.stream().map(c -> c.getVciInfoId()).collect(Collectors.toList());

            List<VciInfo> vciInfoList = vciInfoService.listByIds(vciIds);
            String[] vciSns = new String[vciInfoList.size()];
            List<String> vciNumList = vciInfoList.stream().map(c -> c.getVciNum()).collect(Collectors.toList());
            vciSns = vciNumList.toArray(vciSns);
            userVO.setVciSns(vciSns);
        }
        return Result.ok(userVO);
    }

    @Override
    public Result relieve() {
        return null;
    }

    @Override
    public Result updateState(Integer id, Integer state) {
        User selectUser = getById(id);
        if (BeanUtil.isEmpty(selectUser)) {
            throw new BadReqException("该用户不存在");
        }

        selectUser.setState(state);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        userMapper.update(selectUser, queryWrapper);

        return Result.ok();
    }

    @Override
    public Result updateType(Integer id, Integer type) {
        User selectUser = getById(id);
        if (BeanUtil.isEmpty(selectUser)) {
            throw new BadReqException("该用户不存在");
        }
        selectUser.setUserType(type);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        userMapper.update(selectUser, queryWrapper);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result updateUserInfo(UserAddVO user) {
        Integer userId = user.getId();

        User userById = getById(userId);

        String password = user.getPassword();
        BeanUtil.copyProperties(user, userById);
        try {
            password = AesUtil.Encrypt(password);
        } catch (Exception e) {
            throw new BizException("密码加密出错", ResultCode.PASSWORD_ENCRYPT_ERROR);
        }
        userById.setPassword(password);

    /*    if (!password.equals(userById.getPassword())){
            //密码加密
            try {
                password = AesUtil.Encrypt(password);
            } catch (Exception e) {
                throw new BizException("密码加密出错", ResultCode.PASSWORD_ENCRYPT_ERROR);
            }
            if (!password.equals(userById.getPassword())) {
                userById.setPassword(password);
            }

        }*/

        String deviceSn = user.getDeviceSn();
        if (deviceSn != null && !deviceSn.isEmpty()) {
            Device one = deviceService.lambdaQuery()
                    .eq(Device::getDeviceSn, deviceSn)
                    .one();
            if (BeanUtil.isEmpty(one)) {
                throw new BadReqException("该平板设备不存在");
            }
            one.setUsername(user.getUsername());
            deviceService.updateById(one);
        }

        Integer distributorId = userById.getDistributorId();
        //根据id查询维修厂
        if (distributorId != null){
            Distributor distributor = distributorService.getById(distributorId);
            if (BeanUtil.isEmpty(distributor)) {
                throw new BadReqException("该维修厂不存在");
            }
            userById.setDistributorName(distributor.getCompany());

        }

        List<String> vciSns = user.getVciSn();

        if (CollectionUtil.isNotEmpty(vciSns)) {
            List<UserVci> userVciList = new ArrayList<>();
            int i = 1;
            for (String vciSn : vciSns) {
                UserVci userVci = new UserVci();
                //根据vciSn查询
                VciInfo vciInfo = vciInfoService.lambdaQuery()
                        .eq(VciInfo::getVciNum, vciSn)
                        .one();
                if (vciInfo == null) {
                    throw new BadReqException("该VCI设备不存在");
                }
                //先查询uservci
                List<UserVci> userVciList1 = userVciService.lambdaQuery()
                        .eq(UserVci::getVciInfoId, vciInfo.getId())
                        .eq(UserVci::getUserId, userId)
                        .list();
                if (userVciList1.isEmpty()) {
                    userVci.setVciInfoId(vciInfo.getId());
                    userVci.setUserId(userId);
                    if (i==1){
                        userVci.setIsDefault(1);
                    }else {
                        userVci.setIsDefault(0);
                    }
                    userVciList.add(userVci);
                    i++;
                }
            }
            userVciService.saveOrUpdateBatch(userVciList);

        }

        this.updateById(userById);

        return Result.ok();
    }

    @Override
    public Result password(AppUserUpdatePwdDTO dto) {

        if (BeanUtil.isEmpty(dto)) {
            return Result.fail("未获取到数据").result(ResultCode.NO_DATA);
        }
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);

        Integer userId = guidDTO.getUserId();
        String username = dto.getUsername();
        User user = this.lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (user == null) {
            return Result.error().message("用户不存在").result(ResultCode.USER_NO_EXIST);
        }
        try {
            user.setPassword(AesUtil.Encrypt(dto.getNewPassword()));
        } catch (Exception e) {
            return Result.fail("密码加密出错").result(ResultCode.PASSWORD_ENCRYPT_ERROR);
        }
        this.updateById(user);


        return Result.ok();
    }

    @Override
    public Result register(UserLoginDTO userLoginDTO) {
        User user = new User();
        if (userLoginDTO.getUsername() == null || userLoginDTO.getPassword() == null) {
            return Result.error().message("用户名密码为空").result(ResultCode.NO_DATA);
        }
        if (userLoginDTO.getPassword().equals(userLoginDTO.getRePassword())) {
            return Result.error().message("两次密码不一样").result(ResultCode.PASSWORD_ERROR);
        }
        user.setUsername(userLoginDTO.getUsername());
        try {
            user.setPassword(AesUtil.Encrypt(userLoginDTO.getPassword()));
        } catch (Exception e) {
            return Result.error().message("密码加密错误").result(ResultCode.PASSWORD_ENCRYPT_ERROR);
        }
        boolean save = save(user);
        if (!save) {
            throw new BizException("数据库操作失败");
        }
        return Result.ok();
    }

    @Override
    public Result updateUserName(AppBaseDTO dto) {
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        Integer userId = guidDTO.getUserId();

        User user = getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在").result(ResultCode.USER_NO_EXIST);
        }
        user.setUsername(dto.getUsername());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, userId);
        this.update(user, queryWrapper);
        return Result.ok();

    }

    @Override
    public Result logout() {

        String token = request.getHeader("token");
        token = request.getParameter("token");
        //从token中获取用户id
        Integer uId = jwtUtils.getUserIdFromToken(token);
        //判断 用户id 是否为空
        if (org.springframework.util.StringUtils.isEmpty(uId)) {
            throw new CustomerAuthenticationException("token解析失败");
        }

        //判断redis中是否存在token信息
        String tokenKey = RedisConstant.USER_TOKEN_PREFIX + uId;
        redisTemplate.delete(tokenKey);

        return Result.ok();
    }

    @Override
    public Result updateVci(AppBaseDTO dto) {

        if (BeanUtil.isEmpty(dto)) {
            return Result.error().message("参数为空").result(ResultCode.NO_DATA);
        }
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        Integer userId = guidDTO.getUserId();
        String vciSn = dto.getVciSn();
        VciInfo vciInfo = vciInfoService.lambdaQuery()
                .eq(VciInfo::getVciNum, vciSn)
                .one();
        if (vciInfo == null) {
            return Result.error().message("VCI设备不存在").result(ResultCode.SERVICE_HANDLE_ERROR);
        }
        UserVci userVci = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, userId)
                .eq(UserVci::getIsDefault, true)
                .one();
        userVci.setVciInfoId(vciInfo.getId());

        LambdaQueryWrapper<VciInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VciInfo::getId, vciInfo.getId());
        boolean update = vciInfoService.update(vciInfo, queryWrapper);
        if (!update) {
            throw new BizException("数据库操作失败");
        }

        return Result.ok();
    }

    @Override
    public Result bindingVci(AppBindVO bindVO) {
        if (BeanUtil.isEmpty(bindVO)) {
            return Result.error().message("参数为空").result(ResultCode.NO_DATA);
        }
        Integer userId = bindVO.getUserId();
        String vciNum = bindVO.getVciNum();

        LambdaQueryWrapper<VciInfo> vciInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vciInfoLambdaQueryWrapper.eq(VciInfo::getVciNum, vciNum);
        VciInfo vciInfo = vciInfoService.getOne(vciInfoLambdaQueryWrapper);
        if (vciInfo == null) {
            return Result.error().message("VCI设备不存在").result(ResultCode.SERVICE_HANDLE_ERROR);
        }
        UserVci one = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, userId)
                .eq(UserVci::getVciInfoId, vciInfo.getId())
                .one();
        if (BeanUtil.isNotEmpty(one)) {
            throw new BadReqException("该vci设备已被该用户绑定");
        }

        UserVci userVci = new UserVci();
        userVci.setUserId(userId);
        userVci.setVciInfoId(vciInfo.getId());
        userVci.setIsDefault(1);
        userVciService.save(userVci);

        return Result.ok();


    }

    @Override
    public Result<List<VciInfo>> getVciByUserId(Integer userId) {
        //根据id查询user
        User user = this.getById(userId);
        if (BeanUtil.isEmpty(user)) {
            throw new BadReqException("该用户不存在");
        }
        List<UserVci> list = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, userId)
                .list();
        List<VciInfo> vciInfoList = new ArrayList<>();
        if (!list.isEmpty()) {
            List<Integer> vciIds = list.stream().map(c -> c.getVciInfoId()).collect(Collectors.toList());

            vciInfoList = vciInfoService.listByIds(vciIds);
        }
        return Result.ok(vciInfoList);
    }

    @Override
    public Result relieveVci(AppBindVO bindVO) {
        if (BeanUtil.isEmpty(bindVO)) {
            return Result.error().message("参数为空").result(ResultCode.NO_DATA);
        }
        Integer userId = bindVO.getUserId();
        String vciNum = bindVO.getVciNum();
        LambdaQueryWrapper<VciInfo> vciInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vciInfoLambdaQueryWrapper.eq(VciInfo::getVciNum, vciNum);
        VciInfo vciInfo = vciInfoService.getOne(vciInfoLambdaQueryWrapper);
        if (vciInfo == null) {
            return Result.error().message("VCI设备不存在").result(ResultCode.SERVICE_HANDLE_ERROR);
        }

        UserVci one = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, userId)
                .eq(UserVci::getVciInfoId, vciInfo.getId())
                .one();
        if (BeanUtil.isEmpty(one)) {
            throw new BadReqException("该客户端账号没有绑定该vci设备");
        }
        this.removeById(one.getId());

        return Result.ok();
    }

    @Override
    public Result updateDefaultVci(Integer userId, Integer vciId, Integer status) {
        //根据userid和vciId 查询
        UserVci userVci = userVciService.lambdaQuery()
                .eq(UserVci::getUserId, userId)
                .eq(UserVci::getVciInfoId, vciId)
                .one();
        if (BeanUtil.isEmpty(userVci)) {
            throw new BadReqException("该用户下没有绑定该vci设备");
        }
        userVci.setIsDefault(status);
        userVciService.updateById(userVci);
        return Result.ok();
    }

    @Override
    public Result resetPassword(Integer id) {
        User user = this.getById(id);
        if (BeanUtil.isEmpty(user)) {
            throw new BadReqException("该用户不存在");
        }

        try {
            String encrypt = AesUtil.Encrypt("111111");
            user.setPassword(encrypt);
        } catch (Exception e) {
            throw new BadReqException("密码加密错误");
        }

        this.updateById(user);
        return Result.ok();
    }

    @Override
    public List<User> listByDevice() {
        List<User> userList = this.lambdaQuery().list();
        List<User> collect = userList.stream().filter(user -> StringUtils.isBlank(user.getDeviceSn()))
                .collect(Collectors.toList());
        return collect;
    }


}
