package com.mosty.qwzx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.qwzx.TbQwXffwDto;
import com.mosty.base.model.dto.qwzx.TbQwXfpbAddAndEditDto;
import com.mosty.base.model.dto.qwzx.TbQwXfpbZqDto;
import com.mosty.base.model.dto.qwzx.TbQwXzSearchDto;
import com.mosty.base.model.dto.rwzx.TbRwTaskDto;
import com.mosty.base.model.dto.rwzx.TbRwTaskUserDto;
import com.mosty.base.model.entity.qwzx.*;
import com.mosty.base.model.entity.rwzx.TbRwTask;
import com.mosty.base.model.query.qwzx.TbQwXfpbQuery;
import com.mosty.base.model.query.qwzx.TbQwXfpbSearchMyQuery;
import com.mosty.base.model.query.rwzx.TbRwTaskByYwidQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.qwzx.TbQwXfpbZqMyVo;
import com.mosty.base.model.vo.qwzx.TbQwXfpbZqVo;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.business.service.SysDeptService;
import com.mosty.common.core.business.service.SysRoleService;
import com.mosty.common.token.DeptInfo;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import com.mosty.qwzx.mapper.*;
import com.mosty.qwzx.remote.TbBaseAdaptRemoteService;
import com.mosty.qwzx.remote.TbRwzxAdaptRemoteService;
import com.mosty.qwzx.service.TbQwXfpbService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dw
 * @since 2022/8/3
 **/
