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.Wrapper;
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.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.CabinetBoxReq;
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.exception.enums.*;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.*;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.*;
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.dict.entity.SysDict;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.dict.service.SysDictService;
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.entity.SysFileInfo;
import com.junmp.v2.file.biz.service.SysFileInfoService;
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 com.sun.jna.platform.win32.OaIdl;
import com.sun.org.apache.bcel.internal.generic.SWITCH;
import liquibase.pro.packaged.O;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
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.function.Predicate;
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 PoliceFaceService policeFaceService;

    @Resource
    private StocktakeService stocktakeService;

    @Resource
    private CabinetBoxPoliceService cabinetBoxPoliceService;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private SysDictItemService sysDictItemService;
    @Autowired
    private RabbitMQSendMsg MQ;
    @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 PolicemanService policemanService;

    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()));
        if (CollectionUtil.isNotEmpty(list)){
            throw new ServiceException(PolicemanExceptionEnum.POLICECODE_IS_EXISTS);
        }
        //查询传入的组织机构id是否存在
        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.getFaceInfo());
        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.getCabinetNum(),"policeChange"));
        }
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Adding policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),mqDto);//推送至仓库主机
        return policeman.getId();
    }

    /**
     * 添加警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String AddPolicemanFromCab(CabinetPolicemanReq req) {
        //判断传入的用户名是否存在
        Policeman one = this.getOne(new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getName, req.getName())
                .and(wrapper -> wrapper.eq(Policeman::getPoliceCode, req.getPoliceCode()))
        );
        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);
        //判断是否添加角色，进行绑定
        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.getPoliceId());
        policeman.setPassword(sysUser.getPassword());
        policeman.setState(1);
        policeman.setUserId(sysUser.getUserId());
        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());


        Cabinet cabinet= cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabinetNum, req.getSerialNum()));
        orgInfo.setPoliceUpdateService(cabinet.getName()+"-"+cabinet.getCabinetNum());
        pubOrgService.updateById(orgInfo);
        List<Cabinet> cabinets= cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getOrgIdInt, req.getCabinetOrgId()));//拿到组织机构下所有的警柜用于消息推送
        if (cabinets.size()>0)
        {
            cabinets.forEach(t-> MQ.SendMsg("cabinetMsg",t.getCabinetNum(),"policeChange"));
        }
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Adding policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),mqDto);


        return policeman.getId();
    }

    /**
     * 警员绑定账号
     *
     * @param
     * @return
     */
    public SysUser addFromCabinet(CabinetPolicemanReq req) {
        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.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(), req.getOrgId(), 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) {
        Policeman one = PoliceExist(req.getId());
        PubOrg pubOrg = pubOrgService.PubOrgExist(one.getOrgId());
        PolicemanDto policemanDto = new PolicemanDto();
        BeanPlusUtil.copyProperties(one, policemanDto);
        //将箱门信息展示：
        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.getNumber()+"号箱门，"+boxName;

                }else {
                    boxList.add(cabinet.getBoxId());
                    boxName = boxName + (ObjectUtil.isNull(cabinet.getName())?cabinet.getName():cabinet.getLocation())+"公共"+cabinet.getNumber()+"号箱门，";
                }
            }
            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());
        cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId,req.getId()));
        //通过警员信息中的userId对账号进行删除
        sysUserService.remove(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserId, policeman.getUserId()));
        //还要对关系表进行删除
        sysUserOrgService.remove(new LambdaQueryWrapper<SysUserOrg>().eq(SysUserOrg::getUserId,policeman.getUserId()));
        return removeById(req.getId());

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

        if (policeman.getState().equals(2))//说明当前警员调岗中不可操作
        {
            throw new ServiceException(PolicemanExceptionEnum.POLICE_IS_BUSY);
        }
        else
        {
            policeman.setState(req.getState());
        }

        PubOrg orgInfos=pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, req.getOrgId()));
        orgInfos.setPoliceUpdateTime(DateTime.now());
        Cabinet cabinetOrg= cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabinetNum, req.getSerialNum()));
        orgInfos.setPoliceUpdateService(cabinetOrg.getName()+"-"+cabinetOrg.getCabinetNum());
        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.getCabinetNum(),"policeChange"));
        }
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Updating policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),mqDto);
        return this.updateById(policeman);


    }


    /**
     * 修改警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePolice(UpdatePolicemanReq req) {
        //判断警员是否存在
        Policeman one = PoliceExist(req.getId());

        //查询传入的组织机构id是否存在
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //判断传入的修改的警员编号与本身编号一致，如果一致则无所谓，如果不一致则需要判断修改的警员编号是否已经存在
        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.setPhoto(req.getFaceInfo());
        one.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        SysUser user= sysUserService.getById(req.getUserId());
        user.setPassword(req.getPassword());
        sysUserService.updateById(user);
        //修改角色
        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.getCabinetNum(),"policeChange"));
        }
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Adding policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),mqDto);
        return updateById(one);
    }
    /**
     * 修改警员信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePoliceFromCab(CabinetPolicemanReq req) {
        //判断警员是否存在
        Policeman policeInfo = PoliceExist(req.getPoliceId());
        IStoredEncryptApi storedEncryptApi = (IStoredEncryptApi) SpringUtil.getBean(IStoredEncryptApi.class);
        //查询传入的组织机构id是否存在
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //判断传入的修改的警员编号与本身编号一致，如果一致则无所谓，如果不一致则需要判断修改的警员编号是否已经存在
        BeanPlusUtil.copyProperties(req, policeInfo);
        if (!req.getPoliceCode().equals(policeInfo.getPoliceCode())) {
          //这里需要判断警号和姓名是否都存在
            Policeman exist = this.getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getName, req.getName())
                    .and(wrapper -> wrapper.eq(Policeman::getPoliceCode, req.getPoliceCode()))
            );
            if (ObjectUtil.isNotNull(exist)) {
                throw new ServiceException(PolicemanExceptionEnum.POLICECODE_IS_EXISTS);
            }
        }
        policeInfo.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        PubOrg orgInfo=pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, req.getOrgId()));
        orgInfo.setPoliceUpdateTime(DateTime.now());
        orgInfo.setPoliceUpdateService("平台");
        pubOrgService.updateById(orgInfo);
        PubOrg orgInfos=pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, req.getOrgId()));
        orgInfos.setPoliceUpdateTime(DateTime.now());
        Cabinet cabinetOrg= cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabinetNum, req.getSerialNum()));
        orgInfos.setPoliceUpdateService(cabinetOrg.getName()+"-"+cabinetOrg.getCabinetNum());
        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.getCabinetNum(),"policeChange"));
        }

        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Adding policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        MQ.SendMsg("warehouseMsg",req.getOrgId().toString(),mqDto);
        return updateById(policeInfo);
    }

    /**
     * 修改警员信息
     *
     * @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::getCabinetNum, req.getSerialNum()));

        for (CabinetDataList orgList : dataList) {
            // 获取上报的警员列表
            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, orgList.getOrgId()));
            // 从数据库中查询指定警员ID的数据
            List<Policeman> policeList = this.list(new LambdaQueryWrapper<Policeman>().in(Policeman::getId, reqPoliceIds));

            PubOrg orgInfo = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, orgList.getOrgId()));

            // 比较并处理新增、删除和修改的数据
            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, orgList.getOrgId());
                    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);
            }
        }

        // 人员信息修改之后推送至本地主机和单警柜
        List<Cabinet> cabinets = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getOrgIdInt, req.getCabinetOrgId()));

        if (!cabinets.isEmpty()) {
            cabinets.forEach(t -> MQ.SendMsg("cabinetMsg", t.getCabinetNum(), "policeChange"));
        }
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(5);
        mqDto.setMessage("Adding policemanInfo");
        //警员添加成功之后，往消息队列推送人员更新的消息
        req.getDataList().forEach(t -> MQ.SendMsg("warehouseMsg", t.getOrgId(), mqDto));// 推送至仓库主机
        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 = new InventorySummary();
                        BeanPlusUtil.copyProperties(reqEq, newInventory);
                        newInventory.setPrice(reqEq.getPrice());
                        newInventory.setNumber(Integer.valueOf(reqEq.getNum()));
                        newInventory.setOutboundNumber(Integer.valueOf(reqEq.getOutNum()));
                        newInventory.setLocationType("1");
                        newInventory.setStockNumber(Integer.valueOf(reqEq.getInNum()));
                        newInventory.setLocationId(cabinet.getCabinetNum());
                        newInventory.setOrgId(org.getOrgId());
                        newInventory.setOrgCode(org.getOrgCode());
                        newInventory.setOrgName(org.getOrgName());
                        newInventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
                        newInventory.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                        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 = new InventorySummary();
                        BeanPlusUtil.copyProperties(reqEq, newInventory);
                        newInventory.setPrice(reqEq.getPrice());
                        newInventory.setNumber(Integer.valueOf(reqEq.getNum()));
                        newInventory.setOutboundNumber(Integer.valueOf(reqEq.getOutNum()));
                        newInventory.setLocationType("1");
                        newInventory.setStockNumber(Integer.valueOf(reqEq.getInNum()));
                        newInventory.setLocationId(cabinet.getCabinetNum());
                        newInventory.setOrgId(org.getOrgId());
                        newInventory.setOrgCode(org.getOrgCode());
                        newInventory.setOrgName(org.getOrgName());
                        newInventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
                        newInventory.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                        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());

        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");
        }
        if (ObjectUtil.isNull(req.getPageNo()) && ObjectUtil.isNull(req.getPageSize())) {
            req.setPageNo(1L);
            req.setPageSize(10L);
        }
        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());
        return policemanDtos;
    }

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

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

        for (String org : req.getOrgList()) {
            CompletableFuture<CabinetPoliceDto> future = CompletableFuture.supplyAsync(() -> {
                return processOrg(org);
            }, 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 org) {
        CabinetPoliceDto cpDto = new CabinetPoliceDto();

        // 获取组织机构信息
        PubOrg orgInfo = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>().eq(PubOrg::getOrgId, org));
        cpDto.setOrgId(org);
        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, org)
                .eq(Policeman::getState, 1));

        // 转换警员信息为 PoliceDetailDto
        List<PoliceDetailDto> policeDtoList = new ArrayList<>();
        for (Policeman police : policeList) {
            PoliceDetailDto pdDto = new PoliceDetailDto();
            BeanPlusUtil.copyProperties(police, pdDto);
            //将箱门信息展示：
            List<Cabinet> cabinetInfo = cabinetMapper.getAllCabinetsWithSingleCabinet(org, 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);
            }
            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());
        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());
       //判断是否需要添加空数据
        if(req.getIsCreateNullDate()==null || req.getIsCreateNullDate()){
            Class<PolicemanDto> policemanDto = PolicemanDto.class;
            List<PolicemanDto> nullData = BusinessUtil.createNullData(size, req.getPageNo(), req.getPageSize(), policemanDto);
            policemanDtos.addAll(nullData);
        }
        Page<PolicemanDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(policemanDtos);
        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 boolean AddFaceInfo(UpdatePolicemanReq req) {
        Policeman police = PoliceExist(req.getId());
        police.setFaceInfo(req.getFaceInfo());
        police.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        return updateById(police);
    }

    /**
     * @param
     * @return
     * @author lxh
     * @description 更新人脸信息\删除人脸信息
     * 删除时：传一个null的人脸信息即可
     * @since 2023/7/18 15:02
     **/
    @Override
    public boolean UpdateFaceInfo(UpdatePolicemanReq req) {
        Policeman police = PoliceExist(req.getId());
        police.setFaceInfo(req.getFaceInfo());
        police.setPhoto(req.getFaceInfo());
        police.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        return updateById(police);

    }

    /**
     * @param
     * @return
     * @author lxh
     * @description 查询人脸信息
     * @since 2023/7/18 15:02
     **/
    @Override
    public Policeman SearchFaceInfo(PolicemanReq req) {
        Policeman policeman = PoliceExist(req.getId());
        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,"assign")
                .orderByDesc(OrderLog::getCreateTime));
        List<PoliceEquipment> policeEqsList=new ArrayList<>();
        String locationId="";
        OrderLog orderLog=new OrderLog();
        if (list.size()>0){
             orderLog= list.get(0);
            policeEqsList= policeEquipmentService.list(new LambdaQueryWrapper<PoliceEquipment>()
                    .eq(PoliceEquipment::getPoliceId, policeman.getId()));
            locationId = policeEqsList.get(0).getLocationId();
        }
        List<Object[]> searchItem=new ArrayList<>();
        //判断调岗警员是否已经绑定了箱门
        List<CabinetBoxPolice> list1 = cabinetBoxPoliceService.list(new LambdaQueryWrapper<CabinetBoxPolice>()
                .eq(CabinetBoxPolice::getPoliceId, policeman.getId()));

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

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

            //将箱门全部清除
            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 (ObjectUtil.isNotNull(orderLog) && list1.size()==0 && !flag && !locationId.trim().isEmpty()){
                    flag=true;

                    cabinetBox = cabinetBoxService.getById(boxId);
                    for (PoliceEquipment equipment:policeEqsList) {
                        equipment.setLocationId(cabinetBox.getCabinetId());
                        equipment.setOrgId(req.getOrgId());
                        Object[] item=new Object[]{req.getOrgId(),cabinetBox.getCabinetId(),equipment.getTypeId(),equipment.getSizeId(),equipment.getPrice()};
                        searchItem.add(item);
                    }
                    policeEquipmentService.updateBatchById(policeEqsList);
                }
            }
            if (cabinetBoxPoliceList.size()>0){
                result = cabinetBoxPoliceService.saveBatch(cabinetBoxPoliceList);
            }
        }else {
            result = cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().eq(CabinetBoxPolice::getPoliceId, req.getId()));

        }

        //判断summary表中是否有数据，如果有，summary表直接更新数据，如果summary表没有，那么直接新增一条数据
        if (flag){
            boolean b = updateSumDataAndLog(req.getOrgId(), cabinetBox, policeEqsList, searchItem);

        }
        return result;
    }

    //添加调岗第一次调入人员绑定箱门时修改装备汇总表的信息以及记录日志
    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表进行计算
        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 = getInventorySummary(pubOrg, equipment, cabinet);
                    addSumList.add(inventorySummary);
                }

            }
        }else {
            for (PoliceEquipment equipment:policeEqsList) {
                stringBuilder.append(cabinet.getName()+"新增装备"+equipment.getTypeName()+"【"+equipment.getSizeName()+"】，在柜数量："+equipment.getNum()+"，并且修改了价格和总数；");
                InventorySummary inventorySummary = getInventorySummary(pubOrg, equipment, cabinet);
                addSumList.add(inventorySummary);
            }
        }
        boolean a=true;
        if (addSumList.size()>0){
            a=inventorySummaryService.saveBatch(addSumList);
        }
        boolean b=true;
        if (inventorySummaryList.size()>0){
            b=inventorySummaryService.updateBatchById(inventorySummaryList);
        }
        //记录日志
        OrderLog orderLog1 = new OrderLog();
        orderLog1.setBussinessType("调入警员修改库存汇总");
        String string = stringBuilder.toString();
        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 a && b && c;
    }

    private InventorySummary getInventorySummary(PubOrg pubOrg, PoliceEquipment equipment, Cabinet cabinet) {
        InventorySummary inventorySummary = new InventorySummary();
        inventorySummary.setValuekey(pubOrg.getOrgCode() + equipment.getSizeId());
        inventorySummary.setOrgId(pubOrg.getOrgId());
        inventorySummary.setOrgName(pubOrg.getOrgName());
        inventorySummary.setOrgCode(pubOrg.getOrgCode());
        inventorySummary.setTypeId(equipment.getTypeName());
        inventorySummary.setTypeName(equipment.getTypeName());
        inventorySummary.setSizeId(equipment.getSizeId());
        inventorySummary.setSizeName(equipment.getSizeName());
        inventorySummary.setLocationType("0");
        inventorySummary.setLocationId(cabinet.getId());
        inventorySummary.setLocationName(cabinet.getName());
        inventorySummary.setNumber(equipment.getNum());
        inventorySummary.setPrice(equipment.getPrice().multiply(BigDecimal.valueOf(equipment.getNum())));
        inventorySummary.setUnitPrice(equipment.getPrice());
        inventorySummary.setStockNumber(equipment.getNum());
        inventorySummary.setOutboundNumber(0);
        inventorySummary.setCreateTime(DateTimeUtil.getCurrentDateTime());
        return inventorySummary;
    }

    /**
     * 通过警员id判断警员是否存在，不存在则抛出异常
     */
    @Override
    public Policeman PoliceExist(String policeId) {
        Policeman policeman = getOne(new LambdaQueryWrapper<Policeman>()
                .eq(Policeman::getId,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());
        SysDict sysDict = sysDictService.getOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getDictCode, "reassignment_type"));
        List<SysDictItem> list = sysDictItemService.list(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, sysDict.getDictId()));
        String itemValue = list.get(0).getItemValue();
        String itemValue1 = list.get(1).getItemValue();
        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(itemValue) && itemValue.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);
            }


        }
        //assign是调出
        else if (req.getReassignmentType().equals(itemValue1)  && itemValue1.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()));

            //判断前端传递的装备列表字段是否为空，如果为空则表示该警员不拿走任何装备信息(不做任何操作)
            if (ObjectUtil.isNull(req.getDetailList()) || req.getDetailList().trim().isEmpty()){
//                if (list1.size()>0){
////                    policeEquipmentService.remove(eq);
//                    policeEquipmentService.removeBatchByIds(list1);
//                }

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

                List<Object[]> searchItem=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())){
                            Object[] item=new Object[]{policeEquipment.getOrgId(),policeEquipment.getLocationId(),policeEquipment.getTypeId(),policeEquipment.getSizeId(),policeEquipment.getPrice(),one.getNum()};
                            searchItem.add(item);
                            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);

