package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.junmpProcess.dto.StartProcessInstanceDTO;
import com.junmp.junmpProcess.service.IFlowInstanceService;
import com.junmp.jyzb.api.SendInfoApi;
import com.junmp.jyzb.api.bean.dto.*;
import com.junmp.jyzb.api.bean.dto.fetchingDataDto.PoliceDto;
import com.junmp.jyzb.api.bean.dto.fetchingDataDto.UserDto;
import com.junmp.jyzb.api.bean.query.CabinetReq;
import com.junmp.jyzb.api.bean.query.PolicemanReq;
import com.junmp.jyzb.api.bean.query.QueryReassignmentReq;
import com.junmp.jyzb.api.bean.req.*;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.api.exception.enums.*;
import com.junmp.jyzb.api.expander.KfExpander;
import com.junmp.jyzb.cache.MsgRedisCache;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.CabinetBoxMapper;
import com.junmp.jyzb.mapper.CabinetMapper;
import com.junmp.jyzb.mapper.InventorySummaryMapper;
import com.junmp.jyzb.mapper.PolicemanMapper;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.BusinessUtil;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.jyzb.utils.RabbitMQSendMsg;
import com.junmp.jyzb.utils.RedisUtils;
import com.junmp.v2.auth.api.bean.login.LoginUser;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.auth.api.password.IStoredEncryptApi;
import com.junmp.v2.common.enums.LogicDelEnum;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import com.junmp.v2.file.api.bean.req.SysFileInfoReq;
import com.junmp.v2.file.api.bean.res.SysFileInfoResp;
import com.junmp.v2.file.api.constant.FileConstant;
import com.junmp.v2.file.biz.service.SysFileInfoService;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import com.junmp.v2.sys.api.bean.user.SysUserDto;
import com.junmp.v2.sys.api.bean.user.req.SysUserReq;
import com.junmp.v2.sys.api.bean.user.req.UserOrgReq;
import com.junmp.v2.sys.api.expander.SystemConfigExpander;
import com.junmp.v2.sys.user.entity.SysUser;
import com.junmp.v2.sys.user.entity.SysUserOrg;
import com.junmp.v2.sys.user.entity.SysUserRole;
import com.junmp.v2.sys.user.factory.SysUserCreateFactory;
import com.junmp.v2.sys.user.service.SysUserOrgService;
import com.junmp.v2.sys.user.service.SysUserRoleService;
import com.junmp.v2.sys.user.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