@AllArgsConstructor
@Service
public class TbQwXfpbServiceImpl extends ServiceImpl<TbQwXfpbMapper, TbQwXfpb>
        implements TbQwXfpbService {

    private final TbQwJlMapper tbQwJlMapper;
    private final TbQwXfpbMrjlMapper tbQwXfpbMrjlMapper;
    private final TbQwClMapper tbQwClMapper;
    private final TbQwZnzbMapper tbQwZnzbMapper;
    private final TbQwJyqxMapper tbQwJyqxMapper;
    private final TbQwXfpbZqMapper tbQwXfpbZqMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbQwXfbbMapper tbQwXfbbMapper;
    private final TbRwzxAdaptRemoteService tbRwzxAdaptRemoteService;
    private final TbQwQxjMapper tbQwQxjMapper;
    private final TbQwXffwMapper tbQwXffwMapper;
    private final SysRoleService sysRoleService;
    private final SysDeptService sysDeptService;

    @Override
    @Transactional
    public int addEntity(TbQwXfpbAddAndEditDto dto) {
        String year = DateUtils.getQueryDateString(new Date(), "13");
        if (!DateUtils.getQueryDateString(dto.getPbksrq(), "13").equals(year) || (
                dto.getPbjsrq() != null && !DateUtils.getQueryDateString(dto.getPbjsrq(), "13").equals(year)
        )) {
            throw new BusinessException("排班开始日期和结束日期必须为本年度！！");
        }
        TbQwXfpb entity = new TbQwXfpb();
        BeanUtils.copyProperties(dto, entity);
        UserInfo user = UserInfoManager.get();

        entity.setId(UUIDGenerator.getUUID());
        entity.setPbrid(String.valueOf(user.getUserId()));
        entity.setPbr(user.getUserName());
        entity.setPbrsfzh(user.getIdEntityCard());
        if ("0".equals(entity.getJsrqlx())) {
            try {
                entity.setPbjsrq(new SimpleDateFormat("yyyy-MM-dd").parse("2099-12-31"));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new BusinessException("时间格式转换异常！！");
            }
        }
        if (StringUtils.isBlank(entity.getSsbmdm())) throw new BusinessException("请选择巡防部门！");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(entity.getSsbmdm());
        if (dept != null) {
            entity.setSsbm(dept.getDeptname());
            entity.setSsbmid(dept.getDeptid());
            entity.setSsbmdm(dept.getDeptcode());
            entity.setSsxgajdm(dept.getFxjcode());
            entity.setSsxgajid(dept.getFxjid());
            entity.setSsxgaj(dept.getFxjname());
            entity.setSssgaj(dept.getDszname());
            entity.setSssgajdm(dept.getDszcode());
            entity.setSssgajid(dept.getDszid());
        }
        entity.setXtSjly("1");
        // 保存周期表信息和其他信息
        this.setXfpbzq(dto, entity, dept, null);
        return this.baseMapper.insert(entity);
    }

    // 判断是否有时间重合、任务重合的情况，如果存在，则提示给前端
    private void checkPbxx(TbQwXfpbAddAndEditDto dto) {
        // 查询所有的人员，根据人员查询该时间段是否有排班信息
        List<TbQwXfpbZqDto> zqList = dto.getZqList();
        if (zqList == null || zqList.size() == 0) {
            throw new BusinessException("请配置周期信息");
        }
        for (int i = 0; i < zqList.size(); i++) {
            TbQwXfpbZqDto zq = zqList.get(i);
            this.checkUserPb(zq, dto, zq.getFzrId(), "01", zq.getFzrXm());
            List<TbQwJl> jlList = zq.getJlList();
            if (jlList == null || jlList.size() == 0) {
                throw new BusinessException("请配置第" + (i + 1) + "班的警力信息");
            }
            jlList.forEach(jl -> this.checkUserPb(zq, dto, jl.getJlId(), jl.getJllx(), jl.getJlxm()));
        }
    }

    // 检查用户信息是否重合
    private void checkUserPb(TbQwXfpbZqDto zq, TbQwXfpbAddAndEditDto dto, String jlId,
                             String jlLx, String jlxm) {
        // 查询重合的排班信息
        String kssj = DateUtils.getQueryDateString(zq.getKssj(), "02");
        String jssj = "";
        if (zq.getKssj().getTime() > zq.getJssj().getTime()) {
            jssj = "1970-01-02" + " " + DateUtils.getQueryDateString(zq.getJssj(), "10");
        }
        List<TbQwXfpb> pbTempList = this.baseMapper.getPbBySjAndJl
                (DateUtils.getQueryDateString(dto.getPbksrq(), "01"),
                        DateUtils.getQueryDateString(dto.getPbjsrq(), "01"),
                        jlId, kssj, jssj, dto.getId());
        pbTempList.forEach(pbTemp -> {
            throw new BusinessException(("01".equals(jlLx) ? "民警" : "辅警") + "(" + jlxm + ")在" +
                    "其他排班中时间冲突，冲突排班名称：" + pbTemp.getPbmc());
        });
    }


    @Override
    @Transactional
    public Integer editEntity(TbQwXfpbAddAndEditDto dto) {
        // 判断是否有时间重合、任务重合的情况，如果存在，则提示给前端
        // this.checkPbxx(dto);
        String year = DateUtils.getQueryDateString(new Date(), "13");
        if (!DateUtils.getQueryDateString(dto.getPbksrq(), "13").equals(year) || (
                dto.getPbjsrq() != null && !DateUtils.getQueryDateString(dto.getPbjsrq(), "13").equals(year)
        )) {
            throw new BusinessException("排班开始日期和结束日期必须为本年度！！");
        }
        TbQwXfpb pb = new TbQwXfpb();
        BeanUtils.copyProperties(dto, pb);
        if ("0".equals(pb.getJsrqlx())) {
            try {
                pb.setPbjsrq(new SimpleDateFormat("yyyy-MM-dd").parse("2099-12-31"));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new BusinessException("时间格式转换异常！！");
            }
        }
        if (StringUtils.isBlank(pb.getSsbmdm())) throw new BusinessException("请选择巡防部门！");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByDeptId(pb.getSsbmdm());
        if (dept != null) {
            pb.setSsbm(dept.getDeptname());
            pb.setSsbmid(dept.getDeptid());
            pb.setSsbmdm(dept.getDeptcode());
            pb.setSsxgajdm(dept.getFxjcode());
            pb.setSsxgajid(dept.getFxjid());
            pb.setSsxgaj(dept.getFxjname());
            pb.setSssgaj(dept.getDszname());
            pb.setSssgajdm(dept.getDszcode());
            pb.setSssgajid(dept.getDszid());
        }
        // 删除排班表的数据
        this.deleteXfpb(pb.getId());
        // 添加排班表数据
        this.setXfpbzq(dto, pb, dept, dto.getId());
        return this.baseMapper.updateById(pb);
    }

    @Override
    @Transactional
    public Integer delEntity(String id) {
        // 删除巡防排班周期和警力信息
        this.deleteXfpb(id);
        // 删除排班信息
        return this.baseMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatch(List<String> ids) {
        if (ids.size() > 0) {
            ids.forEach(id -> {
                // 删除值班排班周期和警力信息
                this.deleteXfpb(id);
                // 删除排班信息
                this.baseMapper.deleteById(id);
            });
        }
    }

    @Override
    public IPage<TbQwXfpbAddAndEditDto> getPageList(TbQwXfpbQuery dto) {
        QueryWrapper<TbQwXfpb> qw = new QueryWrapper<>();
        UserInfo userInfo = UserInfoManager.get();
//      PermissionsUtil.queryWrapperUtil(qw, userInfo);
        qw.lambda().eq(StringUtils.isNotBlank(dto.getJsrqlx()), TbQwXfpb::getJsrqlx, dto.getJsrqlx())
                .eq(dto.getXhzq() != null, TbQwXfpb::getXhzq, dto.getXhzq())
                .eq(StringUtils.isNotBlank(dto.getXhlx()), TbQwXfpb::getXhlx, dto.getXhlx())
                .eq(dto.getMrbc() != null, TbQwXfpb::getMrbc, dto.getMrbc())
                .like(dto.getPbmc() != null, TbQwXfpb::getPbmc, dto.getPbmc())
                .eq(StringUtils.isNotBlank(dto.getPbr()), TbQwXfpb::getPbr, dto.getPbr())
                .eq(StringUtils.isNotBlank(dto.getSsbmdm()), TbQwXfpb::getSsbmdm, dto.getSsbmdm())
                .eq(StringUtils.isNotBlank(dto.getSsbmid()), TbQwXfpb::getSsbmid, dto.getSsbmid());
        if (dto.getPbksrq() != null && dto.getPbjsrq() != null) {
            qw.lambda().and(
                    it -> it.last("'" + DateUtils.getQueryDateString(dto.getPbksrq(), "01") + "' between DATE_FORMAT(pbksrq,'%y-%m-%d') and DATE_FORMAT(pbjsrq,'%y-%m-%d')" +
                            " or '" + DateUtils.getQueryDateString(dto.getPbjsrq(), "01") + "' between DATE_FORMAT(pbksrq,'%y-%m-%d') and DATE_FORMAT(pbjsrq,'%y-%m-%d')")
            );
        }
        qw.last(StringUtils.isNotBlank(dto.getFzrXm()), " and id in (select pb_id from tb_qw_xfpb_zq where " +
                "fzr_xm like concat('%','" + dto.getFzrXm() + "','%'))");
        IPage<TbQwXfpb> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page = this.baseMapper.selectPage(page, qw);
        IPage<TbQwXfpbAddAndEditDto> rPage = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        List<TbQwXfpb> list = page.getRecords();
        List<TbQwXfpbAddAndEditDto> rList = new ArrayList<>();
        list.forEach(item -> {
            TbQwXfpbAddAndEditDto entity = new TbQwXfpbAddAndEditDto();
            BeanUtils.copyProperties(item, entity);
            // 查询排班周期
            List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(
                    new LambdaQueryWrapper<TbQwXfpbZq>().eq(TbQwXfpbZq::getPbId, item.getId())
            );
            List<TbQwXfpbZqDto> zqDtoList = new ArrayList<>();
            zqList.forEach(zqItem -> {
                TbQwXfpbZqDto zqDto = new TbQwXfpbZqDto();
                BeanUtils.copyProperties(zqItem, zqDto);
                // 查询警力列表
                List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                        new LambdaQueryWrapper<TbQwJl>().eq(TbQwJl::getYwid, zqDto.getId())
                );
                zqDto.setJlList(jlList);
                // 查询车辆列表
                List<TbQwCl> clList = this.tbQwClMapper.selectList(
                        new LambdaQueryWrapper<TbQwCl>().eq(TbQwCl::getYwid, zqDto.getId())
                );
                zqDto.setClList(clList);
                // 查询通讯装备列表
                List<TbQwZnzb> znzbList = this.tbQwZnzbMapper.selectList(
                        new LambdaQueryWrapper<TbQwZnzb>().eq(TbQwZnzb::getYwid, zqDto.getId())
                );
                zqDto.setZnzbList(znzbList);
                // 查询警用器械列表
                List<TbQwJyqx> jyqxList = this.tbQwJyqxMapper.selectList(
                        new LambdaQueryWrapper<TbQwJyqx>().eq(TbQwJyqx::getYwid, zqDto.getId())
                );
                zqDto.setJyqxList(jyqxList);
                // 查询巡防范围
                List<TbQwXffw> xffwList = this.tbQwXffwMapper.selectList(
                        new LambdaQueryWrapper<TbQwXffw>().eq(TbQwXffw::getYwid, zqItem.getId())
                );
                List<TbQwXffwDto> xffwDtoList = new ArrayList<>();
                xffwList.forEach(x -> {
                    TbQwXffwDto d = new TbQwXffwDto();
                    BeanUtils.copyProperties(x, d);
                    xffwDtoList.add(d);
                });
                zqDto.setXffwList(xffwDtoList);
                zqDtoList.add(zqDto);
            });
            entity.setZqList(zqDtoList);
            rList.add(entity);
        });
        rPage.setRecords(rList);
        rPage.setTotal(page.getTotal());
        return rPage;
    }

    @Override
    public TbQwXfpbAddAndEditDto getInfo(String id) {
        TbQwXfpb item = this.baseMapper.selectById(id);
        if (item != null) {
            TbQwXfpbAddAndEditDto entity = new TbQwXfpbAddAndEditDto();
            BeanUtils.copyProperties(item, entity);
            // 查询排班周期
            List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(
                    new LambdaQueryWrapper<TbQwXfpbZq>().eq(TbQwXfpbZq::getPbId, item.getId())
            );
            List<TbQwXfpbZqDto> zqDtoList = new ArrayList<>();
            zqList.forEach(zqItem -> {
                TbQwXfpbZqDto zqDto = new TbQwXfpbZqDto();
                BeanUtils.copyProperties(zqItem, zqDto);
                // 查询警力列表
                List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                        new LambdaQueryWrapper<TbQwJl>().eq(TbQwJl::getYwid, zqDto.getId())
                );
                zqDto.setJlList(jlList);
                // 查询车辆列表
                List<TbQwCl> clList = this.tbQwClMapper.selectList(
                        new LambdaQueryWrapper<TbQwCl>().eq(TbQwCl::getYwid, zqDto.getId())
                );
                zqDto.setClList(clList);
                // 查询通讯装备列表
                List<TbQwZnzb> znzbList = this.tbQwZnzbMapper.selectList(
                        new LambdaQueryWrapper<TbQwZnzb>().eq(TbQwZnzb::getYwid, zqDto.getId())
                );
                zqDto.setZnzbList(znzbList);
                // 查询警用器械列表
                List<TbQwJyqx> jyqxList = this.tbQwJyqxMapper.selectList(
                        new LambdaQueryWrapper<TbQwJyqx>().eq(TbQwJyqx::getYwid, zqDto.getId())
                );
                zqDto.setJyqxList(jyqxList);
                // 查询巡防范围
                List<TbQwXffw> xffwList = this.tbQwXffwMapper.selectList(
                        new LambdaQueryWrapper<TbQwXffw>().eq(TbQwXffw::getYwid, zqItem.getId())
                );
                List<TbQwXffwDto> xffwDtoList = new ArrayList<>();
                xffwList.forEach(x -> {
                    TbQwXffwDto d = new TbQwXffwDto();
                    BeanUtils.copyProperties(x, d);
                    xffwDtoList.add(d);
                });
                zqDto.setXffwList(xffwDtoList);
                zqDtoList.add(zqDto);
            });
            entity.setZqList(zqDtoList);
            return entity;
        }
        return null;
    }

    @Override
    @Transactional
    public IPage<TbQwXfpbAddAndEditDto> getMyXfpb(TbQwXfpbSearchMyQuery dto) {
        IPage<TbQwXfpbAddAndEditDto> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = UserInfoManager.get();
        map.put("dto", dto);
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("ryid", String.valueOf(userInfo.getUserId()));
        int count = this.baseMapper.getCount(map);
        List<TbQwXfpb> list = this.baseMapper.getList(map);
        List<TbQwXfpbAddAndEditDto> rList = new ArrayList<>();
        list.forEach(item -> {
            TbQwXfpbAddAndEditDto entity = new TbQwXfpbAddAndEditDto();
            BeanUtils.copyProperties(item, entity);
            // 查询排班周期
            List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(
                    new LambdaQueryWrapper<TbQwXfpbZq>().eq(TbQwXfpbZq::getPbId, item.getId())
            );
            List<TbQwXfpbZqDto> zqDtoList = new ArrayList<>();
            zqList.forEach(zqItem -> {
                TbQwXfpbZqDto zqDto = new TbQwXfpbZqDto();
                BeanUtils.copyProperties(zqItem, zqDto);
                // 查询警力列表
                List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                        new LambdaQueryWrapper<TbQwJl>().eq(TbQwJl::getYwid, zqDto.getId())
                );
                zqDto.setJlList(jlList);
                // 查询车辆列表
                List<TbQwCl> clList = this.tbQwClMapper.selectList(
                        new LambdaQueryWrapper<TbQwCl>().eq(TbQwCl::getYwid, zqDto.getId())
                );
                zqDto.setClList(clList);
                // 查询通讯装备列表
                List<TbQwZnzb> znzbList = this.tbQwZnzbMapper.selectList(
                        new LambdaQueryWrapper<TbQwZnzb>().eq(TbQwZnzb::getYwid, zqDto.getId())
                );
                zqDto.setZnzbList(znzbList);
                // 查询警用器械列表
                List<TbQwJyqx> jyqxList = this.tbQwJyqxMapper.selectList(
                        new LambdaQueryWrapper<TbQwJyqx>().eq(TbQwJyqx::getYwid, zqDto.getId())
                );
                zqDto.setJyqxList(jyqxList);
                // 查询巡防范围
                List<TbQwXffw> xffwList = this.tbQwXffwMapper.selectList(
                        new LambdaQueryWrapper<TbQwXffw>().eq(TbQwXffw::getYwid, item.getId())
                );
                List<TbQwXffwDto> xffwDtoList = new ArrayList<>();
                xffwList.forEach(x -> {
                    TbQwXffwDto d = new TbQwXffwDto();
                    BeanUtils.copyProperties(x, d);
                    xffwDtoList.add(d);
                });
                zqDto.setXffwList(xffwDtoList);
                zqDtoList.add(zqDto);
            });
            entity.setZqList(zqDtoList);
            rList.add(entity);
        });
        page.setTotal(count);
        page.setRecords(rList);
        return page;
    }

    @Override
    public void checkThisTimeXfpb() {
        List<TbQwXfpbMrjl> list = this.baseMapper.checkThisTimeXfpb();
        TbRwTaskDto task = new TbRwTaskDto();
        List<TbRwTaskUserDto> userDtoList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach(item -> {
                // 查询是否发送消息，如果发送则无需发送了
                TbRwTaskByYwidQuery query = new TbRwTaskByYwidQuery();
                query.setYwid(item.getId());
                query.setRwxl("03");
                TbRwTask temp = this.tbRwzxAdaptRemoteService.getRwByYwid(query);
                if (temp == null) {
                    // 判断本次排班是否报备,如果没有报备就不需要提醒了
                    int count = this.tbQwXfbbMapper.selectCount(
                            new LambdaQueryWrapper<TbQwXfbb>()
                                    .eq(TbQwXfbb::getXfpbId, item.getPbId())
                                    .eq(TbQwXfbb::getBbzt, "0")
                                    .eq(TbQwXfbb::getXfrq, new Date())
                    );
                    TbQwXfpbZq zq = this.tbQwXfpbZqMapper.selectById(item.getPbzqId());
                    if (count == 0) {
                        // 需要发出提醒
                        TbRwTaskUserDto itemDto = new TbRwTaskUserDto();
                        itemDto.setRwzflx("1");
                        itemDto.setJsrid(zq.getFzrId());
                        itemDto.setJsrmc(zq.getFzrXm());
                        itemDto.setJsrsfzh(zq.getFzrSfzh());
                        itemDto.setJsrlxdh(zq.getFzrLxdh());
                        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(zq.getFzrId());
                        if (dept != null) {
                            itemDto.setSsbm(dept.getDeptname());
                            itemDto.setSsbmid(dept.getDeptid());
                        }
                        userDtoList.add(itemDto);
                        List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                                new LambdaQueryWrapper<TbQwJl>()
                                        .eq(TbQwJl::getYwid, item.getPbzqId())
                                        .eq(TbQwJl::getJllx, "01")
                        );
                        jlList.forEach(jl -> {
                            TbRwTaskUserDto itemDtos = new TbRwTaskUserDto();
                            itemDtos.setRwzflx("1");
                            itemDtos.setJsrid(jl.getJlId());
                            itemDtos.setJsrmc(jl.getJlxm());
                            itemDtos.setJsrsfzh(jl.getSfzh());
                            itemDtos.setJsrlxdh(jl.getLxdh());
                            DeptInfoVo deptVo = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(jl.getJlId());
                            if (deptVo != null) {
                                itemDtos.setSsbm(deptVo.getDeptname());
                                itemDtos.setSsbmid(deptVo.getDeptid());
                            }
                            // 判断重复数据
                            List<TbRwTaskUserDto> tempList = userDtoList.stream().filter(t -> t.getJsrid().equals(jl.getJlId())).collect(Collectors.toList());
                            if (tempList.size() == 0) {
                                userDtoList.add(itemDtos);
                            }
                        });
                    }
                    if (userDtoList.size() > 0) {
                        task.setSsbmid(zq.getSsbmid());
                        task.setSsbmdm(zq.getSsbmdm());
                        task.setRwmc("巡防报备提醒");
                        task.setRwnr("根据巡防排班安排，请您于" + new SimpleDateFormat("HH:mm").format(zq.getKssj()) + "前，" +
                                "进行巡防报备！！");
                        task.setRwjsdx("01");
                        task.setRwlx("2");
                        task.setRwxl("03");
                        task.setRwjjcd("3");
                        task.setRwms("1");
                        task.setSfaqwc("1");
                        task.setCjrid("-1");
                        task.setCjrxm("系统");
                        task.setCjrlxdh("");
                        Date sj;
                        // 跨天
                        if (zq.getJssj().getTime() <= zq.getKssj().getTime()) {
                            sj = DateUtils.getNextDate(
                                    DateUtils.strToDate(
                                            DateUtils.getQueryDateString(
                                                    DateUtils.getNextDate(new Date(), "D", +1), "01") + " " +
                                                    DateUtils.getQueryDateString(zq.getJssj(), "10"), "02"
                                    ), "H", +2
                            );
                        } else {
                            sj = DateUtils.getNextDate(
                                    DateUtils.strToDate(
                                            DateUtils.getQueryDateString(new Date(), "01") + " " +
                                                    DateUtils.getQueryDateString(zq.getJssj(), "10"), "02"
                                    ), "H", +2
                            );
                        }
                        task.setRwyqwcsj(sj);
                        task.setYwid(item.getId());
                        task.setUserDtoList(userDtoList);
                        this.tbRwzxAdaptRemoteService.addRw(task);
                    }
                }
            });
        }
    }

    @Override
    public TbQwXfpbZqMyVo getPbZq(String id, String time) {
        TbQwXfpbZq zqItem = this.tbQwXfpbZqMapper.selectById(id);
        if (zqItem == null) {
            return null;
        }
        TbQwXfpbZqMyVo zqDto = new TbQwXfpbZqMyVo();
        BeanUtils.copyProperties(zqItem, zqDto);
        // 查询警力列表
        List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                new LambdaQueryWrapper<TbQwJl>().eq(TbQwJl::getYwid, zqDto.getId())
        );
        zqDto.setJlList(jlList);
        // 查询车辆列表
        List<TbQwCl> clList = this.tbQwClMapper.selectList(
                new LambdaQueryWrapper<TbQwCl>().eq(TbQwCl::getYwid, zqDto.getId())
        );
        zqDto.setClList(clList);
        // 查询通讯装备列表
        List<TbQwZnzb> znzbList = this.tbQwZnzbMapper.selectList(
                new LambdaQueryWrapper<TbQwZnzb>().eq(TbQwZnzb::getYwid, zqDto.getId())
        );
        zqDto.setZnzbList(znzbList);
        // 查询警用器械列表
        List<TbQwJyqx> jyqxList = this.tbQwJyqxMapper.selectList(
                new LambdaQueryWrapper<TbQwJyqx>().eq(TbQwJyqx::getYwid, zqDto.getId())
        );
        zqDto.setJyqxList(jyqxList);
        // 查询每日警力（获取每日警力ID完成任务）
        TbQwXfpbMrjl mrjl = this.tbQwXfpbMrjlMapper.selectOne(
                new LambdaQueryWrapper<TbQwXfpbMrjl>()
                        .eq(TbQwXfpbMrjl::getPbzqId, zqDto.getId())
                        .eq(TbQwXfpbMrjl::getXfrq, time)
                        .last(" limit 1")
        );
        if (mrjl != null) {
            zqDto.setMrjlid(mrjl.getId());
        }
        return zqDto;
    }

    @Override
    public void addMrjl() {
        // 查询巡防排班信息
        List<TbQwXfpb> pbList = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbQwXfpb>()
                        .eq(TbQwXfpb::getXtSjzt, "1")
                        .eq(TbQwXfpb::getJsrqlx, "0")
        );
        if (!CollectionUtils.isEmpty(pbList)) {
            pbList.forEach(pb -> {
                List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(
                        new LambdaQueryWrapper<TbQwXfpbZq>()
                                .eq(TbQwXfpbZq::getPbId, pb.getId())
                                .eq(TbQwXfpbZq::getXtSjzt, "1")
                );
                zqList.forEach(zq -> {
                    // 获取本年的第一天
                    Date firstDay = DateUtils.strToDate(DateUtils.getQueryDateString(new Date(), "13") + "-01-01", "01");
                    pb.setPbksrq(firstDay);
                    // 获取本年最后一天的数据
                    Date lastDay = DateUtils.strToDate(DateUtils.getQueryDateString(new Date(), "13") + "-12-31", "01");
                    if (lastDay.getTime() >= pb.getPbjsrq().getTime()) {
                        lastDay = pb.getPbjsrq();
                    }
                    pb.setPbjsrq(lastDay);
                    this.setXfpbMrjlOther(pb, zq);
                });
            });
        }
    }


    @Override
    public List<Map<String, Object>> getPbbbByMonthBm(String time, String ssbmdm) {
        if (StringUtils.isBlank(ssbmdm)) {
            UserInfo user = UserInfoManager.get();
            ssbmdm = user.getDeptCode();
        }
        Date kssj = DateUtils.strToDate(time + "-01", "01");
        Date jssj = DateUtils.getThisMonthLastDay(time);
        List<Map<String, Object>> rList = new ArrayList<>();
        ssbmdm = tbBaseAdaptRemoteService.getSsbm(ssbmdm, null);
        while (kssj.getTime() <= jssj.getTime()) {
            Map<String, Object> xfMap = new HashMap<>();
            xfMap.put("day", DateUtils.getQueryDateString(kssj, "01"));
            QueryWrapper<TbQwXfpb> tb = new QueryWrapper<>();
            tb.lambda().likeRight(TbQwXfpb::getSsbmdm, ssbmdm);
            tb.lambda().last("and DATE_FORMAT('" + DateUtils.getQueryDateString(kssj, "01") + "', '%Y-%m-%d') <= pbjsrq  AND DATE_FORMAT( '" + DateUtils.getQueryDateString(kssj, "01") + "', '%Y-%m-%d' ) >= pbksrq ");
            List<TbQwXfpb> tbQwXfpbs = this.baseMapper.selectList(tb);
            xfMap.put("tbQwXfpbs", tbQwXfpbs);
            xfMap.put("pbs", tbQwXfpbs.size());
            Set<String> mjSet = new HashSet<>();
            Set<String> fjSet = new HashSet<>();
            if (!CollectionUtils.isEmpty(tbQwXfpbs)) {
                for (TbQwXfpb pb : tbQwXfpbs) {
                    List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(new LambdaQueryWrapper<TbQwXfpbZq>().eq(TbQwXfpbZq::getPbId, pb.getId()));
                    if (!CollectionUtils.isEmpty(zqList)) {
                        for (TbQwXfpbZq zb : zqList) {
                            String pbmj = zb.getPbmj();
                            if (StringUtils.isNotBlank(pbmj)) {
                                List<TbQwJl> mjList = JSONObject.parseArray(pbmj, TbQwJl.class);
                                mjList.forEach(v -> {
                                    mjSet.add(v.getSfzh());
                                });
                            }
                            String pbfj = zb.getPbfj();
                            if (StringUtils.isNotBlank(pbfj)) {
                                List<TbQwJl> mjList = JSONObject.parseArray(pbfj, TbQwJl.class);
                                mjList.forEach(v -> {
                                    fjSet.add(v.getSfzh());
                                });
                            }
                        }
                    }
                }
            }
            xfMap.put("mjSet", mjSet.size());
            xfMap.put("fjSet", mjSet.size());
            rList.add(xfMap);
            kssj = DateUtils.getNextDate(kssj, "D", +1);
        }
        return rList;
    }

    /**
     * zt: 01.已排班 02.报备中 03.已报备 04.请假
     *
     * @param time
     * @return
     */
    @Override
    public List<Map<String, Object>> getPbbbByMonth(String time) {
        UserInfo user = UserInfoManager.get();

        String userId = String.valueOf(user.getUserId());
        List<Map<String, Object>> rList = new ArrayList<>();
        Date kssj = DateUtils.strToDate(time + "-01", "01");
        Date jssj = DateUtils.getThisMonthLastDay(time);
        while (kssj.getTime() <= jssj.getTime()) {
            // 查询排班情况
            List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.getMyXfpbByTime(kssj, userId);
            Map<String, Object> map = new HashMap<>();
            map.put("day", DateUtils.getQueryDateString(kssj, "12"));
            List<Map<String, Object>> dayList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(zqList)) {
                Date finalKssj = kssj;
                List<Map<String, Object>> finalDayList = dayList;
                zqList.forEach(zq -> {
                    Map<String, Object> dayMap = new HashMap<>();
                    dayMap.put("zt", "01");
                    dayMap.put("time", DateUtils.getQueryDateString(zq.getKssj(), "09") + "-"
                            + DateUtils.getQueryDateString(zq.getJssj(), "09"));
                    dayMap.put("id", zq.getId());
                    // 查询是否报备，如果报备，则覆盖排班信息，改为报备信息
                    TbQwXfbb xfbb = this.tbQwXfbbMapper.selectOne(
                            new LambdaQueryWrapper<TbQwXfbb>()
                                    .eq(TbQwXfbb::getXfpbId, zq.getId())
                                    .eq(TbQwXfbb::getXfrq, finalKssj)
                                    .orderByDesc(TbQwXfbb::getBbkssj)
                                    .last(" limit 1")
                    );
                    if (xfbb != null) {
                        if ("0".equals(xfbb.getBbzt())) {
                            dayMap.put("zt", "02");
                            dayMap.put("time", DateUtils.getQueryDateString(xfbb.getBbkssj(), "09") + "-当前");
                            dayMap.put("id", xfbb.getId());
                        } else if ("1".equals(xfbb.getBbzt())) {
                            dayMap.put("zt", "03");
                            dayMap.put("time", DateUtils.getQueryDateString(xfbb.getBbkssj(), "09") + "-" +
                                    DateUtils.getQueryDateString(xfbb.getBbjssj(), "09"));
                            dayMap.put("id", xfbb.getId());
                        }
                    }
                    finalDayList.add(dayMap);
                });
            }
            // 查询其他的报备信息
            List<TbQwXfbb> bbList = this.tbQwXfbbMapper.getMybbTodayByTime(String.valueOf(user.getUserId()),
                    null, DateUtils.getQueryDateString(kssj, "01"));
            for (TbQwXfbb item : bbList) {
                Map<String, Object> dayMap = new HashMap<>();
                dayMap.put("zt", "0".equals(item.getBbzt()) ? "02" : "03");
                dayMap.put("time", DateUtils.getQueryDateString(item.getKssj(), "09") + "-"
                        + DateUtils.getQueryDateString(item.getJssj(), "09"));
                dayMap.put("id", item.getId());
                dayList.add(dayMap);
            }
            // 查询请休假信息
            TbQwQxj qxj = this.tbQwQxjMapper.selectOne(
                    new LambdaQueryWrapper<TbQwQxj>()
                            .eq(TbQwQxj::getSqrId, userId)
                            .le(TbQwQxj::getKssj, kssj)
                            .ge(TbQwQxj::getJssj, kssj)
                            .last(" limit 1")
            );
            if (qxj != null) {
                Map<String, Object> dayMap = new HashMap<>();
                dayMap.put("zt", "04");
                dayMap.put("time", "00:00-23:59");
                dayList = new ArrayList<>();
                dayList.add(dayMap);
            }
            map.put("list", dayList);
            rList.add(map);
            kssj = DateUtils.getNextDate(kssj, "D", +1);
        }
        return rList;
    }

    @Override
    public List<Map<String, Object>> getXfbbByMonth(String time) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录！");
        }
        String ssbmdm = String.valueOf(user.getDeptCode());
        List<Map<String, Object>> rList = new ArrayList<>();
        Date kssj = DateUtils.strToDate(time + "-01", "01");
        Date jssj = DateUtils.getThisMonthLastDay(time);
        while (kssj.getTime() <= jssj.getTime()) {
            // 查询排班情况
            Date now = DateUtils.strToDate(DateUtils.getQueryDateString(new Date(), "01"), "01");
            Map<String, Object> map = new HashMap<>();
            map.put("time", DateUtils.getQueryDateString(kssj, "01"));
            // 过去,有值班展示值班信息，没有就不展示
            if (now.getTime() > kssj.getTime()) {
                List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                        new LambdaQueryWrapper<TbQwXfbb>()
                                .eq(TbQwXfbb::getXfrq, kssj)
                                .eq(TbQwXfbb::getXtSjzt, "1")
                                .eq(TbQwXfbb::getSsbmdm, ssbmdm)
                );
                if (bbList != null && bbList.size() != 0) {
                    map.put("type", "01");
                    map.put("list", bbList);
                } else {
                    map.put("type", "00");
                }
                // 当天，有报备展示报备，没有报备展示排班
            } else if (now.getTime() == kssj.getTime()) {
                List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                        new LambdaQueryWrapper<TbQwXfbb>()
                                .eq(TbQwXfbb::getXfrq, kssj)
                                .eq(TbQwXfbb::getXtSjzt, "1")
                                .eq(TbQwXfbb::getSsbmdm, ssbmdm)
                );
                if (bbList != null && bbList.size() != 0) {
                    map.put("type", "02");
                    map.put("list", bbList);
                } else {
                    List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.getDeptByMonth(kssj, ssbmdm);
                    if (zqList != null && zqList.size() > 0) {
                        map.put("type", "03");
                        map.put("list", zqList);
                    } else {
                        map.put("type", "04");
                    }
                }
            } else {
                List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.getDeptByMonth(kssj, ssbmdm);
                if (zqList != null && zqList.size() > 0) {
                    map.put("type", "05");
                    map.put("list", zqList);
                } else {
                    map.put("type", "06");
                }
            }
            rList.add(map);
            kssj = DateUtils.getNextDate(kssj, "D", +1);
        }
        return rList;
    }

    @Override
    public TbQwXfpbZqMyVo getMyXfpbToday() {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("登录异常，请重新登录");
        }
        return this.tbQwXfpbZqMapper.getMyXfpbToday(String.valueOf(user.getUserId()));
    }

    @Override
    public IPage<TbQwXfpbZqVo> getThisMonthPbList(TbQwXzSearchDto dto) {
        IPage<TbQwXfpbMrjl> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = this.tbQwXfpbMrjlMapper.selectPage(page,
                new LambdaQueryWrapper<TbQwXfpbMrjl>()
                        .last(" where DATE_FORMAT(xfrq,'%y-%m') = DATE_FORMAT(now(),'%y-%m') order by xfrq desc")
        );
        IPage<TbQwXfpbZqVo> resPage = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<TbQwXfpbMrjl> zqList = page.getRecords();
        List<TbQwXfpbZqVo> resList = new ArrayList<>();
        zqList.forEach(item -> {
            // 根据执勤周期Id查询执勤周期信息
            TbQwXfpbZq zq = this.tbQwXfpbZqMapper.selectById(item.getPbzqId());
            TbQwXfpbZqVo vo = new TbQwXfpbZqVo();
            BeanUtils.copyProperties(zq, vo);
            vo.setXfrq(item.getXfrq());
            resList.add(vo);
        });
        resPage.setRecords(resList);
        resPage.setTotal(page.getTotal());
        return resPage;
    }

    // 删除排班表中的数据
    private void deleteXfpb(String id) {
        List<TbQwXfpbZq> zqList = this.tbQwXfpbZqMapper.selectList(
                new LambdaQueryWrapper<TbQwXfpbZq>()
                        .eq(TbQwXfpbZq::getPbId, id)
        );
        if (!CollectionUtils.isEmpty(zqList)) {
            zqList.forEach(zq -> {
                // 删除警力信息
                this.tbQwJlMapper.deleteByYwid(zq.getId());
                // 删除车辆信息
                this.tbQwClMapper.deleteByYwid(zq.getId());
                // 删除警用器械
                this.tbQwJyqxMapper.deleteByYwid(zq.getId());
                // 删除智能装备
                this.tbQwZnzbMapper.deleteByYwid(zq.getId());
                // 删除每日警力数据
                this.tbQwXfpbMrjlMapper.deleteByYwid(id, zq.getId());
                // 删除巡防范围
                this.tbQwXffwMapper.deleteByYwid(zq.getId());
            });
        }
        this.tbQwXfpbZqMapper.deleteByPbId(id);
    }

    // 保存周期表信息和其他信息
    private void setXfpbzq(TbQwXfpbAddAndEditDto dto, TbQwXfpb entity, DeptInfoVo dept, String pbid) {
        List<TbQwXfpbZqDto> zqList = dto.getZqList();
        if (!CollectionUtils.isEmpty(zqList)) {
            zqList.forEach(zqDto -> {
                TbQwXfpbZq zq = new TbQwXfpbZq();
                BeanUtils.copyProperties(zqDto, zq);
                // 保存每一个周期
                zq.setPbId(entity.getId());
                zq.setId(UUIDGenerator.getUUID());
                zq.setXtSjly("1");
                if (dept != null) {
                    zq.setSsbm(dept.getDeptname());
                    zq.setSsbmid(dept.getDeptid());
                    zq.setSsbmdm(dept.getDeptcode());
                    zq.setSsxgajdm(dept.getFxjcode());
                    zq.setSsxgajid(dept.getFxjid());
                    zq.setSsxgaj(dept.getFxjname());
                    zq.setSssgaj(dept.getDszname());
                    zq.setSssgajdm(dept.getDszcode());
                    zq.setSssgajid(dept.getDszid());
                }
                // 保存警力
                List<TbQwJl> jlList = zqDto.getJlList();
                List<TbQwJl> mjList = new ArrayList<>(), fjList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(jlList)) {
                    for (TbQwJl jl : jlList) {
                        if ("01".equals(jl.getJllx())) {
                            mjList.add(jl);
                        } else if ("02".equals(jl.getJllx())) {
                            fjList.add(jl);
                        }
                        // 保存警力信息
                        jl.setId(UUIDGenerator.getUUID());
                        jl.setYwid(zq.getId());
                        jl.setZblx("2");
                        jl.setJlzt("1");
                        jl.setXtSjly("1");
                        if (dept != null) {
                            jl.setSsbm(dept.getDeptname());
                            jl.setSsbmid(dept.getDeptid());
                            jl.setSsbmdm(dept.getDeptcode());
                            jl.setSsxgajdm(dept.getFxjcode());
                            jl.setSsxgajid(dept.getFxjid());
                            jl.setSsxgaj(dept.getFxjname());
                            jl.setSssgaj(dept.getDszname());
                            jl.setSssgajdm(dept.getDszcode());
                            jl.setSssgajid(dept.getDszid());
                        }
                        this.tbQwJlMapper.insert(jl);
                    }
                }
                zq.setMjsl(mjList.size());
                zq.setFjsl(fjList.size());
                zq.setPbmj(JSONArray.toJSONString(mjList));
                zq.setPbfj(JSONArray.toJSONString(fjList));
                // 保存警车
                List<TbQwCl> clList = zqDto.getClList();
                // 车车巡步巡
                zq.setXlfs(clList.size() > 0 ? "0" : "1");
                if (!CollectionUtils.isEmpty(clList)) {
                    clList.forEach(cl -> {
                        cl.setYwid(zq.getId());
                        cl.setId(UUIDGenerator.getUUID());
                        cl.setXtSjly("1");
                        cl.setZblx("2");
                        if (dept != null) {
                            cl.setSsbm(dept.getDeptname());
                            cl.setSsbmid(dept.getDeptid());
                            cl.setSsbmdm(dept.getDeptcode());
                            cl.setSsxgajdm(dept.getFxjcode());
                            cl.setSsxgajid(dept.getFxjid());
                            cl.setSsxgaj(dept.getFxjname());
                            cl.setSssgaj(dept.getDszname());
                            cl.setSssgajdm(dept.getDszcode());
                            cl.setSssgajid(dept.getDszid());
                        }
                        this.tbQwClMapper.insert(cl);
                    });
                }
                zq.setPbcl(JSONArray.toJSONString(clList));
                zq.setJcsl(clList.size());
                // 智能装备
                List<TbQwZnzb> znzbList = zqDto.getZnzbList();
                if (!CollectionUtils.isEmpty(znzbList)) {
                    znzbList.forEach(znzb -> {
                        znzb.setYwid(zq.getId());
                        znzb.setId(UUIDGenerator.getUUID());
                        znzb.setXtSjly("1");
                        znzb.setZblx("2");
                        if (dept != null) {
                            znzb.setSsbm(dept.getDeptname());
                            znzb.setSsbmid(dept.getDeptid());
                            znzb.setSsbmdm(dept.getDeptcode());
                            znzb.setSsxgajdm(dept.getFxjcode());
                            znzb.setSsxgajid(dept.getFxjid());
                            znzb.setSsxgaj(dept.getFxjname());
                            znzb.setSssgaj(dept.getDszname());
                            znzb.setSssgajdm(dept.getDszcode());
                            znzb.setSssgajid(dept.getDszid());
                        }
                        this.tbQwZnzbMapper.insert(znzb);
                    });
                }
                zq.setTxzb(JSONArray.toJSONString(znzbList));
                zq.setTxzbsl(znzbList.size());
                // 警用器械
                List<TbQwJyqx> jyqxList = zqDto.getJyqxList();
                if (!CollectionUtils.isEmpty(jyqxList)) {
                    jyqxList.forEach(jyqx -> {
                        jyqx.setYwid(zq.getId());
                        jyqx.setId(UUIDGenerator.getUUID());
                        jyqx.setXtSjly("1");
                        jyqx.setZblx("2");
                        if (dept != null) {
                            jyqx.setSsbm(dept.getDeptname());
                            jyqx.setSsbmid(dept.getDeptid());
                            jyqx.setSsbmdm(dept.getDeptcode());
                            jyqx.setSsxgajdm(dept.getFxjcode());
                            jyqx.setSsxgajid(dept.getFxjid());
                            jyqx.setSsxgaj(dept.getFxjname());
                            jyqx.setSssgaj(dept.getDszname());
                            jyqx.setSssgajdm(dept.getDszcode());
                            jyqx.setSssgajid(dept.getDszid());
                        }
                        this.tbQwJyqxMapper.insert(jyqx);
                    });
                }
                // 保存巡防范围表的数据
                this.setXffw(zqDto, entity, zq, dept);
                this.tbQwXfpbZqMapper.insert(zq);
                zq.setJyqx(JSONArray.toJSONString(jyqxList));
                zq.setJyqxsl(jyqxList.size());
                // 保存时间段内的所有的警力数据
                List<String> jlIds = jlList.stream().map(TbQwJl::getJlId).collect(Collectors.toList());
                jlIds.add(zq.getFzrId());
                this.setXfpbMrjl(entity, zq, jlIds, pbid);
            });
        }
    }

    // 保存巡防范围表的数据
    private void setXffw(TbQwXfpbZqDto zqDto, TbQwXfpb entity, TbQwXfpbZq zq, DeptInfoVo dept) {
        List<TbQwXffwDto> fwList = zqDto.getXffwList();
        String xffwlx = (fwList != null && fwList.size() > 0) ? fwList.get(0).getXffwlx() : "";
        if (!CollectionUtils.isEmpty(fwList)) {
            fwList.forEach(item -> {
                if (!xffwlx.equals(item.getXffwlx())) {
                    throw new BusinessException("巡防范围类型只能选择一种！！");
                }
                TbQwXffw xffw = new TbQwXffw();
                xffw.setId(UUIDGenerator.getUUID());
                xffw.setYwid(zq.getId());
                xffw.setGlbid(item.getGlbid());
                xffw.setQwlx("1");
                xffw.setXffwlx(item.getXffwlx());
                xffw.setFwMc(item.getFwMc());
                if (dept != null) {
                    xffw.setSsbm(dept.getDeptname());
                    xffw.setSsbmid(dept.getDeptid());
                    xffw.setSsbmdm(dept.getDeptcode());
                    xffw.setSsxgajdm(dept.getFxjcode());
                    xffw.setSsxgajid(dept.getFxjid());
                    xffw.setSsxgaj(dept.getFxjname());
                    xffw.setSssgaj(dept.getDszname());
                    xffw.setSssgajdm(dept.getDszcode());
                    xffw.setSssgajid(dept.getDszid());
                }
                this.tbQwXffwMapper.insert(xffw);
            });
            zq.setXffwid(fwList.stream().map(TbQwXffwDto::getGlbid).collect(Collectors.joining(",")));
        }
    }

    // 保存时间段累的所有的警力的数据
    private void setXfpbMrjlOther(TbQwXfpb pb, TbQwXfpbZq zq) {
        Date kssj = DateUtils.getNextDate(pb.getPbksrq(), "D", zq.getXfzq() - 1);
        Date jssj = pb.getPbjsrq();
        int a = -1;
        while (kssj.getTime() <= jssj.getTime()) {
            a++;
            if (a % pb.getXhzq() != 0) {
                kssj = DateUtils.getNextDate(kssj, "D", +1);
                continue;
            }
            TbQwXfpbMrjl mrjl = new TbQwXfpbMrjl();
            mrjl.setPbId(pb.getId());
            mrjl.setPbzqId(zq.getId());
            String xfksskTime = DateUtils.getQueryDateString(kssj, "01") + " "
                    + DateUtils.getQueryDateString(zq.getKssj(), "10");
            mrjl.setXfkssj(DateUtils.strToDate(xfksskTime, "02"));
            // 判断排班的开始时间是否大于排班的结束时间，如果大于 那么巡防的结束时间需要加一天
            if (zq.getKssj().getTime() > zq.getJssj().getTime()) {
                Date tempTime = DateUtils.getNextDate(kssj, "D", +1);
                String xfjsskTime = DateUtils.getQueryDateString(tempTime, "01")
                        + " " + DateUtils.getQueryDateString(zq.getJssj(), "10");
                mrjl.setXfjssj(DateUtils.strToDate(xfjsskTime, "02"));
            } else {
                String xfjsskTime = DateUtils.getQueryDateString(kssj, "01")
                        + " " + DateUtils.getQueryDateString(zq.getJssj(), "10");
                mrjl.setXfjssj(DateUtils.strToDate(xfjsskTime, "02"));
            }
            mrjl.setXfrq(kssj);
            this.tbQwXfpbMrjlMapper.insert(mrjl);
            kssj = DateUtils.getNextDate(kssj, "D", +1);
        }
    }

    // 保存时间段内的所有的警力数据
    private void setXfpbMrjl(TbQwXfpb pb, TbQwXfpbZq zq, List<String> jlIds, String pbid) {
        Date kssj = DateUtils.getNextDate(pb.getPbksrq(), "D", zq.getXfzq() - 1);
        Date jssj = pb.getPbjsrq();
        if (kssj != null && jssj != null) {
            // 判断结束时间和开始时间的月份是否一样，如果一样，保存所有数据
            // 如果不一样暂时保存本月数据
            if (!new SimpleDateFormat("yyyy-MM").format(kssj)
                    .equals(new SimpleDateFormat("yyyy-MM").format(jssj))) {
                jssj = DateUtils.getThisMonthLastDay();
            }
            int a = -1;
            while (kssj.getTime() <= jssj.getTime()) {
                a++;
                if (a % pb.getXhzq() != 0) {
                    kssj = DateUtils.getNextDate(kssj, "D", +1);
                    continue;
                }
                TbQwXfpbMrjl mrjl = new TbQwXfpbMrjl();
                mrjl.setPbId(pb.getId());
                mrjl.setPbzqId(zq.getId());
                String xfksskTime = DateUtils.getQueryDateString(kssj, "01") + " " + DateUtils.getQueryDateString(zq.getKssj(), "10");
                mrjl.setXfkssj(DateUtils.strToDate(xfksskTime, "02"));
                // 判断排班的开始时间是否大于排班的结束时间，如果大于 那么巡防的结束时间需要加一天
                if (zq.getKssj().getTime() > zq.getJssj().getTime()) {
                    Date tempTime = DateUtils.getNextDate(kssj, "D", +1);
                    String xfjsskTime = DateUtils.getQueryDateString(tempTime, "01") + " " + DateUtils.getQueryDateString(zq.getJssj(), "10");
                    mrjl.setXfjssj(DateUtils.strToDate(xfjsskTime, "02"));
                } else {
                    String xfjsskTime = DateUtils.getQueryDateString(kssj, "01") + " " + DateUtils.getQueryDateString(zq.getJssj(), "10");
                    mrjl.setXfjssj(DateUtils.strToDate(xfjsskTime, "02"));
                }
                mrjl.setXfrq(kssj);
                // 判断时间是否重合，如果重合则抛出异常给前端
                this.checkTime(mrjl, jlIds, pbid);
                this.tbQwXfpbMrjlMapper.insert(mrjl);
                kssj = DateUtils.getNextDate(kssj, "D", +1);
            }
        }
    }

    private void checkTime(TbQwXfpbMrjl mrjl, List<String> jlIds, String pbid) {
        List<TbQwXfpbMrjl> mrjlList = this.tbQwXfpbMrjlMapper.getMrjlByTime(DateUtils.getQueryDateString(mrjl.getXfkssj(), "02"),
                DateUtils.getQueryDateString(mrjl.getXfjssj(), "02"), pbid);
        if (mrjlList != null && mrjlList.size() > 0) {
            mrjlList.forEach(m -> {
                TbQwXfpbZq zq = this.tbQwXfpbZqMapper.selectById(m.getPbzqId());
                if (zq != null) {
                    TbQwXfpb xfpb = this.baseMapper.selectById(zq.getPbId());
                    if (xfpb != null) {
                        if (jlIds.indexOf(zq.getFzrId()) != -1) {
                            throw new BusinessException(("负责人(" + zq.getFzrXm() + ")在" +
                                    "其他排班中时间冲突，冲突排班名称：" + xfpb.getPbmc()));
                        }
                        // 其他警力
                        List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                                new LambdaQueryWrapper<TbQwJl>()
                                        .eq(TbQwJl::getYwid, zq.getId())
                                        .eq(TbQwJl::getXtSjzt, "1")
                        );
                        jlList.forEach(jl -> {
                            if (jlIds.indexOf(jl.getJlId()) != -1) {
                                throw new BusinessException(("01".equals(jl.getJllx()) ? "民警" : "辅警") + "(" + jl.getJlxm() + ")在" +
                                        "其他排班中时间冲突，冲突排班名称：" + xfpb.getPbmc());
                            }
                        });
                    }
                }
            });
        }
    }
}