//                if (searchItem.size()>0)
//                {
//                //修改库存数量
//                List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
//                List<InventorySummary> updateSummaryList=new ArrayList<>();
//                for (InventorySummary is:inventorySummaryList) {
//                    for ( Object[] one: searchItem) {
//                        if (is.getLocationId().equals(one[1]) && is.getTypeId().equals(one[2])
//                                && is.getSizeId().equals(one[3]) && is.getUnitPrice().compareTo(new BigDecimal(one[4].toString()))==0){
//                            is.setOutboundNumber(is.getOutboundNumber()-Integer.parseInt(one[5].toString()));
//                            is.setNumber(is.getNumber()-Integer.parseInt(one[5].toString()));
//                            updateSummaryList.add(is);
//                            break;
//                        }
//                    }
//                }
//                if (updateSummaryList.size()>0){
//                    inventorySummaryService.updateBatchById(updateSummaryList);
//                }
//                }
            }
            //记录日志(如果警员携带装备,则进行记录 )
            if (ObjectUtil.isNotNull(reqEquipments)){
                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.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())
                            .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 {
                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 = stocktakeService.setOrderCode(req.getBussinessType(), req.getOrgId());
            String codeValue=String.format("%04d",orderNum.getNum());
            reassignment.setOrderCode(orderNum.getBussinessType()+orderNum.getYear()+
                    String.format("%02d", LocalDateTime.now().getMonth().getValue())+
                    String.format("%02d",LocalDateTime.now().getDayOfMonth())+codeValue);
            String userIds=policemanService.searchUserByRoleId(req.getOrgId());
            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);
        }
        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);
        startProcessInstanceDTO.setUserName(req.getPoliceName());
        if (req.getReassignmentType().equals("assign")){
            startProcessInstanceDTO.setEndOrgName(req.getOrgName());
        }else if (req.getReassignmentType().equals("reassign")){
            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())
                .eq(ObjectUtil.isNotNull(req.getExamineState()) && !req.getExamineState().trim().isEmpty(), Reassignment::getExamineState, req.getExamineState())
                .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.getUserId())){
            eq.and(wrapper -> wrapper.eq(Reassignment::getAgentId,req.getUserId())
                    .or().like(Reassignment::getExamineState,req.getUserId()));
        }else {
            LoginUser loginUser = LoginContext.getContext().getLoginUser();
            eq.and(wrapper -> wrapper.eq(Reassignment::getAgentId,loginUser.getUserId())
                    .or().like(Reassignment::getExamineState,loginUser.getUserId()));
        }
        Page<Reassignment> page = reassignmentService.page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        return PageResultFactory.createPageResult(page);
    }

    //查询组织机构下的用户以及角色信息(也可以根据别的查询条件查询)
    @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;
    }

    //添加人脸和指纹照片或修改