@Service
@Slf4j
public class PolicemanServiceImpl extends ServiceImpl<PolicemanMapper, Policeman> implements PolicemanService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private PolicemanMapper policemanMapper;


    @Resource
    private PubOrgService pubOrgService;

    @Resource
    private CabinetService cabinetService;

    @Resource
    private CabinetBoxService cabinetBoxService;

    @Resource
    private PoliceFingerService policeFingerService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private PoliceEquipmentService policeEquipmentService;

    @Resource
    private ReassignmentService reassignmentService;

    @Resource
    private IFlowInstanceService FlowInstanceService;

    @Resource
    private SysUserOrgService sysUserOrgService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private RestHighLevelClient client;

    @Resource
    private BusFormService busFormService;

    @Resource
    private CabinetBoxPoliceService cabinetBoxPoliceService;

    @Autowired
    private RabbitMQSendMsg MQ;

    @Resource
    private MessageApi messageApi;
    @Resource
    private MsgRedisCache redisCache;
    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private CabinetMapper cabinetMapper;

    @Resource
    private SysFileInfoService sysFileInfoService;

    @Resource
    private IStoredEncryptApi iStoredEncryptApi;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private WarehouseInventoryService warehouseInventoryService;

    @Resource
    private OrderMainService orderMainService;

    @Resource
    private SendInfoApi sendInfoApi;

    @Resource
    private CabinetBoxMapper cabinetBoxMapper;


    @Resource
    private PoliceEquipmentDetailService policeEquipmentDetailService;

    private static final String REDIS_POLICE = "Policeman_";
    private static final String REDIS_ORG = "Organization_";


    @Override
    public Object addEs() {
        return null;
    }

    /**
     * 添加警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String AddPoliceman(UpdatePolicemanReq req) {
        //判断传入的用户名是否存在
        SysUser one = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAccount, req.getAccount()));
        if (one!=null){
            throw new ServiceException(UserExceptionEnum.USER_IS_EXIST);
        }
        //判断警员编号是否已经存在
        //判断警员编号+姓名是否已经存在，并且该身份是民警，如果存在，那么直接添加失败

        List<Policeman> list = list(new LambdaQueryWrapper<Policeman>().eq(Policeman::getPoliceCode, req.getPoliceCode())
                .eq(Policeman::getIdentity, req.getIdentity()).eq(Policeman::getName, req.getName()));
        if (CollectionUtil.isNotEmpty(list)){
            throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_EXISTS);
        }


        //查询传入的组织机构id是否存在
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //绑定账号
        SysUser sysUser = add(req);
        //判断是否添加角色，进行绑定
        List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
        if (req.getRolesList().size()>0 ){
            for (Long roleId: req.getRolesList()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
                sysUserRole.setCreateUser(req.getCreateUser());
                sysUserRoleList.add(sysUserRole);
            }
        }
        sysUserRoleService.saveBatch(sysUserRoleList);
        Policeman policeman = new Policeman();
        BeanPlusUtil.copyProperties(req, policeman);
        policeman.setPassword(sysUser.getPassword());
        policeman.setState(1);
        policeman.setUserId(sysUser.getUserId());
        //如果有照片，将警员照片直接复制一下以防万一
        policeman.setPhoto(req.getPhoto());
        policeman.setOrgGuid(pubOrg.getGuid());
        policeman.setCreateTime(DateTimeUtil.getCurrentDateTime());
        policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        save(policeman);
        PubOrg orgInfo=pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, req.getOrgId()));
        orgInfo.setPoliceUpdateTime(DateTimeUtil.getCurrentDateTime());
        orgInfo.setPoliceUpdateService("平台");
        pubOrgService.updateById(orgInfo);

        List<Cabinet> cabinets= cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getOrgIdInt, req.getOrgId()));//拿到组织机构下所有的警柜用于消息推送
        if (cabinets.size()>0)
        {
            cabinets.forEach(t-> MQ.SendMsg("cabinetMsg",t.getDevSn(),"policeChange"));
        }

//        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),"InfoChange",5,
                "Adding policemanInfo",null,null,new ArrayList<>(),null,null);

        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),"InfoChange",10,
                "Adding UserInfo",null,null,new ArrayList<>(),null,null);//推送至仓库主机
        return policeman.getId();
    }

    /**
     * 添加警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PolicemanDto AddPolicemanFromCab(CabinetPolicemanReq req) {
        PubOrg orgInfo = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        //判断传入的警员是否存在
        Policeman one = this.getOne(new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getName, req.getName())
                .eq(Policeman::getPoliceCode, req.getPoliceCode())
                .eq(Policeman::getOrgId,orgInfo.getOrgId()));

        if (one!=null){
            throw new ServiceException(UserExceptionEnum.POLICE_IS_EXIST);
        }
        //查询传入的组织机构id是否存在
//        pubOrgService.PubOrgExist(req.getOrgId());

        //警柜添加的人员统一视为用户
        String UserRoleId="1716370847267106817";
        List<Long> roleList=new ArrayList<>();
        roleList.add(Long.valueOf(UserRoleId));
        req.setRolesList(roleList);
        //绑定账号
        SysUser sysUser = addFromCabinet(req,orgInfo.getOrgId());
        //判断是否添加角色，进行绑定
        List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
        if (req.getRolesList().size()>0 ){
            for (Long roleId: req.getRolesList()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                sysUserRole.setCreateUser(req.getCreateUser());
                sysUserRoleList.add(sysUserRole);
            }
        }
        sysUserRoleService.saveBatch(sysUserRoleList);
        Policeman policeman = new Policeman();
        BeanPlusUtil.copyProperties(req, policeman);
        policeman.setId(req.getStaffId());
        policeman.setOrgId(orgInfo.getOrgId());
        policeman.setOrgGuid(orgInfo.getGuid());
        policeman.setPassword(sysUser.getPassword());
        policeman.setState(ObjectUtil.isNotEmpty(req.getState())? req.getState() : 1);
        policeman.setUserId(sysUser.getUserId());
        policeman.setCreateTime(DateTimeUtil.getCurrentDateTime());
        policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        save(policeman);

        orgInfo.setPoliceUpdateTime(DateTimeUtil.getCurrentDateTime());

        //添加单警柜
        updateOrgAndSendMessage(orgInfo,req.getCabinetOrgCode(),req.getDevSn());
//警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",5,"Adding policemanInfo",
                null,null,new ArrayList<>(),null,null);
//        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",10,"Adding userInfo",
                null,null,new ArrayList<>(),null,null);

        PolicemanDto policemanDto = new PolicemanDto();
        BeanPlusUtil.copyProperties(policeman,policemanDto);
        return policemanDto;
    }

    /**
     * 警员绑定账号
     *
     * @param
     * @return
     */
    public SysUser addFromCabinet(CabinetPolicemanReq req,Long orgId) {
        String accountSet="";
        //判断是否有重复的账号
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getAccount, req.getName()+req.getPoliceCode()));
        if (list.size()>0){//警员账号如果已存在，则账号改为姓名+警号
            accountSet=req.getOrgCode()+req.getName()+req.getPoliceCode();
        }
        else
        {
            accountSet=req.getName()+req.getPoliceCode();
        }
        SysUser sysUser= new SysUser();
        BeanPlusUtil.copyProperties(req,sysUser);
        sysUser.setAccount(accountSet);
        sysUser.setNickName(req.getName());
        sysUser.setRealName(req.getName());
        sysUser.setPassword(req.getPassword());
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());
        sysUserService.save(sysUser);
        sysUserOrgService.add(sysUser.getUserId(), orgId, null);
        return sysUser;
    }
    public SysUser BindCabinet(PoliceListReq req,String orgId) {
        String accountSet="";
        //判断是否有重复的账号
        SysUser one = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getAccount, req.getName()));
        if (ObjectUtil.isNotNull(one)){//警员账号如果已存在，则账号改为姓名+警号
            accountSet=req.getName()+req.getPoliceCode();
        }
        else
        {
            accountSet=req.getName();
        }
        SysUser sysUser= new SysUser();
        BeanPlusUtil.copyProperties(req,sysUser);
        sysUser.setAccount(accountSet);
        sysUser.setNickName(req.getName());
        sysUser.setPassword(req.getPassword());
        sysUser.setRealName(req.getName());
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());
        sysUserService.save(sysUser);
        sysUserOrgService.add(sysUser.getUserId(), Long.valueOf(orgId), null);
        return sysUser;
    }
    /**
     * 警员绑定账号
     *
     * @param
     * @return
     */
    public SysUser add(UpdatePolicemanReq req) {
        //判断是否有重复的账号
        SysUser one = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getAccount, req.getAccount()));
        if (ObjectUtil.isNotNull(one)){
            throw new ServiceException(UserExceptionEnum.USER_IS_EXIST);
        }
        SysUser sysUser= new SysUser();
        BeanPlusUtil.copyProperties(req,sysUser);
        sysUser.setNickName(req.getName());
        sysUser.setRealName(req.getName());
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());
        sysUserService.save(sysUser);
        sysUserOrgService.add(sysUser.getUserId(), req.getOrgId(), null);
        return sysUser;
    }



    // 更新缓存的方法，新增警员信息时调用
    private void updatePoliceIdCache(String orgId, String newPoliceId) {
        // 构建 Redis 缓存键
        String redisKeyFalse = "getAllPoliceId_false_" + orgId;
        String redisKeyTrue = "getAllPoliceId_true_" + orgId;

        // 从 Redis 中获取旧的缓存数据
        List<String> cachedDataFalse = redisUtils.findCachedData(redisKeyFalse);
        List<String> cachedDataTrue = redisUtils.findCachedData(redisKeyTrue);

        //如果缓存中没有数据，则直接查询数据库并更新Redis缓存
        //如果缓存中有数据，就更新数据
        if (cachedDataFalse == null && cachedDataTrue == null) {
            //getAllPoliceId(Map.of("IncludeLowerLevel", false, "orgId", orgId));
            return;
        } else if (cachedDataFalse != null) {
            cachedDataFalse.add(newPoliceId);
            redisUtils.set(redisKeyFalse, cachedDataFalse);
        } else if (cachedDataTrue != null) {
            cachedDataTrue.add(newPoliceId);
            redisUtils.set(redisKeyTrue, cachedDataTrue);
        }
    }

    //删除缓存的方法
    private void deletePoliceIdCache(String orgId) {
        //构建 Redis 缓存键
        String redisKey = "getAllPoliceId_false_" + orgId;
        redisUtils.delete(redisKey);

        //构建 Redis 缓存键
        redisKey = "getAllPoliceId_true_" + orgId;
        redisUtils.delete(redisKey);
    }


    /**
     * @param req
     * @return
     */
    @Override
    public PolicemanDto GetOnePolice(PolicemanReq req) {
        PolicemanDto policemanDto = new PolicemanDto();
        if (ObjectUtil.isNull(req.getId()) && ObjectUtil.isNotNull(req.getUserId())){
            Policeman one = getOne(new LambdaQueryWrapper<Policeman>().eq(Policeman::getUserId, req.getUserId()));
            BeanPlusUtil.copyProperties(one,policemanDto);
            return policemanDto;
        }
        Policeman one = PoliceExist(req.getId());
        BeanPlusUtil.copyProperties(one, policemanDto);
        PubOrg pubOrg = pubOrgService.PubOrgExist(one.getOrgId());

        //将箱门信息展示：
        List<Cabinet> cabinetInfo = cabinetMapper.getAllCabinetsWithSingleCabinet(String.valueOf(one.getOrgId()), req.getId());
        List<String> boxList=new ArrayList<>();
        String boxName="";
        if (cabinetInfo.size()>0){
            for (Cabinet cabinet:cabinetInfo) {

                if (cabinet.getContainType().equals("1")){
                    boxList.add(0,cabinet.getBoxId());
                    boxName = (ObjectUtil.isNull(cabinet.getName())?cabinet.getName():cabinet.getLocation())+"单警"+cabinet.getBoxNo()+"号箱门，"+boxName;

                }else {
                    boxList.add(cabinet.getBoxId());
                    boxName = boxName + (ObjectUtil.isNull(cabinet.getName())?cabinet.getName():cabinet.getLocation())+"公共"+cabinet.getBoxNo()+"号箱门，";
                }
            }
            policemanDto.setBoxList(boxList);
        }
        policemanDto.setBoxName(boxName.trim().isEmpty()?boxName:boxName.substring(0,boxName.length()-1));

        //将警员的指纹信息查询出来
        List<PoliceFinger> list1 = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>()
                .eq(ObjectUtil.isNotNull(req.getId()), PoliceFinger::getPoliceId, req.getId()));
        List<PoliceFingerDto> fingerDtoList = new ArrayList<>();
        for (PoliceFinger policeFinger : list1) {
            PoliceFingerDto policeFingerDto = new PoliceFingerDto();
            BeanPlusUtil.copyProperties(policeFinger, policeFingerDto);
            fingerDtoList.add(policeFingerDto);
        }
        policemanDto.setFingersList(fingerDtoList);
        //将账号名称返回
        policemanDto.setAccount(sysUserService.getById(policemanDto.getUserId()).getAccount());
        //通过警员信息将该警员的角色id返回
        List<SysUserRoleDto> sysUserRoleDtos = policemanMapper.selectUserRoleInfo(policemanDto.getUserId());
        List<Long> roleIds=new ArrayList<>();
        String roleNames="";
        for (SysUserRoleDto sysUserRoleDto:sysUserRoleDtos) {
            roleIds.add(sysUserRoleDto.getRoleId());
            roleNames+=sysUserRoleDto.getRoleName()+",";
        }
        // 删除最后一个逗号
        if (!roleNames.isEmpty()) {
            roleNames = roleNames.substring(0, roleNames.length() - 1);
        }
        policemanDto.setRolesList(roleIds);
        policemanDto.setRolesName(roleNames);
        policemanDto.setOrgName(pubOrg.getOrgName());

        return policemanDto;
    }




    /**
     * 删除警员信息
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean DeletePolice(UpdatePolicemanReq req) {
        //通过警员id查询警员信息
        Policeman policeman = PoliceExist(req.getId());
        policeman.setState(0);
        return updateById(policeman);

    }
    /**
     * 禁用警员信息
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PolicemanDto DeletePoliceFromCab(CabinetPolicemanReq req) {
        //通过警员id查询警员信息
        Policeman policeman = PoliceExist(req.getStaffId());

        if (policeman.getState().equals(2))//说明当前警员调岗中不可操作
        {
            throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_BUSY);
        }
        else
        {
            policeman.setState(3);
        }
        policeman.setUserLocalId(req.getUserLocalId());
        sysUserService.update(new LambdaUpdateWrapper<SysUser>().set(SysUser::getDelFlag,1).eq(SysUser::getUserId,policeman.getUserId()));
        PubOrg orgInfos = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        orgInfos.setPoliceUpdateTime(DateTime.now());
        updateOrgAndSendMessage(orgInfos,req.getCabinetOrgCode(),req.getDevSn());
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",orgInfos.getOrgId().toString(),"InfoChange",5,"delete policemanInfo",
                null,null,new ArrayList<>(),null,null);
        this.updateById(policeman);
        PolicemanDto policemanDto = new PolicemanDto();
        BeanPlusUtil.copyProperties(req,policemanDto);
        return policemanDto;


    }


    /**
     * 修改警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePolice(UpdatePolicemanReq req) {
        //判断警员是否存在
        Policeman one = PoliceExist(req.getId());
        if (ObjectUtil.isEmpty(req.getName()) || ObjectUtil.isEmpty(req.getPoliceCode())){
            throw new ServiceException(PolicemanExceptionEnum.POLICE_INFO_IS_EMPTY);
        }
        List<Policeman> list = list(new LambdaQueryWrapper<Policeman>().eq(Policeman::getPoliceCode, req.getPoliceCode())
                .eq(Policeman::getIdentity, req.getIdentity()).eq(Policeman::getName, req.getName()));

        if (CollectionUtil.isNotEmpty(list) && list.size()==1){
            Policeman policeman = list.get(0);
            if (!policeman.getId().equals(req.getId())){
                throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_EXISTS);
            }
        }else if (CollectionUtil.isNotEmpty(list) && list.size()>1){
            throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_EXISTS);

        }
        //首先我需要判断用户名是否由警员姓名或者警员编号组成，如果是则进行下一步判断
        List<SysUser> userInfoList = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, req.getUserId()).or().eq(SysUser::getAccount, req.getAccount()));
        SysUser user = userInfoList.stream().filter(a -> a.getUserId().equals(req.getUserId())).collect(Collectors.toList()).get(0);

        List<SysUser> accountList = userInfoList.stream().filter(a -> a.getAccount().equals(req.getAccount()) && !a.getUserId().equals(req.getUserId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(accountList)){
            throw new ServiceException(UserExceptionEnum.USER_IS_EXIST);
        }
        if (!user.getAccount().equals(req.getAccount())){
            user.setAccount(req.getAccount());
        }
        //判断如果姓名和警员编号不一致，那么我直接对account进行修改，否则不变
//        user.setPassword(req.getPassword());
        if (!user.getRealName().equals(req.getName())){
            user.setNickName(req.getName());
            user.setRealName(req.getName());
        }
        if (ObjectUtil.isNotEmpty(req.getPhone())){
            user.setPhone(req.getPhone());
        }
        sysUserService.updateById(user);
        //判断传入的修改的警员编号与本身编号一致，如果一致则无所谓，如果不一致则需要判断修改的警员编号是否已经存在
        BeanPlusUtil.copyProperties(req, one);
//        if (!req.getPoliceCode().equals(one.getPoliceCode())) {
//            Policeman one1 = getOne(new LambdaQueryWrapper<Policeman>()
//                    .eq(ObjectUtil.isNotNull(req.getPoliceCode()), Policeman::getPoliceCode, req.getPoliceCode()));
//            if (ObjectUtil.isNotNull(one1)) {
//                throw new ServiceException(PolicemanExceptionEnum.POLICECODE_IS_EXISTS);
//            }
//        }
        one.setUpdateTime(DateTimeUtil.getCurrentDateTime());

        //修改角色
        if (req.getRolesList().size()>0){
//            sysUserRoleService.removeBatchByIds(req.getRolesList());
            sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,req.getUserId()));
            List<SysUserRole> collect = req.getRolesList().stream().map(s -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(req.getUserId());
                sysUserRole.setRoleId(s);
                sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
                return sysUserRole;
            }).collect(Collectors.toList());
            sysUserRoleService.saveBatch(collect);
        }
        PubOrg orgInfos=pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, req.getOrgId()));
        orgInfos.setPoliceUpdateTime(DateTime.now());
        orgInfos.setPoliceUpdateService("平台");
        pubOrgService.updateById(orgInfos);
        List<Cabinet> cabinets= cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getOrgIdInt, req.getCabinetOrgId()));//拿到组织机构下所有的警柜用于消息推送
        if (cabinets.size()>0)
        {
            cabinets.forEach(t-> MQ.SendMsg("cabinetMsg",t.getDevSn(),"policeChange"));
        }
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),"InfoChange",5,"Updating policemanInfo",
                null,null,new ArrayList<>(),null,null);

        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),"InfoChange",10,"Updating UserInfo",
                null,null,new ArrayList<>(),null,null);
        return updateById(one);
    }
    /**
     * 修改警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PolicemanDto UpdatePoliceFromCab(CabinetPolicemanReq req) {
        //判断警员是否存在
        Policeman policeInfo = PoliceExist(req.getStaffId());
        BeanPlusUtil.copyProperties(req,policeInfo);
        policeInfo.setId(req.getStaffId());
        //查询传入的组织机构id是否存在
        PubOrg orgInfo = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        //判断传入的修改的警员编号与本身编号一致，如果一致则无所谓，如果不一致则需要判断修改的警员编号是否已经存在
        if (!req.getPoliceCode().equals(policeInfo.getPoliceCode())) {
          //这里需要判断警号和姓名是否都存在
            Policeman exist = this.getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getName, req.getName())
                    .eq(Policeman::getPoliceCode, req.getPoliceCode())
                    .eq(Policeman::getOrgId,orgInfo.getOrgId()));
            if (ObjectUtil.isNotNull(exist)) {
                throw new ServiceException(PolicemanExceptionEnum.POLICECODE_IS_EXISTS);
            }
        }
        SysUser user= sysUserService.getById(policeInfo.getUserId());
        if ((policeInfo.getName()+policeInfo.getPoliceCode()).equals(user.getAccount())
                || policeInfo.getPoliceCode().equals(user.getAccount() )
                || policeInfo.getName().equals(user.getAccount())){

            user.setAccount(req.getName()+req.getPoliceCode());

        }
        user.setNickName(req.getName());
        user.setRealName(req.getName());
        sysUserService.updateById(user);
        if (ObjectUtil.isNotEmpty(req.getPassword())){
            policeInfo.setPassword(req.getPassword());
            sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getPassword,req.getPassword())
                    .eq(SysUser::getUserId,policeInfo.getUserId()));
        }
        if (ObjectUtil.isNotEmpty(req.getPhoto())){
            policeInfo.setPhoto(req.getPhoto());
        }
        policeInfo.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        orgInfo.setPoliceUpdateTime(DateTime.now());
        updateOrgAndSendMessage(orgInfo,req.getCabinetOrgCode(),req.getDevSn());
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",5,"Updating policemanInfo",
                null,null,new ArrayList<>(),null,null);
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",10,"Updating UserInfo",
                null,null,new ArrayList<>(),null,null);
        updateById(policeInfo);
        PolicemanDto policemanDto = new PolicemanDto();
        BeanPlusUtil.copyProperties(policeInfo,policemanDto);
        return policemanDto;
    }

    /**
     * 修改警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UploadPolicemanList(CabinetUploadReq req) {
        List<CabinetDataList> dataList = req.getDataList();
        Cabinet cabinetOrg = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn, req.getDevSn()));

        for (CabinetDataList orgList : dataList) {
            PubOrg orgInfo = pubOrgService.PubOrgCodeExist(orgList.getOrgCode());

            // 获取上报的警员列表
            List<PoliceListReq> policeReqList = orgList.getPoliceList();
            Set<String> reqPoliceIds = policeReqList.stream().map(PoliceListReq::getPoliceId).collect(Collectors.toSet());
            // 查询数据库中的警员列表
            List<Policeman> policeListCurrent = this.list(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getOrgId, orgInfo.getOrgId()));
            // 从数据库中查询指定警员ID的数据
            List<Policeman> policeList = this.list(new LambdaQueryWrapper<Policeman>().in(Policeman::getId, reqPoliceIds));


            // 比较并处理新增、删除和修改的数据
            List<Policeman> toAdd = new ArrayList<>();
            List<Policeman> toDelete = new ArrayList<>();
            List<CabinetBoxPolice> toDeleteCabAndPo = new ArrayList<>();
            List<Policeman> toUpdate = new ArrayList<>();

            // 处理新增和修改
            for (PoliceListReq reqPolice : policeReqList) {
                Policeman dbPolice = findPoliceById(policeList, reqPolice.getPoliceId());
                SysUser user= sysUserService.getById(dbPolice.getUserId());
                if (dbPolice == null) {
                    // 新增数据
                    Policeman newPolice = convertToPoliceman(reqPolice, orgInfo.getOrgId().toString());
                    toAdd.add(newPolice);
                } else {
                    // 修改数据
                    Policeman updatedPolice = updatePoliceman(user,dbPolice, reqPolice, orgInfo, cabinetOrg);
                    toUpdate.add(updatedPolice);
                }
            }

            // 处理删除
            for (Policeman dbPolice : policeListCurrent) {
                PoliceListReq matchingReqPolice = findPoliceReqById(policeReqList, dbPolice.getId());
                if (matchingReqPolice == null) {
                    dbPolice.setState(0);
                    // 将箱门全部清除
                    List<CabinetBoxPolice> cbplist = cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, dbPolice.getId()));
                    toDeleteCabAndPo.addAll(cbplist);
                    // 数据库中存在但上报数据中不存在，需要删除
                    toDelete.add(dbPolice);
                }
            }

            // 执行新增、删除和修改操作
            if (!toAdd.isEmpty()) {
                this.saveBatch(toAdd);
            }
            if (!toUpdate.isEmpty()) {
                this.updateBatchById(toUpdate);
            }
            if (!toDelete.isEmpty()) {
                this.updateBatchById(toDelete);
                cabinetBoxPoliceService.removeBatchByIds(toDeleteCabAndPo);
            }
        }

        return true;
    }


    // 辅助方法：根据警员ID在列表中查找警员
    private Policeman findPoliceById(List<Policeman> policeList, String policeId) {
        return policeList.stream().filter(p -> Objects.equals(p.getId(), policeId)).findFirst().orElse(null);
    }

    // 辅助方法：根据警员ID在上报数据列表中查找警员
    private PoliceListReq findPoliceReqById(List<PoliceListReq> policeReqList, String policeId) {
        return policeReqList.stream().filter(p -> Objects.equals(p.getPoliceId(), policeId)).findFirst().orElse(null);
    }

    // 辅助方法：将 PoliceListReq 转换为 Policeman 对象
    private Policeman convertToPoliceman(PoliceListReq reqPolice,String orgID) {
        //警柜添加的人员统一视为用户
        String UserRoleId="1716370847267106817";
        List<Long> roleList=new ArrayList<>();
        roleList.add(Long.valueOf(UserRoleId));
        reqPolice.setRolesList(roleList);
        //绑定账号
        SysUser sysUser = BindCabinet(reqPolice,orgID);
        //判断是否添加角色，进行绑定
        List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
        if (reqPolice.getRolesList().size()>0 ){
            for (Long roleId: reqPolice.getRolesList()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                sysUserRole.setCreateUser("cabinet");
                sysUserRoleList.add(sysUserRole);
            }
        }
        sysUserRoleService.saveBatch(sysUserRoleList);
        Policeman policeman = new Policeman();
        BeanPlusUtil.copyProperties(reqPolice, policeman);
        policeman.setPassword(sysUser.getPassword());
        policeman.setState(1);
        policeman.setUserId(sysUser.getUserId());
        policeman.setCreateTime(DateTimeUtil.getCurrentDateTime());
        policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        save(policeman);
        return policeman;
    }

    // 辅助方法：更新 Policeman 对象的属性
    private Policeman updatePoliceman(SysUser user, Policeman dbPolice, PoliceListReq reqPolice, PubOrg org, Cabinet cabinet) {
        CabinetBox cb = cabinetBoxService.getById(reqPolice.getCabinetBoxId());
        if (cb.getBoxName() == null) {
            cb.setBoxName("");
        }
        // 判断警员是否存在
        // 判断传入的修改的警员编号与本身编号一致，如果一致则无所谓，如果不一致则需要判断修改的警员编号是否已经存在
        user.setPassword(reqPolice.getPassword());
        dbPolice.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        List<PoliceEquipment> policeEqsList = policeEquipmentService.list(new LambdaQueryWrapper<PoliceEquipment>()
                .eq(PoliceEquipment::getPoliceId, dbPolice.getId()));
        if (!dbPolice.getOrgId().equals(org.getOrgId())) {//现有警员组织机构和原有的不一样，说明是调岗的


            policeEquipmentService.removeBatchByIds(policeEqsList);
            List<PoliceEquipment> addEqsList = new ArrayList<>();
            List<EquipmentsReq> reqEquipment = reqPolice.getEquipments();
            List<InventorySummary> toUpdateInventoryList = new ArrayList<>();
            List<InventorySummary> toAddInventoryList = new ArrayList<>();
            List<InventorySummary> toDeleteInventoryList = new ArrayList<>();

            for (EquipmentsReq reqEq : reqEquipment) {
                PoliceEquipment pe = new PoliceEquipment();
                pe.setId(UUID.randomUUID().toString());
                pe.setPoliceId(dbPolice.getId());
                pe.setPoliceName(dbPolice.getName());
                pe.setNum(Integer.valueOf(reqEq.getNum()));
                pe.setPrice(reqEq.getPrice());
                pe.setCreateTime(DateTimeUtil.getCurrentDateTime());
                pe.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                pe.setOrgId(org.getOrgId());
                pe.setOutNum(Integer.valueOf(reqEq.getOutNum()));
                pe.setInNum(Integer.valueOf(reqEq.getInNum()));
                pe.setLocationId(cb.getId());
                pe.setLocationName(cabinet.getName() + "-" + cb.getBoxName());
                BeanPlusUtil.copyProperties(reqEq, pe);
                addEqsList.add(pe);
                List<InventorySummary> inventoryList = inventorySummaryService.list(
                        new LambdaQueryWrapper<InventorySummary>().eq(InventorySummary::getOrgId, dbPolice.getOrgId())
                );
                // 判断是否存在相同编号的设备
                Optional<InventorySummary> existingInventory = inventoryList.stream()
                        .filter(inventory -> inventory.getSizeId().equals(reqEq.getSizeId()) &&
                                inventory.getTypeId().equals(reqEq.getTypeId())&&inventory.getPrice().equals(
                                        reqEq.getPrice()
                        ))
                        .findFirst();//原有组织机构数据

                List<InventorySummary> NowInventoryList = inventorySummaryService.list(
                        new LambdaQueryWrapper<InventorySummary>().eq(InventorySummary::getOrgId, org.getOrgId())
                );
                // 判断是否存在相同编号的设备
                Optional<InventorySummary> NowExistingInventory = NowInventoryList.stream()
                        .filter(inventory -> inventory.getSizeId().equals(reqEq.getSizeId()) &&
                                inventory.getTypeId().equals(reqEq.getTypeId())&&inventory.getPrice().equals(
                                        reqEq.getPrice()))
                        .findFirst();//现在组织机构数据
                if (dbPolice.getOrgId() == null) {//如果为空则说明调岗中，则只需要为当前组织机构增加相应数据即可
                    if (existingInventory.isPresent()) {
                        // 如果存在，更新数据库中的数据
                        InventorySummary existingInventorySummary = existingInventory.get();
                        existingInventorySummary.setNumber(Integer.valueOf(reqEq.getNum() + existingInventorySummary.getNumber()));
                        existingInventorySummary.setPrice(existingInventorySummary.getPrice().add(reqEq.getPrice()));
                        existingInventorySummary.setOutboundNumber(existingInventorySummary.getOutboundNumber() - Integer.valueOf(reqEq.getOutNum()));
                        existingInventorySummary.setStockNumber(existingInventorySummary.getStockNumber() + Integer.valueOf(reqEq.getInNum()));
                        toUpdateInventoryList.add(existingInventorySummary);
                    } else {
                        // 如果不存在，新增数据到数据库
                        InventorySummary newInventory = inventorySummaryService.createInventorySummary(org.getOrgId(),
                                org.getOrgName(),org.getOrgCode(),reqEq.getTypeId(),reqEq.getTypeName(),reqEq.getSizeId(),
                                reqEq.getSizeName(),cabinet.getId(),cabinet.getName(),reqEq.getInNum(),reqEq.getOutNum(),reqEq.getPrice()
                                ,0,0,0,0,0,0,0,"1");
                        toAddInventoryList.add(newInventory);
                    }
                } else {

                        if (existingInventory.isPresent()) {
                            // 如果存在，减去对应数量
                            InventorySummary existingInventorySummary = existingInventory.get();
                            existingInventorySummary.setNumber(Math.max(0, existingInventorySummary.getNumber() - Integer.parseInt(String.valueOf(reqEq.getNum()))));
                            existingInventorySummary.setPrice(
                                    existingInventorySummary.getPrice().subtract(reqEq.getPrice()).max(BigDecimal.ZERO)
                            );
                            existingInventorySummary.setOutboundNumber(Math.max(0, existingInventorySummary.getOutboundNumber() - Integer.parseInt(String.valueOf(reqEq.getOutNum()))));
                            existingInventorySummary.setStockNumber(Math.max(0, existingInventorySummary.getStockNumber() - Integer.parseInt(String.valueOf(reqEq.getInNum()))));
//                            existingInventorySummary.setOutboundNumberPrice(
//                                    existingInventorySummary.getOutboundNumberPrice().subtract(reqEq.getOutPrice()).max(BigDecimal.ZERO)
//                            );
//                            existingInventorySummary.setStockNumberPrice(
//                                    existingInventorySummary.getStockNumberPrice().subtract(reqEq.getInPrice()).max(BigDecimal.ZERO)
//                            );
                            // 判断 Number 是否为 0 或者小于 0
                            if (existingInventorySummary.getNumber() <= 0) {
                                toDeleteInventoryList.add(existingInventorySummary);
                            } else {
                                toUpdateInventoryList.add(existingInventorySummary);
                            }
                        }
                    if (NowExistingInventory.isPresent()) {
                        // 如果存在，更新数据库中的数据
                        InventorySummary existingInventorySummary = existingInventory.get();
                        existingInventorySummary.setNumber(Integer.valueOf(reqEq.getNum() + existingInventorySummary.getNumber()));
                        existingInventorySummary.setPrice(existingInventorySummary.getPrice().add(reqEq.getPrice()));
                        existingInventorySummary.setOutboundNumber(existingInventorySummary.getOutboundNumber() - Integer.valueOf(reqEq.getOutNum()));
                        existingInventorySummary.setStockNumber(existingInventorySummary.getStockNumber() + Integer.valueOf(reqEq.getInNum()));
                        toUpdateInventoryList.add(existingInventorySummary);
                    } else {
                        // 如果不存在，新增数据到数据库
                        InventorySummary newInventory = inventorySummaryService.createInventorySummary(org.getOrgId(),
                                org.getOrgName(),org.getOrgCode(),reqEq.getTypeId(),reqEq.getTypeName(),reqEq.getSizeId(),
                                reqEq.getSizeName(),cabinet.getId(),cabinet.getName(),reqEq.getInNum(),reqEq.getOutNum(),reqEq.getPrice()
                                ,0,0,0,0,0,0,0,"1");
                        toAddInventoryList.add(newInventory);
                    }
                    }
                }


            // 批量更新
            if (!toUpdateInventoryList.isEmpty()) {
                inventorySummaryService.updateBatchById(toUpdateInventoryList);
            }

            // 批量插入
            if (!toAddInventoryList.isEmpty()) {
                inventorySummaryService.saveBatch(toAddInventoryList);
            }
            // 执行删除操作
            if (!toDeleteInventoryList.isEmpty()) {
                inventorySummaryService.removeByIds(
                        toDeleteInventoryList.stream().map(InventorySummary::getId).collect(Collectors.toList())
                );
            }
            policeEquipmentService.saveBatch(addEqsList);
        }
        dbPolice.setOrgId(Long.valueOf(org.getOrgId()));
        dbPolice.setState(1);
        BeanPlusUtil.copyProperties(reqPolice, dbPolice);
        sysUserService.updateById(user);
        return dbPolice;
    }



    /**
     * 修改用户状态
     *
     * @param req
     * @return
     */
    @Override
    public boolean ChangePoliceState(UpdatePolicemanReq req) {
        if (req.getState()!=1 && req.getState()!=2){
            throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
        }
        SysUser sysUser = sysUserService.getById(req.getUserId());
        sysUser.setStatusFlag(req.getState());
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),"InfoChange",10,"Updating UserInfo",
                null,null,new ArrayList<>(),null,null);
        return sysUserService.updateById(sysUser);

    }

    public List<Map<String, Object>> getAllPolicemanMsg(Map<String, Object> msg, List<String> allPoliceId) {
        List<Map<String, Object>> allPoliceman = new ArrayList<>();
        // 构建 Redis 缓存键
        String redisKey = REDIS_ORG + msg.get("IncludeLowerLevel").toString() + '_' + msg.get("orgId").toString();
        // 从 Redis 中获取数据
        List<Map<String, Object>> cachedData = redisUtils.findCachedData(redisKey);
        if (cachedData != null) {
            //将Long类型的数据转化为Date
            for (Map<String, Object> one : cachedData) {
                Long dataMsg = (Long) one.get("updateTime");
                one.put("updateTime", redisUtils.getDate(dataMsg));
                allPoliceman.add(one);
            }
            return cachedData;
        }
        for (String policeId : allPoliceId) {
            Map<String, Object> policeMsg = policemanMapper.getOnePolice(policeId);
            allPoliceman.add(policeMsg);
        }

        //按照updateTime降序排序
        DateTimeUtil.timeSort(allPoliceman);

        //将查询结果存入 Redis 中
        redisUtils.set(redisKey, allPoliceman);
        return allPoliceman;
    }


    public List<PolicemanDto> GetAllPolicemanList(PolicemanReq req) {
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }else {
            req.setOrder("desc");
            req.setColumn("create_time");
        }

        List<PolicemanDto> policemanDtos = policemanMapper.selectUserBypoliceIds
                (req.getOrgId(),req.getAccount(),req.getName(),req.getPoliceCode(),
                        req.getState(),req.getUserId(),req.getPhone(),req.getFlag(),null
                        ,null,req.getColumn(),req.getOrder(),req.getRoleCodeList(),req.getOrgList(),null);
        return policemanDtos;
    }

    private final ExecutorService executorService = Executors.newFixedThreadPool(5); // 适当设置线程池大小

    public List<CabinetPoliceDto> GetListByOrgAsync(PolicemanReq req) {
        List<CompletableFuture<CabinetPoliceDto>> futures = new ArrayList<>();

        for (String orgCode : req.getOrgList()) {
            CompletableFuture<CabinetPoliceDto> future = CompletableFuture.supplyAsync(() -> {
                return processOrg(orgCode,req.getStartTime());
            }, executorService);

            futures.add(future);
        }

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        try {
            // 等待所有异步任务完成
            allOf.get(30, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | java.util.concurrent.TimeoutException e) {
            e.printStackTrace(); // 处理异常，具体根据业务需要进行调整
        }

        List<CabinetPoliceDto> result = new ArrayList<>();
        for (CompletableFuture<CabinetPoliceDto> future : futures) {
            try {
                result.add(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace(); // 处理异常，具体根据业务需要进行调整
            }
        }

        return result;
    }
    private CabinetPoliceDto processOrg(String orgCode,String startTime) {
        CabinetPoliceDto cpDto = new CabinetPoliceDto();

        // 获取组织机构信息
        PubOrg orgInfo = pubOrgService.PubOrgCodeExist(orgCode);
//        PubOrg orgInfo = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, org));
        cpDto.setOrgId(orgInfo.getOrgId());
        cpDto.setLastAction(orgInfo.getPoliceUpdateService());
        cpDto.setActionUpdateTime(String.valueOf(orgInfo.getPoliceUpdateTime()));
        cpDto.setOrgName(orgInfo.getOrgName());

        // 获取组织机构下的警员列表，state字段为字符串 "1"
        List<Policeman> policeList = this.list(new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getOrgId, orgInfo.getOrgId())
                .eq(Policeman::getState, 1)
                .ge(ObjectUtil.isNotEmpty(startTime),Policeman::getUpdateTime,startTime));

        // 转换警员信息为 PoliceDetailDto
        List<PoliceDetailDto> policeDtoList = new ArrayList<>();
        for (Policeman police : policeList) {
            PoliceDetailDto pdDto = new PoliceDetailDto();
            BeanPlusUtil.copyProperties(police, pdDto);
            //将箱门信息展示：
            List<Cabinet> cabinetInfo = cabinetMapper.getAllCabinetsWithSingleCabinet(orgInfo.getOrgId().toString(), police.getId());
            List<String> boxList=new ArrayList<>();
            if (cabinetInfo.size()>0){
                for (Cabinet cabinet:cabinetInfo) {

                    if (cabinet.getContainType().equals("1")){
                        boxList.add(0,cabinet.getBoxId());
                    }else {
                        boxList.add(cabinet.getBoxId());
                    }
                }
                pdDto.setBoxList(boxList);
            }
            List<PoliceFinger> list = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>().eq(PoliceFinger::getPoliceId, police.getId()).isNotNull(PoliceFinger::getCabFingerNum));
            List<UpdatePoliceFingerReq> collect = list.stream().map(policeFinger -> {
                UpdatePoliceFingerReq updatePoliceFingerReq = new UpdatePoliceFingerReq();
                BeanPlusUtil.copyProperties(policeFinger, updatePoliceFingerReq);
                return updatePoliceFingerReq;
            }).collect(Collectors.toList());
            pdDto.setFingerList(collect);
            policeDtoList.add(pdDto);

        }

        cpDto.setPoliceList(policeDtoList);
        return cpDto;
    }

    //通过组织机构id查询警员列表(page)
    @Override
    public PageResult<PolicemanDto> GetAllPolicemanPage(PolicemanReq req) {
        //查询传入的组织机构id是否存在
//        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //查询出组织机构下的所有警员信息
        //排序字段（默认以用户状态进行排序）
        //(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }else {
            req.setOrder("desc");
            req.setColumn("create_time");
        }
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        long size=policemanMapper.count(req.getOrgId(),req.getAccount(),
                req.getName(),req.getPoliceCode(),req.getState(),
                req.getUserId(),req.getPhone(),req.getFlag(),req.getRoleCodeList(),req.getIsAllOrgVisible());
        List<PolicemanDto> policemanDtos = policemanMapper.selectUserBypoliceIds
                (req.getOrgId(),req.getAccount(),req.getName(),req.getPoliceCode(),
                        req.getState(),req.getUserId(),req.getPhone(),req.getFlag(),(req.getPageNo()-1)*req.getPageSize()
                        ,req.getPageSize(),req.getColumn(),req.getOrder(),req.getRoleCodeList(),req.getOrgList(),req.getIsAllOrgVisible());

        List<PolicemanDto> collect = policemanDtos.stream()
                .peek(policeman -> {
                    List<PoliceEquipment> list1 = policeEquipmentService.list(
                            new LambdaQueryWrapper<PoliceEquipment>().eq(PoliceEquipment::getPoliceId, policeman.getId()));
                    List<PoliceEquipmentDto> beanList = BeanPlusUtil.toBeanList(list1, PoliceEquipmentDto.class);
                    policeman.setPoliceEquipmentList(beanList);
                }).collect(Collectors.toList());
       //判断是否需要添加空数据
        if(req.getIsCreateNullDate()==null || req.getIsCreateNullDate()){
            Class<PolicemanDto> policemanDto = PolicemanDto.class;
            List<PolicemanDto> nullData = BusinessUtil.createNullData(size, req.getPageNo(), req.getPageSize(), policemanDto);
            collect.addAll(nullData);
        }
        Page<PolicemanDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(collect);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }


    //根据单警柜id查询警员信息(list)
    @Override
    public List<PolicemanDto> GetPoliceData(CabinetReq req) {
        //判断单警柜id是否正确
        Cabinet cabinet = cabinetService.CabinetExist(req.getId());
        PubOrg pubOrg = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>()
                        .eq(PubOrg::getOrgId, cabinet.getOrgIdInt()));
        //通过箱门id查询出警员
        List<Policeman> policemenList = policemanMapper.SearchPoliceList(req.getId());
        List<PolicemanDto> list = new ArrayList<>();
        for (Policeman policeman : policemenList) {
            PolicemanDto policemanDto = new PolicemanDto();
            BeanPlusUtil.copyProperties(policeman, policemanDto);
            //指纹信息查找
            List<PoliceFinger> fingerList = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>()
                    .eq(PoliceFinger::getPoliceId, policeman.getId()));
            List<PoliceFingerDto> fingerDtoList = new ArrayList<>();
            for (PoliceFinger policeFinger : fingerList) {
                PoliceFingerDto policeFingerDto = new PoliceFingerDto();
                BeanPlusUtil.copyProperties(policeFinger, policeFingerDto);
                fingerDtoList.add(policeFingerDto);
            }
            policemanDto.setFingersList(fingerDtoList);
            policemanDto.setOrgName(pubOrg.getOrgName());
            list.add(policemanDto);
        }
        return list;
    }


    //根据单警柜id查询警员信息(page)
    @Override
    public PageResult<PolicemanDto> GetPoliceDataPage(CabinetReq req) {
        //判断单警柜id是否正确
        Cabinet cabinet = cabinetService.CabinetExist(req.getId());
        PubOrg pubOrg = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>()
                .eq(PubOrg::getOrgId, cabinet.getOrgIdInt()));
        //通过箱门id查询出警员
        Page<Policeman> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        long size = policemanMapper.SearchPoliceSize(req.getId());
        IPage<Policeman> policemenList = policemanMapper.SearchPolicePage(page,req.getId());
        List<PolicemanDto> list = new ArrayList<>();
        CabinetDto cabinetDto = new CabinetDto();
        BeanPlusUtil.copyProperties(cabinet,cabinetDto);
        for (Policeman policeman : policemenList.getRecords()) {
            PolicemanDto policemanDto = new PolicemanDto();
            BeanPlusUtil.copyProperties(policeman, policemanDto);
            //指纹信息查找
            List<PoliceFinger> fingerList = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>()
                    .eq(PoliceFinger::getPoliceId, policeman.getId()));
            List<PoliceFingerDto> fingerDtoList = new ArrayList<>();
            for (PoliceFinger policeFinger : fingerList) {
                PoliceFingerDto policeFingerDto = new PoliceFingerDto();
                BeanPlusUtil.copyProperties(policeFinger, policeFingerDto);
                fingerDtoList.add(policeFingerDto);
            }
            policemanDto.setFingersList(fingerDtoList);
            policemanDto.setCabinetInfo(cabinetDto);
            policemanDto.setOrgName(pubOrg.getOrgName());
            list.add(policemanDto);
        }
        Page<PolicemanDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(list);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }

    //添加人脸信息
    @Override
    public CabinetPoliceDto AddFaceInfo(CabinetPolicemanReq req) {
        Policeman police = PoliceExist(req.getStaffId());
        police.setFaceInfo(req.getFaceInfo());
        police.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        updateById(police);
        PubOrg orgInfo = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        updateOrgAndSendMessage(orgInfo,req.getCabinetOrgCode(),req.getDevSn());
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",5,"Updating policemanInfo:"+police.getName(),
                null,null,new ArrayList<>(),null,null);
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(police,cabinetPoliceDto);
        return cabinetPoliceDto;
    }

    /**
     * @param
     * @return
     * @author lxh
     * @description 更新人脸信息\删除人脸信息
     * 删除时：传一个null的人脸信息即可
     * @since 2023/7/18 15:02
     **/
    @Override
    public CabinetPoliceDto UpdateFaceInfo(CabinetPolicemanReq req) {
        Policeman police = PoliceExist(req.getStaffId());
        police.setFaceInfo(ObjectUtil.isNotEmpty(req.getFaceInfo())?req.getFaceInfo():null);
        police.setPhoto(ObjectUtil.isNotEmpty(req.getPhoto())?req.getPhoto():null);
        police.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        police.setUserLocalId(req.getUserLocalId());
        updateById(police);
        PubOrg orgInfo = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        updateOrgAndSendMessage(orgInfo,req.getCabinetOrgCode(),req.getDevSn());
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",orgInfo.getOrgId().toString(),"InfoChange",5,"Updating policemanInfo:"+police.getName(),
                null,null,new ArrayList<>(),null,null);
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(police,cabinetPoliceDto);
        return cabinetPoliceDto;

    }

    /**
     * @param
     * @return
     * @author lxh
     * @description 查询人脸信息
     * @since 2023/7/18 15:02
     **/
    @Override
    public Policeman SearchFaceInfo(CabinetPolicemanReq req) {
        Policeman policeman = PoliceExist(req.getStaffId());
        return policeman;

    }




    //人员绑定箱门
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean PoliceBindBox(PolicemanReq req) {
        Policeman policeman = PoliceExist(req.getId());

        CabinetBox cabinetBox = new CabinetBox();
        //判断该警员是否是调入的警员，如果是调入警员，那么查询log表中是否有记录，如果有记录表示他携带装备
        List<OrderLog> list = orderLogService.list(new LambdaQueryWrapper<OrderLog>()
                .eq(OrderLog::getOrgId, req.getOrgId())
                .eq(OrderLog::getOrderType, policeman.getName() + policeman.getPoliceCode())
                .eq(OrderLog::getBussinessType,"updateInvSum")
                .orderByDesc(OrderLog::getCreateTime));
        List<PoliceEquipment> policeEqsList=new ArrayList<>();
        List<PoliceEquipmentDetail> policeEqsDetailList=new ArrayList<>();
        String locationId="";
        OrderLog orderLog=new OrderLog();
        orderLog = null;
        if (list.size()<=0){
            policeEqsList= policeEquipmentService.list(new LambdaQueryWrapper<PoliceEquipment>()
                    .eq(PoliceEquipment::getPoliceId, policeman.getId()));
            policeEqsDetailList=policeEquipmentDetailService.list(new LambdaQueryWrapper<PoliceEquipmentDetail>()
                    .eq(PoliceEquipmentDetail::getPoliceId, policeman.getId()));
        }
        List<Object[]> searchItem=new ArrayList<>();
        //判断调岗警员是否已经绑定了箱门
        List<CabinetBoxPolice> list1 = cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>()
                .eq(CabinetBoxPolice::getPoliceId, policeman.getId()));

        //判断箱门是否存在
        boolean result=true;
        //判断是否需要添加汇总信息标识
        boolean flag=false;
        List<String> boxList = req.getBoxList();
        if (boxList.size()>0){

            //根据警员id和箱门id绑定公共柜
            List<CabinetBoxPolice> cabinetBoxPoliceList=new ArrayList<>();

            //将箱门全部清除
            cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, req.getId()));

            //公共柜和单警柜一起批量绑定
            for (String boxId:boxList ) {
                CabinetBoxPolice cabinetBoxPolice = new CabinetBoxPolice();
                cabinetBoxPolice.setPoliceId(req.getId());
//                cabinetBoxPolice.setCabinetId(boxReq.getCabinetId());
                cabinetBoxPolice.setCabinetBoxId(boxId);
                cabinetBoxPolice.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                cabinetBoxPolice.setCabinetName(boxReq.getCabinetName());
//                cabinetBoxPolice.setNum(boxReq.getNum());
//                cabinetBoxPolice.setContainType(boxReq.getContainType());
                cabinetBoxPoliceList.add(cabinetBoxPolice);

                //调岗警员绑定第一个单警柜以后，不管之后他是否还有单警柜，我都默认是不绑了。
                // 判断他下面是否有箱门，如果有则表示他已经帮过单警柜并且调岗携带的装备都已经记录过，那么将不再被记录
                if (orderLog==null && list1.size()==0 && !flag ){
                    flag=true;

                    cabinetBox = cabinetBoxService.getById(boxId);
                    for (PoliceEquipment equipment:policeEqsList) {
                        equipment.setLocationId(boxId);
                        equipment.setOrgId(req.getOrgId());
                        Object[] item=new Object[]{req.getOrgId(),cabinetBox.getCabinetId(),equipment.getTypeId(),equipment.getSizeId(),equipment.getPrice()};
                        searchItem.add(item);
                    }
                    policeEquipmentService.updateBatchById(policeEqsList);
                    List<String> epcList = policeEqsDetailList.stream().map(PoliceEquipmentDetail::getEpc).collect(Collectors.toList());
                    //将locationId设置进去
                    inventoryService.update(new LambdaUpdateWrapper<Inventory>().set(Inventory::getLocationId,boxId)
                            .set(Inventory::getBussinessState,"normal")
                            .set(Inventory::getLocationState,"in")
                            .set(Inventory::getLocationType,1)
                            .isNull(Inventory::getLocationId)
                            .in(CollectionUtil.isNotEmpty(epcList),Inventory::getEpc,epcList));
                    warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>()
                            .set(WarehouseInventory::getLocationId,boxId)
                            .set(WarehouseInventory::getLocationState,"in")
                            .set(WarehouseInventory::getLocationType,1)
                            .isNull(WarehouseInventory::getLocationId)
                            .in(CollectionUtil.isNotEmpty(epcList),WarehouseInventory::getEpc,epcList));
                    policeEqsDetailList.forEach(s->{s.setOrgId(req.getOrgId().toString());s.setLocationId(boxId);});
                    policeEquipmentDetailService.updateBatchById(policeEqsDetailList);
                }
            }
            if (cabinetBoxPoliceList.size()>0){
                result = cabinetBoxPoliceService.saveBatch(cabinetBoxPoliceList);
            }
        }else {
            if (CollectionUtil.isNotEmpty(list1)){
                result = cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, req.getId()));
            }

        }

        //判断summary表中是否有数据，如果有，summary表直接更新数据，如果summary表没有，那么直接新增一条数据
        if (flag){
            boolean b = updateSumDataAndLog(req.getOrgId(), cabinetBox, policeEqsList, searchItem);
        }
        //还需要绑定箱门推送过去
        if (Objects.equals(policeman.getOrgId(), JYZBConstant.ORG_ID_PRODUCTION)){
            //调用半山项目的接口
            try {
                //将半山的柜子的绑定关系发送过去，别的箱门别管
                List<String> kfBoxList=new ArrayList<>();
                if (CollectionUtil.isNotEmpty(boxList)){
                    kfBoxList=cabinetBoxMapper.getkfBoxList(boxList, policeman.getOrgId());
                }
                SendBoxBindPoliceDto sendBoxBindPoliceDto = new SendBoxBindPoliceDto();
                sendBoxBindPoliceDto.setUserId(policeman.getUserId());
                sendBoxBindPoliceDto.setBoxList(kfBoxList);
                sendBoxBindPoliceDto.setPushFlag(false);
                sendInfoApi.sendBoxBindPoliceInfo(KfExpander.sendBoxBindPoliceInfo(),sendBoxBindPoliceDto);
            } catch (Exception e) {
                System.out.println("推送箱门绑定信息失败" );
            }
        }
        return result;
    }

    /**
     * 人员绑定箱门（单警柜）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public CabinetPoliceDto PoliceBindBoxFormCab(CabinetPolicemanReq req) {
        Policeman policeman = PoliceExist(req.getStaffId());

        policeman.setUserLocalId(req.getUserLocalId());
        policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        updateById(policeman);
        List<CabinetBoxPolice> list1 = cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>()
                .eq(CabinetBoxPolice::getPoliceId, policeman.getId()));

        //判断箱门是否存在
        boolean result=true;
        //判断是否需要添加汇总信息标识
        if (CollectionUtil.isNotEmpty(req.getBoxList())){

            //根据警员id和箱门id绑定公共柜
            List<CabinetBoxPolice> cabinetBoxPoliceList=new ArrayList<>();
            List<String> boxList = req.getBoxList().stream().map(UpdateCabinetBoxReq::getId).collect(Collectors.toList());

            //将箱门全部清除
            cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, req.getStaffId()));

            //公共柜和单警柜一起批量绑定
            for (String boxId:boxList ) {
                CabinetBoxPolice cabinetBoxPolice = new CabinetBoxPolice();
                cabinetBoxPolice.setPoliceId(req.getStaffId());
                cabinetBoxPolice.setCabinetBoxId(boxId);
                cabinetBoxPolice.setCreateTime(DateTimeUtil.getCurrentDateTime());
                cabinetBoxPolice.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                cabinetBoxPoliceList.add(cabinetBoxPolice);


            }
            if (cabinetBoxPoliceList.size()>0){
                result = cabinetBoxPoliceService.saveBatch(cabinetBoxPoliceList);
            }
        }else {
            if (CollectionUtil.isNotEmpty(list1)){
                result = cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, req.getStaffId()));
            }

        }
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(policeman,cabinetPoliceDto);

        return cabinetPoliceDto;
    }

    /**
     * 查询没有组织机构的警员信息
     * @return
     */
    @Override
    public PageResult<Policeman> GetPoliceWithoutOrgPage(UpdatePolicemanReq req) {
        List<Policeman> policemanList=policemanMapper.searchPoliceWithoutOrg(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        int size=policemanMapper.searchPoliceWithoutOrgCount(req);
        List<Policeman> collect = policemanList.stream()
                .peek(policeman -> {
                    List<PoliceEquipment> list1 = policeEquipmentService.list(
                            new LambdaQueryWrapper<PoliceEquipment>().eq(PoliceEquipment::getPoliceId, policeman.getId()));
                    policeman.setPoliceEquipmentList(list1);
                }).collect(Collectors.toList());
        Page<Policeman> page=PageFactory.getDefaultPage(req.getPageNo(),req.getPageSize());
        page.setTotal(size);
        page.setRecords(collect);
        return PageResultFactory.createPageResult(page);
    }

    //人员解绑箱门
    @Override
    @Transactional
    public boolean PoliceUnBindBox(PolicemanReq req) {
        //判断传递的警员id是否存在，判断传递的箱门id是否绑定在该警员下面
        Policeman policeman = PoliceExist(req.getId());
        List<CabinetBoxPolice> list = cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>()
                .eq(CabinetBoxPolice::getPoliceId, policeman.getId()));
        List<CabinetBoxPolice> delList=new ArrayList<>();
        if (req.getBoxList().size()>0) {
            for (CabinetBoxPolice boxPolice:list) {
                for (String boxId:req.getBoxList()) {
                    if (boxId.equals(boxPolice.getCabinetBoxId())){
                        delList.add(boxPolice);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(delList)){
            cabinetBoxPoliceService.removeBatchByIds(delList);
        }
        //人员与箱门装备表是否存在绑定关系，如果存在，那么进行解绑操作
//        List<PoliceEquipmentDetail> eqsPoliceList = policeEquipmentDetailService.list(new LambdaQueryWrapper<PoliceEquipmentDetail>()
//                .eq(PoliceEquipmentDetail::getPoliceId, policeman.getId()));
//        if (eqsPoliceList.size()>0){
//            for (PoliceEquipmentDetail policeEqsDetail:eqsPoliceList) {
//                for (String boxId:req.getBoxList()) {
//                    if (boxId.equals(policeEqsDetail.getLocationId())){
//                        policeEqsDetail.setPoliceId(null);
//                    }
//                }
//            }
//            policeEquipmentDetailService.updateBatchById(eqsPoliceList);
//        }
        return true;
    }



    //添加调岗第一次调入人员绑定箱门时修改装备汇总表的信息以及记录日志
    private boolean updateSumDataAndLog(Long orgId,CabinetBox cabinetbox,List<PoliceEquipment> policeEqsList,List<Object[]> searchItem){
        PubOrg pubOrg = pubOrgService.PubOrgExist(orgId);
        Cabinet cabinet = cabinetService.CabinetExist(cabinetbox.getCabinetId());
        StringBuilder stringBuilder = new StringBuilder();
        //将警员调岗携带的装备进行查询出来，并对summary表进行计算
        if (CollectionUtil.isNotEmpty(searchItem)) {


            List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
            List<InventorySummary> addSumList = new ArrayList<>();
            if (inventorySummaryList.size() > 0) {
                for (PoliceEquipment equipment : policeEqsList) {
                    boolean a = false;
                    //找到库存汇总
                    for (InventorySummary is : inventorySummaryList) {
                        if (equipment.getTypeId().equals(is.getTypeId())
                                && equipment.getSizeId().equals(is.getSizeId())
                                && equipment.getPrice().compareTo(is.getUnitPrice()) == 0) {
                            a = true;
                            Integer totalNum = is.getNumber() + equipment.getNum();
                            stringBuilder.append(cabinet.getName() + "下的" + equipment.getTypeName() + "【" + equipment.getSizeName() + "】装备的在柜数量：" + is.getStockNumber() + "改成" + totalNum + "，并且修改了价格和总数；");
                            is.setNumber(totalNum);
                            is.setPrice(is.getPrice().add(equipment.getPrice().multiply(BigDecimal.valueOf(equipment.getNum()))));
                            is.setStockNumber(is.getStockNumber() + equipment.getNum());
                            break;
                        }
                    }
                    //没找到，直接新增
                    if (!a) {
                        stringBuilder.append(cabinet.getName() + "新增装备" + equipment.getTypeName() + "【" + equipment.getSizeName() + "】，在柜数量：" + equipment.getNum() + "，并且修改了价格和总数；");
                        InventorySummary inventorySummary = inventorySummaryService.createInventorySummary(pubOrg.getOrgId(),pubOrg.getOrgName(),
                                pubOrg.getOrgCode(),equipment.getTypeId(),equipment.getTypeName(),equipment.getSizeId(),
                                equipment.getSizeName(),cabinet.getId(),cabinet.getName(),equipment.getNum(),0,
                                equipment.getPrice(),0,0,0,0,0,0,0,"0");
                        addSumList.add(inventorySummary);
                    }

                }
            } else {
                for (PoliceEquipment equipment : policeEqsList) {
                    stringBuilder.append(cabinet.getName() + "新增装备" + equipment.getTypeName() + "【" + equipment.getSizeName() + "】，在柜数量：" + equipment.getNum() + "，并且修改了价格和总数；");
                    InventorySummary inventorySummary = inventorySummaryService.createInventorySummary(pubOrg.getOrgId(),pubOrg.getOrgName(),
                            pubOrg.getOrgCode(),equipment.getTypeId(),equipment.getTypeName(),equipment.getSizeId(),
                            equipment.getSizeName(),cabinet.getId(),cabinet.getName(),equipment.getNum(),0,
                            equipment.getPrice(),0,0,0,0,0,0,0,"0");
                    addSumList.add(inventorySummary);
                }
            }

            if (addSumList.size()>0){
                inventorySummaryService.saveBatch(addSumList);
            }

            if (inventorySummaryList.size()>0){
                inventorySummaryService.updateBatchById(inventorySummaryList);
            }

        }
        //记录日志
        OrderLog orderLog1 = new OrderLog();
        orderLog1.setBussinessType("调入警员修改库存汇总");
        orderLog1.setProcessType("updateInvSum");
        String string = stringBuilder.toString();
        if (ObjectUtil.isNotEmpty(string)){
            string=string.substring(0,string.length()-1);
        }
        orderLog1.setHistoryMsg(string);
        orderLog1.setOrgId(pubOrg.getOrgId());
        orderLog1.setOrgName(pubOrg.getOrgName());
        orderLog1.setCreateTime(DateTimeUtil.getCurrentDateTime());
        boolean c = orderLogService.save(orderLog1);
        return true;
    }


    /**
     * 通过警员id判断警员是否存在，不存在则抛出异常
     */
    @Override
    public Policeman PoliceExist(String policeId) {
        Policeman policeman = getById(policeId);
        if (ObjectUtil.isNull(policeman)) {
            throw new ServiceException(PolicemanExceptionEnum.POLICEMAN_NOT_EXIST);
        }
        return policeman;
    }

    //删除账号时同时对警员的信息进行更改操作
    @Override
    public boolean UpdatePoliceInfo(UserOrgReq req) {
        Policeman police = getOne(new LambdaQueryWrapper<Policeman>().eq(Policeman::getUserId,req.getUserId()));
        if (ObjectUtil.isNull(police)) {
            //如果查询不到，表示该账号不是警员的，直接删除就行，不需要做任何操作
            return true;
        }
        police.setUserId(null);
        police.setPassword(null);
        return updateById(police);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changePoliceOrg(UpdateReassignmentReq req) {
        //通过警员id查询出该警员的基本信息
        Policeman policeman = getById(req.getPoliceId());
        StringBuilder stringBuilder = new StringBuilder();
        Integer inventoryQuantity=0;
        Integer actualQuantity=0;
        List<PoliceEquipment> reqEquipments = JSON.parseArray(req.getDetailList(), PoliceEquipment.class);
        //查询出该警员的所有装备信息
        LambdaQueryWrapper<PoliceEquipment> eq = new LambdaQueryWrapper<PoliceEquipment>()
                .eq(PoliceEquipment::getPoliceId, policeman.getId());
        //查询该警员是否存在装备信息，如果存在则进行删除
        List<PoliceEquipment> list1 = policeEquipmentService.list(eq);
        //判断是调入单还是调出单
        //0是调入警员，1是调出警员
        //assign是调入
        if(req.getReassignmentType().equals("assign")){
            //添加账号和组织机构的绑定关系
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setOrgId(req.getOrgId());
            sysUserOrg.setUserId(policeman.getUserId());
            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrgService.save(sysUserOrg);
            //将警员中的组织机构id设置
            policeman.setOrgId(req.getOrgId());
            policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            //将组织机构的guid也进行修改
            PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
            policeman.setOrgGuid(pubOrg.getGuid());
            policeman.setState(1);
            //如果调入的警员携带装备,那么我应该怎么处理呢

            stringBuilder.append("警员:"+req.getPoliceName()+",警号为："+req.getPoliceCode()+",因调岗携带以下装备:");
            if(CollectionUtil.isNotEmpty(reqEquipments)){
                for (PoliceEquipment equipment:reqEquipments) {
                    stringBuilder.append(equipment.getTypeName()+
                            "【"+equipment.getSizeName()+"】，数量为:"+equipment.getNum()+"\n");
                    inventoryQuantity+=equipment.getNum();
                    actualQuantity+=equipment.getNum();

                }


            }
            if (CollectionUtil.isNotEmpty(list1)){
                for (PoliceEquipment pe:list1) {
                    pe.setOrgId(req.getOrgId());
                }
                policeEquipmentService.updateBatchById(list1);
            }

        }
        //reassign是调出
        else if (req.getReassignmentType().equals("reassign")){
            //将其组织机构号设为空

            PubOrg pubOrg = pubOrgService.getById(policeman.getOrgId());
            policeman.setOrgGuid(pubOrg.getGuid());
            policeman.setOrgId(null);
            policeman.setState(2);
            policeman.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            //将账号与组织机构关联表进行删除
            sysUserOrgService.remove(new LambdaQueryWrapper<SysUserOrg>().eq(SysUserOrg::getUserId,policeman.getUserId()));

            //箱门进行解绑删除
            cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>()
                    .eq(CabinetBoxPolice::getPoliceId,policeman.getId()));
            //拿到警员绑定的装备详情，根据具体epc进行设置orgId和locationId为空

            //判断前端传递的装备列表字段是否为空，如果为空则表示该警员不拿走任何装备信息(不做任何操作)
            if (ObjectUtil.isNotEmpty(req.getDetailList()) || !req.getDetailList().trim().isEmpty()){

                //将该警员拿走的装备的组织机构设置为空，并且其他装备进行跟警员进行解绑删除
                List<PoliceEquipment> removeList=new ArrayList<>();
                //更新装备（将装备信息进行删除）
                List<PoliceEquipment> updateList=new ArrayList<>();

                stringBuilder.append(req.getOrgName()+"的警员"+req.getPoliceName()+
                        "，警号为："+req.getPoliceCode()+"，因调岗拿走以下装备:");
                for (PoliceEquipment policeEquipment:list1) {//库中存在装备
                    boolean flag=false;
                    for (PoliceEquipment one:reqEquipments) {//传递装备
                        if (policeEquipment.getSizeId().equals(one.getSizeId())
                                && policeEquipment.getTypeId().equals(one.getTypeId())){

                            stringBuilder.append(policeEquipment.getTypeName()+"【"+policeEquipment.getSizeName()+
                                    "】，原数量:"+policeEquipment.getNum()+"，取走:"+one.getNum()+"，剩余："+(policeEquipment.getNum()-one.getNum())+"\n");
                            inventoryQuantity+=policeEquipment.getNum();
                            actualQuantity+=one.getNum();
                            policeEquipment.setNum(one.getNum());
                            policeEquipment.setOrgId(null);
                            policeEquipment.setLocationId(null);
//                            policeEquipment.setStorageLocation(null);
                            updateList.add(policeEquipment);
                            flag=true;
                            break;
                        }
                    }
                    if (!flag){
                        removeList.add(policeEquipment);
                    }
                }
                policeEquipmentService.updateBatchById(updateList);
                policeEquipmentService.removeBatchByIds(removeList);

//                List<Object[]> searchItem=new ArrayList<>();
//                if(CollectionUtil.isNotEmpty(reqEquipments)){
//                    for (PoliceEquipment equipment:reqEquipments) {
//                        stringBuilder.append(equipment.getTypeName()+
//                                "【"+equipment.getSizeName()+"】，数量为:"+equipment.getNum()+"\n");
//                        inventoryQuantity+=equipment.getNum();
//                        actualQuantity+=equipment.getNum();
//                        Object[] item=new Object[]{equipment.getOrgId(),equipment.getLocationId(),equipment.getTypeId(),
//                                equipment.getSizeId(),equipment.getPrice(),0,equipment.getNum()};
//                        searchItem.add(item);
//
//                    }
//                    List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(searchItem);
//                    for (InventorySummary is:inventorySummaryList) {
//                        for (Object[] obj:searchItem) {
//                            if (obj[1].equals(is.getLocationId())&& obj[2].equals(is.getTypeId())
//                                    && obj[3].equals(is.getSizeId()) && is.getUnitPrice().compareTo((BigDecimal) obj[4])==0){
//                                //需要判断位置是在单警柜还是在仓库下面，如果在仓库下面，那么数量应该减去仓库的出库数量，
//                                // 如果是在单警柜下面，那么数量应该减去单警柜的在库数量
//                                if (is.getLocationType().equals("0")){
//                                    is.setOutboundNumber(is.getOutboundNumber()-(Integer) obj[6]);
//                                    is.setNumber(is.getNumber()-(Integer) obj[6]);
//                                    is.setOutboundNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getOutboundNumber())));
//                                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                                }else{
//                                    is.setStockNumber(is.getStockNumber()-(Integer) obj[6]);
//                                    is.setNumber(is.getNumber()-(Integer) obj[6]);
//                                    is.setStockNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getStockNumber())));
//                                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                                }
//                                break;
//                            }
//                        }
//                    }
//                    inventorySummaryService.updateBatchById(inventorySummaryList);
//
//                }

            }

        }
        //记录日志(如果警员携带装备,则进行记录 )
        OrderLog orderLog = new OrderLog();
        String string = stringBuilder.toString();
        string=string.substring(0,string.length()-1);
        orderLog.setHistoryMsg(string);
        orderLog.setOrgId(req.getOrgId());
        //特殊记号，警员+警员编号
        orderLog.setOrderType(req.getPoliceName()+req.getPoliceCode());
        orderLog.setBussinessType(req.getReassignmentType());
        orderLog.setProcessType(req.getReassignmentType());
        orderLog.setOrderCode(req.getOrderCode());
        orderLog.setOrderId(req.getId());
        orderLog.setOrgName(req.getOrgName());
        orderLog.setInventoryQuantity(inventoryQuantity);
        orderLog.setActualQuantity(actualQuantity);
        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
        orderLogService.save(orderLog);


        return updateById(policeman);
    }
    //警员调岗
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean changePoliceOrg(UpdateReassignmentReq req) {
//        //通过警员id查询出该警员的基本信息
//        Policeman policeman = getById(req.getPoliceId());
//
//        StringBuilder stringBuilder = new StringBuilder();
//        Integer inventoryQuantity=0;
//        Integer actualQuantity=0;
//        List<PoliceEquipment> reqEquipments = JSON.parseArray(req.getDetailList(), PoliceEquipment.class);
//        //查询出该警员的所有装备信息
//        LambdaQueryWrapper<PoliceEquipment> eq = new LambdaQueryWrapper<PoliceEquipment>()
//                .eq(PoliceEquipment::getPoliceId, policeman.getId());
//        //查询该警员是否存在装备信息，如果存在则进行删除
//        List<PoliceEquipment> list1 = policeEquipmentService.list(eq);
//        //判断是调入单还是调出单
//        //0是调入警员，1是调出警员
//        //assign是调入
//        if(req.getReassignmentType().equals("assign")){
//            //添加账号和组织机构的绑定关系
//            SysUserOrg sysUserOrg = new SysUserOrg();
//            sysUserOrg.setOrgId(req.getOrgId());
//            sysUserOrg.setUserId(policeman.getUserId());
//            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
//            sysUserOrgService.save(sysUserOrg);
//            //将警员中的组织机构id设置
//            policeman.setOrgId(req.getOrgId());
//            policeman.setState(1);
//            //如果调入的警员携带装备,那么我应该怎么处理呢
//
//            stringBuilder.append("警员:"+req.getPoliceName()+",警号为："+req.getPoliceCode()+",因调岗携带以下装备:");
//            if(CollectionUtil.isNotEmpty(reqEquipments)){
//                for (PoliceEquipment equipment:reqEquipments) {
//                    stringBuilder.append(equipment.getTypeName()+
//                            "【"+equipment.getSizeName()+"】，数量为:"+equipment.getNum()+"\n");
//                    inventoryQuantity+=equipment.getNum();
//                    actualQuantity+=equipment.getNum();
//
//                }
//
//
//            }
//            if (CollectionUtil.isNotEmpty(list1)){
//                for (PoliceEquipment pe:list1) {
//                    pe.setOrgId(req.getOrgId());
//                }
//                policeEquipmentService.updateBatchById(list1);
//            }
//
//
//        }
//        //reassign是调出
//        else if (req.getReassignmentType().equals("reassign")){
//            //将其组织机构号设为空
//            policeman.setOrgId(null);
//            policeman.setState(2);
//            //将账号与组织机构关联表进行删除
//            sysUserOrgService.remove(new LambdaQueryWrapper<SysUserOrg>().eq(SysUserOrg::getUserId,policeman.getUserId()));
//
//            //箱门进行解绑删除
//            cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>()
//                    .eq(CabinetBoxPolice::getPoliceId,policeman.getId()));
//            //拿到警员绑定的装备详情，根据具体epc进行设置orgId和locationId为空
////            List<PoliceEquipmentDetail> EqsDetaillist = policeEquipmentDetailService.list(new LambdaQueryWrapper<PoliceEquipmentDetail>()
////                    .eq(PoliceEquipmentDetail::getPoliceId, policeman.getId())
////                    .groupBy(PoliceEquipmentDetail::getTypeId,PoliceEquipmentDetail::getSizeId,PoliceEquipmentDetail::getPrice));
//            //判断前端传递的装备列表字段是否为空，如果为空则表示该警员不拿走任何装备信息(不做任何操作)
//            if (ObjectUtil.isNotNull(req.getDetailList()) || !req.getDetailList().trim().isEmpty()){
//
//                //将该警员拿走的装备的组织机构设置为空，并且其他装备进行跟警员进行解绑删除
//                List<PoliceEquipment> removeList=new ArrayList<>();
//                //更新装备（将装备信息进行删除）
//                List<PoliceEquipment> updateList=new ArrayList<>();
//
//                stringBuilder.append(req.getOrgName()+"的警员"+req.getPoliceName()+
//                        "，警号为："+req.getPoliceCode()+"，因调岗拿走以下装备:");
//                for (PoliceEquipment policeEquipment:list1) {//库中存在装备
//                    boolean flag=false;
//                    for (PoliceEquipment one:reqEquipments) {//传递装备
//                        if (policeEquipment.getSizeId().equals(one.getSizeId())
//                                && policeEquipment.getTypeId().equals(one.getTypeId())){
//
//                            stringBuilder.append(policeEquipment.getTypeName()+"【"+policeEquipment.getSizeName()+
//                                    "】，原数量:"+policeEquipment.getNum()+"，取走:"+one.getNum()+"，剩余："+(policeEquipment.getNum()-one.getNum())+"\n");
//                            inventoryQuantity+=policeEquipment.getNum();
//                            actualQuantity+=one.getNum();
//                            policeEquipment.setNum(one.getNum());
//                            policeEquipment.setOrgId(null);
//                            policeEquipment.setLocationId(null);
////                            policeEquipment.setStorageLocation(null);
//                            updateList.add(policeEquipment);
//                            flag=true;
//                            break;
//                        }
//                    }
//                    if (!flag){
//                        removeList.add(policeEquipment);
//                    }
//                }
//                policeEquipmentService.updateBatchById(updateList);
//                policeEquipmentService.removeBatchByIds(removeList);
//
//                List<Object[]> searchItem=new ArrayList<>();
//                if(CollectionUtil.isNotEmpty(reqEquipments)){
//                    for (PoliceEquipment equipment:reqEquipments) {
//                        stringBuilder.append(equipment.getTypeName()+
//                                "【"+equipment.getSizeName()+"】，数量为:"+equipment.getNum()+"\n");
//                        inventoryQuantity+=equipment.getNum();
//                        actualQuantity+=equipment.getNum();
//                        Object[] item=new Object[]{equipment.getOrgId(),equipment.getLocationId(),equipment.getTypeId(),
//                                equipment.getSizeId(),equipment.getPrice(),0,equipment.getNum()};
//                        searchItem.add(item);
//
//                    }
//                    List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(searchItem);
//                    for (InventorySummary is:inventorySummaryList) {
//                        for (Object[] obj:searchItem) {
//                            if (obj[1].equals(is.getLocationId())&& obj[2].equals(is.getTypeId())
//                                    && obj[3].equals(is.getSizeId()) && is.getUnitPrice().compareTo((BigDecimal) obj[4])==0){
//                                //需要判断位置是在单警柜还是在仓库下面，如果在仓库下面，那么数量应该减去仓库的出库数量，
//                                // 如果是在单警柜下面，那么数量应该减去单警柜的在库数量
//                                if (is.getLocationType().equals("0")){
//                                    is.setOutboundNumber(is.getOutboundNumber()-(Integer) obj[5]);
//                                    is.setNumber(is.getNumber()-(Integer) obj[5]);
//                                    is.setOutboundNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getOutboundNumber())));
//                                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                                }else{
//                                    is.setStockNumber(is.getStockNumber()-(Integer) obj[5]);
//                                    is.setNumber(is.getNumber()-(Integer) obj[5]);
//                                    is.setStockNumberPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getStockNumber())));
//                                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                                }
//                                break;
//                            }
//                        }
//                    }
//                    inventorySummaryService.updateBatchById(inventorySummaryList);
//                    //将epc设空（根据具体调岗带走装备数量）
//                }
//
//            }
//
//        }
//        //记录日志(如果警员携带装备,则进行记录 )
//        OrderLog orderLog = new OrderLog();
//        String string = stringBuilder.toString();
//        string=string.substring(0,string.length()-1);
//        orderLog.setHistoryMsg(string);
//        orderLog.setOrgId(req.getOrgId());
//        //特殊记号，警员+警员编号
//        orderLog.setOrderType(req.getPoliceName()+req.getPoliceCode());
//        orderLog.setBussinessType(req.getReassignmentType());
//        orderLog.setProcessType(req.getReassignmentType());
//        orderLog.setOrderCode(req.getOrderCode());
//        orderLog.setOrderId(req.getId());
//        orderLog.setOrgName(req.getOrgName());
//        orderLog.setInventoryQuantity(inventoryQuantity);
//        orderLog.setActualQuantity(actualQuantity);
//        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
//        orderLogService.save(orderLog);
//
//
//        return updateById(policeman);
//    }

    //获取警员下面的装备
    @Override
    public List<PoliceEquipment> GetPoliceEqs(QueryReassignmentReq req) {
        LambdaQueryWrapper<PoliceEquipment> eq = new LambdaQueryWrapper<PoliceEquipment>();

        if (ObjectUtil.isNotNull(req.getPoliceId() )&& ! req.getPoliceId().trim().isEmpty()){
            Policeman policeman = PoliceExist(req.getPoliceId());
            eq.eq(PoliceEquipment::getPoliceId, policeman.getId());
            return policeEquipmentService.list(eq);
        }else {
            if (ObjectUtil.isNotNull(req.getUserId() )&& ! req.getUserId().trim().isEmpty()){
                //(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
                if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                        (req.getOrder().equalsIgnoreCase("desc") || req.getOrder().equalsIgnoreCase("asc"))
                        && ObjectUtil.isNotNull(req.getOrder())&& !req.getOrder().trim().isEmpty()){
                    req.setColumn(req.getColumn().replaceAll("[A-Z]","_$0").toLowerCase());
                    req.setOrder(req.getOrder().toLowerCase());
                }
                Policeman one = getOne(new LambdaQueryWrapper<Policeman>().eq(Policeman::getUserId, req.getUserId()));
                if (ObjectUtil.isNotNull(one)){
                    eq.eq(PoliceEquipment::getPoliceId, one.getId())
                            .eq(ObjectUtil.isNotNull(req.getTypeId()),PoliceEquipment::getTypeId,req.getTypeId())
                            .eq(ObjectUtil.isNotNull(req.getSizeId()),PoliceEquipment::getSizeId,req.getSizeId())
                            .like(ObjectUtil.isNotNull(req.getTypeName()),PoliceEquipment::getTypeName,req.getTypeName())
                            .like(ObjectUtil.isNotNull(req.getSizeName()),PoliceEquipment::getSizeName,req.getSizeName())
                            .last("order by "+req.getColumn()+ " "+req.getOrder());

                    return policeEquipmentService.list(eq);
                }else {
                    return new ArrayList<>();
                }
            }
            else {
                throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
            }

        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePoliceUser() {
        List<Policeman> list = list();
        List<Policeman> policemanList=new ArrayList<>();
        list.forEach(policeman -> {
            //如果警员存在账号，则跳过循环，继续下一条警员的信息
            if (ObjectUtil.isNotNull(policeman.getUserId())){
                return;
            }
            SysUser sysUser= new SysUser();
            sysUser.setPhone(policeman.getPhone());
            sysUser.setTel(policeman.getTel());
            //没有账号，默认是警员的编号
            sysUser.setAccount(policeman.getPoliceCode());
            sysUser.setNickName(policeman.getName());
            sysUser.setRealName(policeman.getName());
            SysUserCreateFactory.fillAddSysUser(sysUser);
            sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
            sysUser.setDelFlag(LogicDelEnum.N.getCode());
            sysUser.setCreateTime(DateTime.now());
            sysUser.setUpdateTime(DateTime.now());
            sysUserService.save(sysUser);
            sysUserOrgService.add(sysUser.getUserId(), policeman.getOrgId(), null);
            policeman.setUserId(sysUser.getUserId());
            policemanList.add(policeman);
        });
        return updateBatchById(policemanList);
    }

    //警员调岗申请
    @Override
    public String PoliceReassignment(UpdateReassignmentReq req) {
        //判断该警员是否已经在审核中，如果是的话，那么则提示报错,存草稿没事，但是一旦发起审核流，则需要进行判断
        //但是审核通过之后该警员应该将审核中的状态改回正常，
        if (ObjectUtil.isNotNull(req.getProcessDefinitionId())){
            List<Reassignment> list = reassignmentService.list(new LambdaQueryWrapper<Reassignment>()
                    .eq(Reassignment::getPoliceId, req.getPoliceId())
                    .eq(Reassignment::getReassignmentType,req.getReassignmentType())
                    .eq(Reassignment::getOrgId, req.getOrgId())
                    .eq(Reassignment::getExamineState,"working")
                    .isNotNull(Reassignment::getProcessId)
                    .orderByDesc(Reassignment::getCreateTime));
            if (list.size()>0){
                throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_IN_EXAMINE);
            }
        }

        Reassignment reassignment1=null;
        if (ObjectUtil.isNotNull(req.getId()) && !req.getId().trim().isEmpty()){
            reassignment1 = reassignmentService.getById(req.getId());
        }
        if (reassignment1!=null){

            //判断该单据是否可以进行修改(如果审核中则不允许修改)\
            if (ObjectUtil.isNotNull(reassignment1.getExamineState()) && reassignment1.getExamineState().equals("working")){
                throw new ServiceException(OrderExceptionEnum.ORDER_CAN_NOT_UPDATE);
            }
        }
        //判断是否有工作流id，如果有则将状态进行修改
        if (ObjectUtil.isEmpty(req.getProcessDefinitionId())) {
            req.setExamineState("none");
        } else {
            req.setExamineState("working");
        }

        Reassignment reassignment = new Reassignment();
        BeanPlusUtil.copyProperties(req,reassignment);

        //先判断该单据id是否存在，如果存在，进行更新操作即可
        if (ObjectUtil.isNotNull(req.getId()) && ! req.getId().trim().isEmpty() && ObjectUtil.isNull(req.getProcessDefinitionId())){
            reassignment.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            reassignmentService.updateById(reassignment);
            return reassignment.getId();
        }
        reassignment.setCreateTime(DateTimeUtil.getCurrentDateTime());
        reassignment.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        //如果id是空默认是新建单据，name生成新的单据编号
        if (ObjectUtil.isNull(req.getId()) || req.getId().isEmpty()){
            OrderNum orderNum = busFormService.setOrderCode(req.getBussinessType(), req.getOrgId());
            String codeValue=String.format("%04d",orderNum.getNum());
            long time = new Date().getTime() % 10000;
            reassignment.setOrderCode(orderNum.getBussinessType()+String.format("%04d",time)+orderNum.getYear()+
                    String.format("%02d", LocalDateTime.now().getMonth().getValue())+
                    String.format("%02d",LocalDateTime.now().getDayOfMonth())+codeValue);
            String userIds=searchUserByRoleId(req.getOrgId(), JYZBConstant.SH_ROLR_ID);
            String userId=LoginContext.getContext().getLoginUser().getUserId().toString()+","+userIds;
            reassignment.setHistoryAssign(userId);
            reassignmentService.save(reassignment);
        }
        //执行工作流（如果点击提交接入审核流）
        if (req.getExamineState().equals("working"))
        {
            StartProcessInstanceDTO startProcessInstanceDTO = setParams(req,reassignment);
            String ProcessInstanceId= FlowInstanceService.startProcessInstanceById(startProcessInstanceDTO);
            reassignment.setProcessId(ProcessInstanceId);
            String assigns= FlowInstanceService.GetNextAssign(ProcessInstanceId);//这里需要手动更新审核人信息
            reassignment.setCurrentAssign(assigns);
            reassignmentService.updateById(reassignment);
        }

        String objJson= redisCache.get(reassignment.getProcessId());
        redisCache.remove(reassignment.getProcessId());
        List<MessageSendReq> msgs= JSONObject.parseArray(objJson,MessageSendReq.class);
        if (CollectionUtil.isNotEmpty(msgs)){
            msgs.forEach(msg->
                    {
                        messageApi.sendMessageNoToken(msg);
                    }

            );
        }
        return reassignment.getId();
    }

    @Override
    public boolean delToSubmitReassignment(UpdateReassignmentReq req) {
        Reassignment one = reassignmentService.getById(req.getId());
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(OrderExceptionEnum.ORDER_NOT_EXIST);
        }
        if (!one.getExamineState().equals("none")){
            throw new ServiceException(OrderExceptionEnum.ORDER_DEL_ERROR);
        }
        return reassignmentService.removeById(one.getId());
    }

    private StartProcessInstanceDTO setParams(UpdateReassignmentReq req,Reassignment reassignment){
        StartProcessInstanceDTO startProcessInstanceDTO=new StartProcessInstanceDTO();
        startProcessInstanceDTO.setProcessDefinitionId(req.getProcessDefinitionId());
        startProcessInstanceDTO.setOrderId(reassignment.getId());
        startProcessInstanceDTO.setTypeOrder("reassignment");
        startProcessInstanceDTO.setUserId(req.getUserId());
        startProcessInstanceDTO.setType("reassignmentDto");
        startProcessInstanceDTO.setReassignmentType(req.getReassignmentType());
        Object A= JSON.toJSONString(req, SerializerFeature.WriteDateUseDateFormat);
        JSONObject jsonObject = JSON.parseObject(A.toString());
        startProcessInstanceDTO.setFormData(jsonObject);
        //assign调入，reassign调出
        if (req.getReassignmentType().equals("assign")){
            startProcessInstanceDTO.setStartUserName(req.getPoliceName());
            startProcessInstanceDTO.setEndOrgName(req.getOrgName());
        }else if (req.getReassignmentType().equals("reassign")){
            startProcessInstanceDTO.setEndUserName(req.getPoliceName());
            startProcessInstanceDTO.setStartOrgName(req.getOrgName());
        }
        return startProcessInstanceDTO;
    }

    //查看警员调岗申请单
    @Override
    public PageResult<Reassignment> ShowReassignmentPage(QueryReassignmentReq req) {

        //(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }
        LambdaQueryWrapper<Reassignment> eq = new LambdaQueryWrapper<Reassignment>()
                .eq(ObjectUtil.isNotNull(req.getOrgId()), Reassignment::getOrgId, req.getOrgId())
                .eq(ObjectUtil.isNotNull(req.getReassignmentType()),Reassignment::getReassignmentType,req.getReassignmentType())
                .eq(ObjectUtil.isNotNull(req.getProcessId()),Reassignment::getProcessId,req.getProcessId())
                .like(ObjectUtil.isNotNull(req.getAgent()),Reassignment::getAgent,req.getAgent())
                .like(ObjectUtil.isNotNull(req.getPoliceName()), Reassignment::getPoliceName, req.getPoliceName())
                .like(ObjectUtil.isNotNull(req.getTypeName()),Reassignment::getInvList,req.getTypeName())
                .ge(ObjectUtil.isNotNull(req.getStartTime()), Reassignment::getApplyTime, req.getStartTime())
                .le(ObjectUtil.isNotNull(req.getEndTime()), Reassignment::getApplyTime, req.getEndTime())
                .last("order by " + req.getColumn() + " " + req.getOrder());

        //业务单据审核状态
        if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("unaudited")){

            List<String> examineStateList=new ArrayList<>();
            examineStateList.add("none");
            examineStateList.add("working");
            eq.in( Reassignment::getExamineState,examineStateList);
        } else if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("finished")) {
            List<String> examineStateList=new ArrayList<>();
            examineStateList.add("finished");
            examineStateList.add("refuse");
            eq.in( Reassignment::getExamineState,examineStateList);
        }
        if (ObjectUtil.isNotNull(req.getUserId())){
            eq.and(wrapper -> wrapper.eq(Reassignment::getAgentId,req.getUserId())
                    .or().like(Reassignment::getHistoryAssign,req.getUserId()));
        }else {
            LoginUser loginUser = LoginContext.getContext().getLoginUser();
            eq.and(wrapper -> wrapper.eq(Reassignment::getAgentId,loginUser.getUserId())
                    .or().like(Reassignment::getHistoryAssign,loginUser.getUserId()));
        }
        Page<Reassignment> page = reassignmentService.page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public Reassignment showReassignmentById(QueryReassignmentReq req) {
        Reassignment reassignment = new Reassignment();
        if (ObjectUtil.isNotEmpty(req.getId())){
            reassignment= reassignmentService.getById(req.getId());
        } else if (ObjectUtil.isNotEmpty(req.getProcessId())) {
            reassignment= reassignmentService.getOne(new LambdaQueryWrapper<Reassignment>().eq(Reassignment::getProcessId,req.getProcessId()));
        }
        return reassignment;
    }




    //查询组织机构下的用户以及角色信息(也可以根据别的查询条件查询)
    @Override
    public PageResult<SysUserDto> ShowUserRole(SysUserReq req) {
        Integer numRoles=0;
        if (ObjectUtil.isNotNull(req.getGrantRoleIdList()) && req.getGrantRoleIdList().size() > 0){
            numRoles=req.getGrantRoleIdList().size();
        }
        //查询出所有用户以及用户角色
        List<UserRoleDto> list=policemanMapper.ShowUserRole(req,numRoles);
        //将查询的条件合并（如果一用户有多个角色，那么将该用户的角色id存入列表）
        List<Long> uniqueUsers = new ArrayList<>();
        List<SysUserDto> sysUserDtos=new ArrayList<>();

        for (UserRoleDto userRoleDto : list) {
            // 初始化 uniqueUsers 列表
            if (sysUserDtos.size()==0) {
                SysUserDto sysUserDto = new SysUserDto();
                BeanPlusUtil.copyProperties(userRoleDto,sysUserDto);
                uniqueUsers.add(userRoleDto.getRoleId());
                sysUserDto.setGrantRoleIdList(uniqueUsers);
                sysUserDtos.add(sysUserDto);
                continue;
            }

            boolean foundUser = false;
            for (SysUserDto list1:sysUserDtos) {
                //如果不存在则进行添加，如果已经存在则直接修改角色列表
                if (userRoleDto.getUserId().equals(list1.getUserId())) {
                    uniqueUsers.add(userRoleDto.getRoleId());
                    list1.setGrantRoleIdList(uniqueUsers);
                    foundUser = true;
                    break;
                }
            }
            if (!foundUser){
                SysUserDto sysUserDto = new SysUserDto();
                BeanPlusUtil.copyProperties(userRoleDto, sysUserDto);
                uniqueUsers = new ArrayList<>();
                uniqueUsers.add(userRoleDto.getRoleId());
                sysUserDto.setGrantRoleIdList(uniqueUsers);
                sysUserDtos.add(sysUserDto);
            }
        }
        Page<SysUserDto> page=PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page.setRecords(sysUserDtos);
        page.setTotal(sysUserDtos.size());
        return PageResultFactory.createPageResult(page);
    }

    //获取所有没有组织机构的警员信息
    @Override
    public List<Policeman> GetPoliceWithoutOrg() {
        List<Policeman> list = list(new LambdaQueryWrapper<Policeman>().isNull(Policeman::getOrgId));
        List<Policeman> collect = list.stream()
                .peek(policeman -> {
                    List<PoliceEquipment> list1 = policeEquipmentService.list(
                            new LambdaQueryWrapper<PoliceEquipment>().eq(PoliceEquipment::getPoliceId, policeman.getId()));
                    policeman.setPoliceEquipmentList(list1);
                }).collect(Collectors.toList());
        return collect;
    }


    //查询组织机构为null的警员
    @Override
    public List<PolicemanDto> getPoliceWithoutOrg() {
        List<Policeman> list = list(new LambdaQueryWrapper<Policeman>().isNull(Policeman::getOrgId));
        List<PolicemanDto> collect = list.stream().map(policeman -> {
            PolicemanDto policemanDto = new PolicemanDto();
            BeanPlusUtil.copyProperties(policeman, policemanDto);
            return policemanDto;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UploadPolicePhotoDto uploadPolicePhoto(MultipartFile picture,UploadPolicePhotoReq req) {

        //查询警员表，判断该警员是否已经存在警员照片
        // 如果存在，则查询file表将该数据进行删除，再调用上传文件接口，将返回的文件信息以及地址更新存储到警员表最终返回警员id和照片地址
        // 如果不存在照片，那么直接调用上传文件接口，将照片存储到警员表并且返回警员id和照片地址
        SysFileInfoReq sysFileInfoReq = new SysFileInfoReq();
        String userId="";
        if (ObjectUtil.isNotEmpty(req.getPoliceId())){
            userId=req.getPoliceId();
        }if (ObjectUtil.isNotEmpty(req.getStaffId())){
            userId=req.getStaffId();
        }
        Policeman policeman = getById(userId);
        PubOrg pubOrg = pubOrgService.PubOrgExist(policeman.getOrgId());
        if (ObjectUtil.isNotNull(policeman.getFileId())){
            //删除照片
            sysFileInfoReq.setFileId(policeman.getFileId());
            try {
                this.sysFileInfoService.deleteReally(sysFileInfoReq);
            } catch (Exception var3) {
                throw new ServiceException(PublicExceptionEnum.FILE_DEL_FAILTURE);
            }
        }
        //上传照片
        sysFileInfoReq.setFileBucket("jyzb");
        sysFileInfoReq.setFileLocation(3);
        sysFileInfoReq.setFileObjectName("policePhoto/"+pubOrg.getOrgCode()+"/");
        SysFileInfoResp sysFileInfoResp = sysFileInfoService.uploadFile(picture, sysFileInfoReq);
        policeman.setFileId(sysFileInfoResp.getFileId());
        policeman.setPhoto(sysFileInfoResp.getAccessUrl());
        //更新警员
        updateById(policeman);
        UploadPolicePhotoDto uploadPolicePhotoDto = new UploadPolicePhotoDto();
        uploadPolicePhotoDto.setPoliceId(policeman.getId());
        uploadPolicePhotoDto.setPhoto(policeman.getPhoto());
        return uploadPolicePhotoDto;
    }

    //重置密码
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reSetPassword(SysUserReq req) {
        IStoredEncryptApi storedEncryptApi = (IStoredEncryptApi)SpringUtil.getBean(IStoredEncryptApi.class);
        String defaultPassword = SystemConfigExpander.getDefaultPassWord();
        String password = iStoredEncryptApi.encrypt(defaultPassword);
        SysUserReq sysUserReq=policemanMapper.selectUserById(req.getUserId());
        sysUserService.update(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserId,req.getUserId())
                .set(SysUser::getPassword,password));
        Policeman one = getOne(new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getUserId, req.getUserId()));
        if (ObjectUtil.isNotNull(one)){
            one.setPassword(password);
            updateById(one);
            //那么我直接将消息推送到相应单警柜以及本地主机

            MQ.SendMsg("warehouseMsg",one.getOrgId().toString(),"InfoChange",10,"Updating UserInfo",
                    null,null,new ArrayList<>(),null,null);

        }
        //发送用户修改消息
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",sysUserReq.getOrgId().toString(),"InfoChange",10,"Updating userInfo",
                null,null,new ArrayList<>(),null,null);
        return true;
    }

    //修改密码
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(UpdatePolicemanReq req) {
        IStoredEncryptApi storedEncryptApi = (IStoredEncryptApi) SpringUtil.getBean(IStoredEncryptApi.class);
        Policeman one =getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getId, req.getId()).or().eq(Policeman::getUserId,req.getUserId()));
        //查询用户
        SysUserReq sysUserReq = new SysUserReq();
        if (ObjectUtil.isNotNull(one)){
            //如果不为空则表示修改警员密码
            String newPassword = storedEncryptApi.encrypt(req.getNewPassword());
            //同时修改警员密码
            one.setPassword(newPassword);
            updateById(one);
        }
        sysUserReq=policemanMapper.selectUserById(req.getUserId());
        Long orgId = sysUserReq.getOrgId();
        BeanPlusUtil.copyProperties(req,sysUserReq);
        sysUserReq.setOrgId(orgId);
        sysUserService.editPassword(sysUserReq);

        //警员添加成功之后，往消息队列推送人员更新的消息
        if (ObjectUtil.isNotNull(one)){
            //警员添加成功之后，往消息队列推送人员更新的消息
            MQ.SendMsg("warehouseMsg",one.getOrgId().toString(),"InfoChange",5,"Updating policemanInfo",
                    null,null,new ArrayList<>(),null,null);

        }
        //发送用户修改消息
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",sysUserReq.getOrgId().toString(),"InfoChange",10,"Updating userInfo",
                null,null,new ArrayList<>(),null,null);

        return true;
    }

    //同步警员信息
    @Override
    public List<PoliceDto> alignPoliceInfo(PolicemanReq req) {
        LambdaQueryWrapper<Policeman> eq = new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getOrgId, req.getOrgId())
                .ge(Policeman::getUpdateTime, req.getUpdateTime());
        List<Policeman> list = list(eq);
        int size = list.size();
        List<PoliceDto> returnList=new ArrayList<>();
        List<String> policeIdList = list.stream().map(Policeman::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(policeIdList)){
            List<PoliceFinger> list1 = policeFingerService.list(Wrappers.<PoliceFinger>lambdaQuery().in(PoliceFinger::getPoliceId, policeIdList).isNull(PoliceFinger::getCabFingerNum));
            Map<String, List> map = new HashMap<>();
            for (PoliceFinger pf:list1) {
                PoliceFingerDto policeFingerDto = new PoliceFingerDto();
                BeanPlusUtil.copyProperties(pf, policeFingerDto);
                String policeId = pf.getPoliceId();
                List<PoliceFingerDto> list2 = map.get(policeId);
                if (CollectionUtil.isNotEmpty(list2)){
                    list2.add(policeFingerDto);
                    map.put(policeId,list2);
                } else {
                    List<PoliceFingerDto> list3 = new ArrayList<>();
                    list3.add(policeFingerDto);
                    map.put(policeId,list3);
                }

            }
            for (Policeman p:list) {
                PoliceDto policeDto = new PoliceDto();
                BeanPlusUtil.copyProperties(p, policeDto);
                List<PoliceFingerDto> list2 = map.get(p.getId());
                policeDto.setFingersList(list2);
                returnList.add(policeDto);
            }
        }
        return returnList;
    }

    @Override
    public List<UserDto> alignUserInfo(PolicemanReq req) {
        String date = DateTimeUtil.TimeLongToString(req.getUpdateTime());
        Long orgId = req.getOrgId();
        return policemanMapper.alignUserInfo(orgId,date);
    }


    private Long addUser(SysUser sysUser,String i,PubOrg pubOrg){
        if (i.equals("yw")) {
            sysUser.setNickName(pubOrg.getDName()+"运维人员");
            sysUser.setRealName(pubOrg.getDName()+"运维人员");
        }
        if (i.equals("sh")) {
            sysUser.setNickName(pubOrg.getDName()+"审核员");
            sysUser.setRealName(pubOrg.getDName()+"审核员");
        }
        if (i.equals("gl")) {
            sysUser.setNickName(pubOrg.getDName()+"仓管员");
            sysUser.setRealName(pubOrg.getDName()+"仓管员");
        }

        sysUser.setAccount(i+pubOrg.getOrgCode());
        sysUser.setPassword("123456");
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTimeUtil.getCurrentDateTime());
        sysUser.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        sysUserService.save(sysUser);
        return sysUser.getUserId();
    }
    private SysUser addUserAndReturn(SysUser sysUser,String i,PubOrg pubOrg){
        if (i.equals("yw")) {
            sysUser.setNickName(pubOrg.getDName()+"运维人员");
            sysUser.setRealName(pubOrg.getDName()+"运维人员");
        }
        if (i.equals("sh")) {
            sysUser.setNickName(pubOrg.getDName()+"审核员");
            sysUser.setRealName(pubOrg.getDName()+"审核员");
        }
        if (i.equals("gl")) {
            sysUser.setNickName(pubOrg.getDName()+"仓管员");
            sysUser.setRealName(pubOrg.getDName()+"仓管员");
        }

        sysUser.setAccount(i+pubOrg.getOrgCode());
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTimeUtil.getCurrentDateTime());
        sysUser.setUpdateTime(DateTimeUtil.getCurrentDateTime());

        return sysUser;
    }

    public List<PubOrg> searchAll(Integer pageNum, Integer pageSize ) throws IOException {

        if (pageNum < 0) pageNum = 0;

        SearchRequest request = new SearchRequest("org_pinyin");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.from(pageNum);
        builder.size(pageSize);

        // 添加过滤条件，只获取 delFlag 为 1 的数据
        builder.postFilter(QueryBuilders.termQuery("delFlag", 1));
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        List<PubOrg> pubOrgList = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            PubOrg pubOrg = this.fromMap(sourceAsMap);

            // 添加到结果列表
            pubOrgList.add(pubOrg);
        }

        return pubOrgList;
    }
    public static PubOrg fromMap(Map<String, Object> map) {
        PubOrg pubOrg = new PubOrg();
        BeanPlusUtil.copyProperties(map, pubOrg);
//        pubOrg.setOrgName((String) map.get("orgName"));
        // 可以设置其他字段...
        return pubOrg;
    }

    public boolean CreateSystemAccount( ) throws InterruptedException, IOException {
//        List<PubOrg> orgList = searchAll(0, 3000);

        LambdaQueryWrapper<PubOrg> wp = new LambdaQueryWrapper<>();
        wp.eq( PubOrg::getDelFlag, 1);
        List<PubOrg> listOrg=  pubOrgService.list(wp);
        // 创建线程池
        int numThreads = Runtime.getRuntime().availableProcessors(); // 获取可用处理器数量
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);

        // 提交任务给线程池执行
        for (PubOrg one : listOrg) {
            executor.submit(() -> {
                try {
                    oneClickAccountCreation1(one);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭线程池
        executor.shutdown();

        // 等待所有任务完成
        while (!executor.isTerminated()) {
//            Thread.sleep(1000); // 可以根据需要调整等待时间
        }
        return true;
    }



    private final Lock lock = new ReentrantLock();
//    @Async
//    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean oneClickAccountCreation1(PubOrg pubOrg) throws IOException {
        //一次性创建一个组织机构下的三种系统账号（运维，仓管员，审核员）
        //先判断一下前端是否传递组织机构编号（如果传递，指定创建该组织机构下的三种账号）
        lock.lock(); // 获取锁
        try {
        List<String> userAccountList=new ArrayList<>();
        userAccountList.add("yw");
        userAccountList.add("sh");
        userAccountList.add("gl");
        List<Long> userRoleList=new ArrayList<>();
        userRoleList.add(JYZBConstant.YW_ROLR_ID);
        userRoleList.add(JYZBConstant.SH_ROLR_ID);
        userRoleList.add(JYZBConstant.GL_ROLR_ID);
        List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
        List<SysUserOrg> sysUserOrgList=new ArrayList<>() ;
        List<SysUser> sysUserList=new ArrayList<>();
        SysUser sysUser = new SysUser();
        boolean ywExists = false;
        boolean shExists = false;
        boolean glExists = false;
        if (ObjectUtil.isNull(pubOrg.getOrgCode()) || pubOrg.getOrgCode().trim().isEmpty()){
            //如果没有组织机构编号，需要判断全部组织机构下面是否已经存在对应的账号，如果存在则不创建账号，否则创建指定账号
            //将未被禁用的组织机构全部查询出来
//            List<PubOrg> orgList = pubOrgService.list(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getDelFlag, 1).eq(PubOrg::getStatusFlag, 1));
            List<PubOrg> orgList=searchAll(0, 3000);

            List<UserDto> userDto = policemanMapper.oneClickAccountCreation1(null,userRoleList);
            for (PubOrg one:orgList) {
                Map<String, List<?>> map = addRoleAndOrg(userDto, one, ywExists, shExists,glExists,sysUser,
                        sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
                List<SysUserOrg> userlist=(List<SysUserOrg>)map.get("sysUserOrgList");
                sysUserOrgList.addAll(userlist);
                List<SysUserRole> roleList =(List<SysUserRole>) map.get("sysUserRoleList");
                sysUserRoleList.addAll(roleList);
            }

        }else {
            //如果有组织机构编号，则判断该组织机构下面是否已经存在账号，如果存在，则不进行创建，否则进行创建
            PubOrg one = pubOrgService.list(new LambdaQueryWrapper<PubOrg>()
                    .eq(PubOrg::getOrgCode, pubOrg.getOrgCode())).get(0);
            if (ObjectUtil.isNull(one)){
                throw new ServiceException(PubOrgExceptionEnum.PUBORG_NOT_EXIST);
            }
            List<UserDto> userDtos = policemanMapper.oneClickAccountCreation(one.getOrgId(),null,null,userRoleList);

            if (userDtos.size()==0){
                for (int i = 0; i < userAccountList.size(); i++) {
                    sysUser.setUserId(null);
                    //创建用户信息
                    Long userId = addUser(sysUser, userAccountList.get(i), one);
                    //创建关联表数据
                    SysUserOrg sysUserOrg = new SysUserOrg();
                    sysUserOrg.setOrgId(one.getOrgId());
                    sysUserOrg.setUserId(userId);
                    sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    sysUserOrgList.add(sysUserOrg);
                    //创建角色表数据
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(userRoleList.get(i));
                    sysUserRole.setUserId(userId);
                    sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    sysUserRoleList.add(sysUserRole);

                }

            }else {
                List<String> expectedPrefixes = Arrays.asList("sh", "gl", "yw");
                List<String> foundPrefixes = userDtos.stream()
                        .map(UserDto::getAccount)
                        .map(account -> account.substring(0, 2)) // 获取账户名的前两个字符
                        .filter(expectedPrefixes::contains) // 过滤出符合期望前缀的账户名
                        .distinct() // 去重
                        .collect(Collectors.toList());

                // 找出缺少的前缀
                List<String> missingPrefixes = new ArrayList<>(expectedPrefixes);
                missingPrefixes.removeAll(foundPrefixes);

                // 输出缺少的前缀
                if (!missingPrefixes.isEmpty()) {
                    System.out.println("缺少以下前缀的用户: " + missingPrefixes);
                }



            }

            sysUserOrgService.saveBatch(sysUserOrgList);
            sysUserRoleService.saveBatch(sysUserRoleList);

        }


        }
        finally {
            lock.unlock(); // 释放锁
        }
        return true;
    }


    private Map<String,List<?>> addRoleAndOrg(List<UserDto> userDtos,PubOrg one,Boolean ywExists,Boolean shExists,Boolean glExists,SysUser sysUser,
                                                List<SysUserOrg> sysUserOrgList,List<Long> userRoleList,
                                                List<String> userAccountList,List<SysUserRole> sysUserRoleList){
        Map<String,List<?>> map=new HashMap<>();
        for (UserDto user:userDtos) {
            if (user.getAccount().equals("yw"+one.getOrgCode())){
                ywExists=true;
                continue;
            }
            if (user.getAccount().equals("sh"+one.getOrgCode())){
                shExists=true;
                continue;
            }
            if (user.getAccount().equals("gl"+one.getOrgCode())){
                glExists = true;
                if (ywExists && shExists ){
                    break;
                }
            }

        }

        if (!ywExists){
            sysUser.setUserId(null);
            Long userId = addUser(sysUser, userAccountList.get(0), one);
            //创建关联表数据
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setOrgId(one.getOrgId());
            sysUserOrg.setUserId(userId);
            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(0));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRoleList.add(sysUserRole);
        }
        if (!shExists){
            sysUser.setUserId(null);
            Long userId = addUser(sysUser, userAccountList.get(1), one);
            //创建关联表数据
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setOrgId(one.getOrgId());
            sysUserOrg.setUserId(userId);
            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(1));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRoleList.add(sysUserRole);
        }

        if (!glExists){
            sysUser.setUserId(null);
            Long userId = addUser(sysUser, userAccountList.get(2), one);
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setOrgId(one.getOrgId());
            sysUserOrg.setUserId(userId);
            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(2));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRoleList.add(sysUserRole);
        }
        map.put("sysUserRoleList",sysUserRoleList);
        map.put("sysUserOrgList",sysUserOrgList);
        return map;
    }

    //获取组织机构下所有的指定角色的userId，用字符串拼接
    @Override
    public String searchUserByRoleId(Long orgId,Long roleId) {
        return policemanMapper.searchUserByRoleId(orgId,roleId);
    }

    //一键生成普通警员账号
    @Override
    @Transactional
    public boolean CreateAllUserId() {
        List<Policeman> policemanList=policemanMapper.getAllPolice();
        List<Long> userIds=policemanMapper.getUserIds();
        List<Long> list = new ArrayList<>();
        for (int i=0;i<policemanList.size();i++) {
            boolean flag=false;
            Random random = new Random();
            long rangeStart = 100000000000000000L; // 10^18
            long rangeEnd = 999999999999999999L; // 10^19 - 1
            Long userId=rangeStart + ((long) (random.nextDouble() * (rangeEnd - rangeStart)));

            if (userIds.contains(userId)){
                flag=true;
            }
            if (!flag){
                list.add(userId);
            }
            if (flag){
                i--;
            }
        }
        List<SysUserRole> sysUserRoleList=new ArrayList<>();
        List<SysUserOrg> sysUserOrgList=new ArrayList<>();
        List<SysUser> sysUserList=new ArrayList<>();
        //角色
        Long roleId=1716370847267106817L;
        for (int i=0;i<policemanList.size();i++) {
            Policeman one = policemanList.get(i);
            Long userId = list.get(i);
            //创建用户信息
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setAccount(one.getName()+one.getPoliceCode());
            sysUser.setPassword("123456");
            sysUser.setNickName(one.getName());
            sysUser.setRealName(one.getName());
            SysUserCreateFactory.fillAddSysUser(sysUser);
            sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
            sysUser.setDelFlag(LogicDelEnum.N.getCode());
            sysUser.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUser.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserList.add(sysUser);
            one.setUserId(sysUser.getUserId());
            one.setPassword(sysUser.getPassword());
            //创建关联表数据
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setOrgId(one.getOrgId());
            sysUserOrg.setUserId(sysUser.getUserId());
            sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRoleList.add(sysUserRole);

        }
        updateBatchById(policemanList);
        sysUserService.saveBatch(sysUserList);
        sysUserRoleService.saveBatch(sysUserRoleList);
        sysUserOrgService.saveBatch(sysUserOrgList);
        return true;
    }
    @Override
    @Transactional
    public boolean changeErrorPoliceUserId(PolicemanReq req) {
        List<Long> userIdList=new ArrayList<>();
        List<Policeman> policeList=new ArrayList<>();
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().select(SysUser::getUserId));
        List<Long> collect = list.stream().map(SysUser::getUserId).collect(Collectors.toList());
        Long roleId=1716370847267106817L;
        List<SysUserRole> sysUserRoleList=new ArrayList<>();
        List<SysUserOrg> sysUserOrgList=new ArrayList<>();
        List<SysUser> sysUserList=new ArrayList<>();
        if (ObjectUtil.isNotNull(req.getFlag()) && req.getFlag().equals("true")) {
            userIdList=policemanMapper.selectErrorInfo();

        }else {
            List<Long> userRoleList=new ArrayList<>();
            userRoleList.add(JYZBConstant.YW_ROLR_ID);
            userRoleList.add(JYZBConstant.SH_ROLR_ID);
            userRoleList.add(JYZBConstant.GL_ROLR_ID);
            policeList = policemanMapper.changeUserIdToPolice(userRoleList);
            userIdList=policeList.stream().map(Policeman::getUserId).collect(Collectors.toList());
        }
        for (int i=0;i<userIdList.size();i++) {
            Long userId = userIdList.get(i);
            if (ObjectUtil.isNotNull(req.getFlag()) && req.getFlag().equals("true")){
                policeList=policemanMapper.getErrorPolice(userId);
            }
            if (ObjectUtil.isNotNull(req.getFlag()) && req.getFlag().equals("true")){
                for (int j=0;j<policeList.size() - 1;j++) {
                    Policeman one = policeList.get(j);
                    Random random = new Random();
                    long rangeStart = 100000000000000000L; // 10^18
                    long rangeEnd = 999999999999999999L; // 10^19 - 1
                    Long newUserId=rangeStart + ((long) (random.nextDouble() * (rangeEnd - rangeStart)));

                    if (collect.contains(newUserId)){
                        j--;
                        continue;
                    }else {
                        collect.add(newUserId);

                    }
                    SysUser sysUser = createUser(newUserId, one);
                    sysUserList.add(sysUser);
                    one.setUserId(sysUser.getUserId());
                    one.setPassword(sysUser.getPassword());
                    //创建关联表数据
                    SysUserOrg sysUserOrg = createUserOrg(one.getOrgId(), sysUser.getUserId());
                    sysUserOrgList.add(sysUserOrg);
                    //创建角色表数据
                    SysUserRole sysUserRole = createSysUserRole(sysUser.getUserId(), roleId);
                    sysUserRoleList.add(sysUserRole);
                }
            }else {
                Policeman one = policeList.get(i);
                Random random = new Random();
                long rangeStart = 100000000000000000L; // 10^18
                long rangeEnd = 999999999999999999L; // 10^19 - 1
                Long newUserId=rangeStart + ((long) (random.nextDouble() * (rangeEnd - rangeStart)));

                if (collect.contains(newUserId)){
                    i--;
                }else {
                    collect.add(newUserId);

                }
                SysUser sysUser = createUser(newUserId, one);
                sysUserList.add(sysUser);
                one.setUserId(sysUser.getUserId());
                one.setPassword(sysUser.getPassword());
                //创建关联表数据
                SysUserOrg sysUserOrg = createUserOrg(one.getOrgId(), sysUser.getUserId());
                sysUserOrgList.add(sysUserOrg);
                //创建角色表数据
                SysUserRole sysUserRole = createSysUserRole(sysUser.getUserId(), roleId);
                sysUserRoleList.add(sysUserRole);
            }

            updateBatchById(policeList);
        }
        sysUserService.saveBatch(sysUserList);
        sysUserRoleService.saveBatch(sysUserRoleList);
        sysUserOrgService.saveBatch(sysUserOrgList);
        return true;
    }

    public SysUser createUser(Long newUserId,Policeman one){
        SysUser sysUser = new SysUser();
        sysUser.setUserId(newUserId);
        sysUser.setAccount(one.getName()+one.getPoliceCode());
        sysUser.setPassword("123456");
        sysUser.setNickName(one.getName());
        sysUser.setRealName(one.getName());
        SysUserCreateFactory.fillAddSysUser(sysUser);
        sysUser.setAvatar(FileConstant.DEFAULT_AVATAR_FILE_ID);
        sysUser.setDelFlag(LogicDelEnum.N.getCode());
        sysUser.setCreateTime(DateTimeUtil.getCurrentDateTime());
        sysUser.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        return sysUser;
    }
    public SysUserRole createSysUserRole(Long userId,Long roleId){
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(roleId);
        sysUserRole.setUserId(userId);
        sysUserRole.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
        return sysUserRole;
    }
    public SysUserOrg createUserOrg(Long orgId,Long userId){
        SysUserOrg sysUserOrg = new SysUserOrg();
        sysUserOrg.setOrgId(orgId);
        sysUserOrg.setUserId(userId);
        sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
        sysUserOrg.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        return sysUserOrg;
    }

    public void updateOrgAndSendMessage(PubOrg orgInfos,String orgCode,String devSn){
        Cabinet cabinetOrg= cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn, devSn));
        orgInfos.setPoliceUpdateService(cabinetOrg.getName()+"-"+cabinetOrg.getDevSn());
        pubOrgService.updateById(orgInfos);
        //人员信息修改之后推送至本地主机和单警柜
        PubOrg cabinetOrgInfos = pubOrgService.PubOrgCodeExist(orgCode);
        List<Cabinet> cabinets= cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getOrgIdInt, cabinetOrgInfos.getOrgId()));//拿到组织机构下所有的警柜用于消息推送
        if (cabinets.size()>0)
        {
            cabinets.forEach(t-> MQ.SendMsg("cabinetMsg",t.getDevSn(),"policeChange"));
        }
    }



}