//    @Override
//    public boolean addFaceAndfinger(UpdatePolicemanReq req) {
//        //人脸
//        boolean a=true;
//        boolean flag=false;
//        Policeman one = getById(req.getId());

//        if (one.getFaceInfo()!=null && !one.getFaceInfo().isEmpty()){
//            flag=true;
//            if(req.getFaceInfoList().size()>0 && !req.getFaceInfoList().get(0).equals(one.getFaceInfo())){
//                one.setFaceInfo(req.getFaceInfoList().get(0));
//            }else {
//                one.setFaceInfo(null);
//
//            }
//            a = updateById(one);
//        }else {
//            flag=true;
//            one.setFaceInfo(req.getFaceInfoList().get(0));
//            a = updateById(one);
//        }

//        //指纹
//        List<PoliceFinger> addFingerList=new ArrayList<>();
//        List<PoliceFinger> delFingerList=new ArrayList<>();
//        //库中存储的指纹信息
//        List<PoliceFinger> fingerList = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>()
//                .eq(PoliceFinger::getPoliceId, req.getId()));
//        List<String> fingerInfoList = req.getFingerList();
//        Set<String> set1 = new HashSet<>();
//        for (PoliceFinger finger : fingerList) {
//            set1.add(finger.getFingerInfo());
//        }
//        if (fingerList.size()>0){
//            if (fingerInfoList.size()>0){
//                for (String finger : fingerInfoList) {
//                    if (!set1.contains(finger)) {
//                        PoliceFinger finger1 = new PoliceFinger();
//                        finger1.setFingerInfo(finger);
//                        finger1.setPoliceId(req.getId());
//                        finger1.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                        addFingerList.add(finger1);
//                    }
//                }
//                for (PoliceFinger finger : fingerList) {
//                    if (!fingerInfoList.contains(finger.getFingerInfo())) {
//                        delFingerList.add(finger);
//                    }
//                }
//            }else {
//                delFingerList.addAll(fingerList);
//            }
//        }else {
//            if (fingerInfoList.size()>0){
//                for (String finger:fingerInfoList) {
//                    PoliceFinger finger1 = new PoliceFinger();
//                    finger1.setFingerInfo(finger);
//                    finger1.setPoliceId(req.getId());
//                    finger1.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                    addFingerList.add(finger1);
//                }
//            }
//        }
//        boolean c=true;
//        if (addFingerList.size()>0){
//            flag=true;
//            c=policeFingerService.saveBatch(addFingerList);
//        }
//        boolean d=true;
//        if (delFingerList.size()>0){
//            flag=true;
//            d=policeFingerService.removeByIds(delFingerList);
//        }
//        return (a  && c && d);
//    }

    //查询组织机构为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();
        Policeman policeman = getById(req.getPoliceId());
        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);
        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);
            //那么我直接将消息推送到相应单警柜以及本地主机

        }
        return true;
    }

    //修改密码
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePassword(UpdatePolicemanReq req) {
        IStoredEncryptApi storedEncryptApi = (IStoredEncryptApi) SpringUtil.getBean(IStoredEncryptApi.class);
        Policeman one=new Policeman();
        if (ObjectUtil.isNotNull(req.getId()) && ObjectUtil.isNotNull(req.getUserId())){
            one = getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getId, req.getId()).eq(Policeman::getUserId,req.getUserId()));
        } else if (ObjectUtil.isNotNull(req.getId()) && ObjectUtil.isNull(req.getUserId())){
            one = getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getId, req.getId()));
        }else if (ObjectUtil.isNotNull(req.getUserId()) && ObjectUtil.isNull(req.getId())){
            one = getOne(new LambdaQueryWrapper<Policeman>()
                    .eq(Policeman::getUserId, req.getUserId()));
        }
        if (ObjectUtil.isNotNull(one)){
            //如果不为空则表示修改警员密码
            String newPassword = storedEncryptApi.encrypt(req.getNewPassword());
            //同时修改警员密码
            one.setPassword(newPassword);
            updateById(one);
        }
        SysUserReq sysUserReq = new SysUserReq();
        BeanPlusUtil.copyProperties(req,sysUserReq);
        sysUserService.editPassword(sysUserReq);
        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);
        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));
            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);
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean oneClickAccountCreation(PubOrg pubOrg) throws IOException {
//        //一次性创建一个组织机构下的三种系统账号（运维，仓管员，审核员）
//        //先判断一下前端是否传递组织机构编号（如果传递，指定创建该组织机构下的三种账号）
//        List<String> userAccountList=new ArrayList<>();
//        userAccountList.add("yw");
//        userAccountList.add("sh");
//        userAccountList.add("gl");
//        List<Long> userRoleList=new ArrayList<>();
//        userRoleList.add(1663372027127402498L);
//        userRoleList.add(1663372320355389441L);
//        userRoleList.add(1528003832557232130L);
//        List<SysUserRole> sysUserRoleList=new ArrayList<>() ;
//        List<SysUserOrg> sysUserOrgList=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> userDtoYW = policemanMapper.oneClickAccountCreation(null,userAccountList.get(0)+"33%",userRoleList.get(0));
//            List<UserDto> userDtosSH = policemanMapper.oneClickAccountCreation(null,userAccountList.get(1)+"33%",userRoleList.get(1));
//            List<UserDto> userDtosGL = policemanMapper.oneClickAccountCreation(null,userAccountList.get(2)+"33%",userRoleList.get(2));
//            List<CompletableFuture<Void>> futures = new ArrayList<>();
//            List<CompletableFuture<Void>> futures1 = new ArrayList<>();
//            List<CompletableFuture<Void>> futures2 = new ArrayList<>();
//
//            for (PubOrg one: orgList) {
//                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                    Map<String, List<?>> map = addRoleAndOrgYW(userDtoYW, one, ywExists, sysUser,
//                            sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                    List<SysUserOrg> userlist1 = (List<SysUserOrg>) map.get("sysUserOrgList");
//                    sysUserOrgList.addAll(userlist1);
//                    List<SysUserRole> roleList1 = (List<SysUserRole>) map.get("sysUserRoleList");
//                    sysUserRoleList.addAll(roleList1);
//                });
//
//                futures.add(future);
//            }
//            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//
//
//            for (PubOrg one: orgList) {
//                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                    Map<String, List<?>> map = addRoleAndOrgSH(userDtosSH, one, shExists, sysUser,
//                            sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                    List<SysUserOrg> userlist1 = (List<SysUserOrg>) map.get("sysUserOrgList");
//                    sysUserOrgList.addAll(userlist1);
//                    List<SysUserRole> roleList1 = (List<SysUserRole>) map.get("sysUserRoleList");
//                    sysUserRoleList.addAll(roleList1);
//                });
//
//                futures1.add(future);
//            }
//            CompletableFuture.allOf(futures1.toArray(new CompletableFuture[0])).join();
//
//
//            for (PubOrg one: orgList) {
//                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                    Map<String, List<?>> map = addRoleAndOrgGL(userDtosGL, one, glExists, sysUser,
//                            sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                    List<SysUserOrg> userlist1 = (List<SysUserOrg>) map.get("sysUserOrgList");
//                    sysUserOrgList.addAll(userlist1);
//                    List<SysUserRole> roleList1 = (List<SysUserRole>) map.get("sysUserRoleList");
//                    sysUserRoleList.addAll(roleList1);
//                });
//
//                futures2.add(future);
//            }
//
//            // 等待所有异步任务完成
//            CompletableFuture.allOf(futures2.toArray(new CompletableFuture[0])).join();
//
//
//        }else {
//            //如果有组织机构编号，则判断该组织机构下面是否已经存在账号，如果存在，则不进行创建，否则进行创建
//            PubOrg one = pubOrgService.getOne(new LambdaQueryWrapper<PubOrg>()
//                    .eq(PubOrg::getOrgCode, pubOrg.getOrgCode()));
//            if (ObjectUtil.isNull(one)){
//                throw new ServiceException(OrgExceptionEnum.ORG_NOT_EXIST);
//            }
//            List<UserDto> userDtos = policemanMapper.oneClickAccountCreation(one.getOrgId(),null,null);
//
//            if (CollectionUtil.isEmpty(userDtos)){
//                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);
//                    sysUserOrgList.add(sysUserOrg);
//                    //创建角色表数据
//                    SysUserRole sysUserRole = new SysUserRole();
//                    sysUserRole.setRoleId(userRoleList.get(i));
//                    sysUserRole.setUserId(userId);
//                    sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                    sysUserRoleList.add(sysUserRole);
//                }
//
//            }else {
//                Map<String, List<?>> mapYw = addRoleAndOrgYW(userDtos, one, ywExists, sysUser,
//                         sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                List<SysUserOrg> userlist1=(List<SysUserOrg>)mapYw.get("sysUserOrgList");
//                sysUserOrgList.addAll(userlist1);
//                List<SysUserRole> roleList1 =(List<SysUserRole>) mapYw.get("sysUserRoleList");
//                sysUserRoleList.addAll(roleList1);
//
//                Map<String, List<?>> mapSh = addRoleAndOrgSH(userDtos, one,  shExists, sysUser,
//                        sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                List<SysUserOrg> userlist2=(List<SysUserOrg>)mapSh.get("sysUserOrgList");
//                sysUserOrgList.addAll(userlist2);
//                List<SysUserRole> roleList2 =(List<SysUserRole>) mapSh.get("sysUserRoleList");
//                sysUserRoleList.addAll(roleList2);
//
//                Map<String, List<?>> mapGl = addRoleAndOrgGL(userDtos, one,  glExists, sysUser,
//                        sysUserOrgList, userRoleList, userAccountList, sysUserRoleList);
//                List<SysUserOrg> userlist3=(List<SysUserOrg>)mapGl.get("sysUserOrgList");
//                sysUserOrgList.addAll(userlist3);
//                List<SysUserRole> roleList3 =(List<SysUserRole>) mapGl.get("sysUserRoleList");
//                sysUserRoleList.addAll(roleList3);
//
//            }
//
//            sysUserOrgService.saveBatch(sysUserOrgList);
//            sysUserRoleService.saveBatch(sysUserRoleList);
//
//        }
//
//        return true;
//    }
//    private Map<String,List<?>> addRoleAndOrgYW(List<UserDto> userDtos,PubOrg one,Boolean ywExists,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;
//                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);
//            sysUserOrgList.add(sysUserOrg);
//            //创建角色表数据
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setRoleId(userRoleList.get(0));
//            sysUserRole.setUserId(userId);
//            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//            sysUserRoleList.add(sysUserRole);
//        }
//        map.put("sysUserRoleList",sysUserRoleList);
//        map.put("sysUserOrgList",sysUserOrgList);
//        return map;
//    }
//
//    private Map<String,List<?>> addRoleAndOrgSH(List<UserDto> userDtos,PubOrg one,Boolean shExists,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("sh"+one.getOrgCode())){
//                shExists=true;
//                break;
//            }
//        }
//        if (!shExists){
//            sysUser.setUserId(null);
//            Long userId = addUser(sysUser, userAccountList.get(1), one);
//            //创建关联表数据
//            SysUserOrg sysUserOrg = new SysUserOrg();
//            sysUserOrg.setOrgId(one.getOrgId());
//            sysUserOrg.setUserId(userId);
//            sysUserOrgList.add(sysUserOrg);
//            //创建角色表数据
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setRoleId(userRoleList.get(1));
//            sysUserRole.setUserId(userId);
//            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//            sysUserRoleList.add(sysUserRole);
//        }
//        map.put("sysUserRoleList",sysUserRoleList);
//        map.put("sysUserOrgList",sysUserOrgList);
//        return map;
//    }
//
//    private Map<String,List<?>> addRoleAndOrgGL(List<UserDto> userDtos,PubOrg one,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("gl"+one.getOrgCode())){
//                glExists = true;
//                break;
//            }
//
//        }
//        if (!glExists){
//            sysUser.setUserId(null);
//            Long userId = addUser(sysUser, userAccountList.get(2), one);
//            SysUserOrg sysUserOrg = new SysUserOrg();
//            sysUserOrg.setOrgId(one.getOrgId());
//            sysUserOrg.setUserId(userId);
//            sysUserOrgList.add(sysUserOrg);
//            //创建角色表数据
//            SysUserRole sysUserRole = new SysUserRole();
//            sysUserRole.setRoleId(userRoleList.get(2));
//            sysUserRole.setUserId(userId);
//            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//            sysUserRoleList.add(sysUserRole);
//        }
//        map.put("sysUserRoleList",sysUserRoleList);
//        map.put("sysUserOrgList",sysUserOrgList);
//        return map;
//    }

    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(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());
        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(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());

        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(1663372027127402498L);
        userRoleList.add(1663372320355389441L);
        userRoleList.add(1528003832557232130L);
        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);
            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(OrgExceptionEnum.ORG_NOT_EXIST);
            }
            List<UserDto> userDtos = policemanMapper.oneClickAccountCreation(one.getOrgId(),null,null);

            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);
                    sysUserOrgList.add(sysUserOrg);
                    //创建角色表数据
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(userRoleList.get(i));
                    sysUserRole.setUserId(userId);
                    sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    sysUserRoleList.add(sysUserRole);

//                    sysUser.setUserId(null);
//                    //创建用户信息
//                    SysUser Adduser = addUserAndReturn(sysUser, userAccountList.get(i), one);
//                    sysUserService.save(Adduser);
//                    //创建角色表数据
//                    SysUserRole sysUserRole = new SysUserRole();
//                    sysUserRole.setRoleId(userRoleList.get(i));
//                    sysUserRole.setUserId(Adduser.getUserId());
//                    sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                    sysUserRoleService.save(sysUserRole);
//                    //创建关联表数据
//                    SysUserOrg sysUserOrg = new SysUserOrg();
//                    sysUserOrg.setOrgId(one.getOrgId());
//                    sysUserOrg.setUserId(Adduser.getUserId());
//                    sysUserOrg.setCreateTime(DateTimeUtil.getCurrentDateTime());
//                    sysUserOrgService.save(sysUserOrg);

                }

            }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);
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(0));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(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);
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(1));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(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);
            sysUserOrgList.add(sysUserOrg);
            //创建角色表数据
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(userRoleList.get(2));
            sysUserRole.setUserId(userId);
            sysUserRole.setCreateTime(DateTimeUtil.getCurrentDateTime());
            sysUserRoleList.add(sysUserRole);
        }
        map.put("sysUserRoleList",sysUserRoleList);
        map.put("sysUserOrgList",sysUserOrgList);
        return map;
    }

    //获取组织机构下所有的审核员的userId，用字符串拼接
    @Override
    public String searchUserByRoleId(Long orgId) {
        return policemanMapper.searchUserByRoleId(orgId);
    }


}
