package com.mosty.qwzx.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.jcgl.TbJcglKfdDto;
import com.mosty.base.model.dto.jcgl.TbJcglXfqyDto;
import com.mosty.base.model.dto.qwzx.*;
import com.mosty.base.model.dto.websocket.WebSocketObject;
import com.mosty.base.model.entity.jcgl.TbJcglBxd;
import com.mosty.base.model.entity.jcgl.TbJcglJwz;
import com.mosty.base.model.entity.lzother.BphJlxx;
import com.mosty.base.model.entity.qwzx.*;
import com.mosty.base.model.entity.wzzx.TbWzLswz;
import com.mosty.base.model.entity.wzzx.TbWzSblswz;
import com.mosty.base.model.entity.wzzx.TbWzXfwz;
import com.mosty.base.model.query.qwzx.TbQwJmxzSearchDto;
import com.mosty.base.model.query.qwzx.TbQwXfbbJmxzQuery;
import com.mosty.base.model.query.qwzx.TbQwXfbbQuery;
import com.mosty.base.model.query.qwzx.TbQwxfbbDkQuery;
import com.mosty.base.model.query.sjzx.XfbbQuery;
import com.mosty.base.model.query.sjzx.XfbbTjQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.qwzx.TbQwxfbbDkVO;
import com.mosty.base.model.vo.yszx.TbYsGajgVo;
import com.mosty.base.utils.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.qwzx.mapper.*;
import com.mosty.qwzx.remote.*;
import com.mosty.qwzx.service.TbQwXfbbService;
import com.vividsolutions.jts.algorithm.PointLocator;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.operation.buffer.BufferOp;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * <p>
 * 巡防报备表 服务实现类
 * </p>
 *
 * @author zengbo
 * @since 2022-06-27
 */
@AllArgsConstructor
@Service
public class TbQwXfbbServiceImpl extends ServiceImpl<TbQwXfbbMapper, TbQwXfbb> implements TbQwXfbbService {

    private final TbQwXfbbMapper tbQwXfbbMapper;
    private final TbQwJlMapper tbQwJlMapper;
    private final TbQwClMapper tbQwClMapper;
    private final TbQwZnzbMapper tbQwZnzbMapper;
    private final TbQwJyqxMapper tbQwJyqxMapper;
    private final TbYszxAdaptRemoteService tbYszxAdaptRemoteService;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbQwxfbbDkMapper tbQwxfbbDkMapper;
    private final TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private final RedisService redisService;
    private final TbQwXffwMapper tbQwXffwMapper;
    private final TbLzotherAdaptRemoteService tbLzotherAdaptRemoteService;
    private final TbWebSocketAdaptRemoteService tbWebSocketAdaptRemoteService;

    @Override
    public IPage<TbQwXfbbVo> queryList(TbQwXfbbQuery xfbb) {
//        UserInfo userInfo = UserInfoManager.get();
        IPage<TbQwXfbbVo> page = PageUtils.buildPage(xfbb.getPageSize(), xfbb.getPageCurrent());
//         tbQwXfbbMapper.queryList(page, xfbb, PermissionsUtil.createSql("a", userInfo));
        xfbb.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(xfbb.getSsbmdm(), null));
        return tbQwXfbbMapper.queryList(page, xfbb);

    }

    @Override
    public TbQwXfbbVo selectById(String id) {
        TbQwXfbbVo vo = new TbQwXfbbVo();
        TbQwXfbb xfbb = this.tbQwXfbbMapper.selectById(id);
        BeanUtils.copyProperties(xfbb, vo);
        List<TbQwJl> jlList = this.tbQwJlMapper.queryListByYwid(Collections.singletonList(id));
        List<TbQwCl> clList = this.tbQwClMapper.queryListByYwid(Collections.singletonList(id));
        List<TbQwZnzb> znzbList = this.tbQwZnzbMapper.queryListByYwid(Collections.singletonList(id));
        List<TbQwJyqx> jyqxList = this.tbQwJyqxMapper.queryListByYwid(Collections.singletonList(id));
        List<TbQwXffw> xffwList = this.tbQwXffwMapper.selectList(
                new LambdaQueryWrapper<TbQwXffw>()
                        .eq(TbQwXffw::getYwid, id)
                        .eq(TbQwXffw::getXtSjzt, "1")
        );
        if (!CollectionUtils.isEmpty(xffwList)) {
            List<TbQwXffwDto> xffwDtoList = new ArrayList<>();
            xffwList.forEach(item -> {
                TbQwXffwDto dto = new TbQwXffwDto();
                BeanUtils.copyProperties(item, dto);
                xffwDtoList.add(dto);
            });
            vo.setXffwList(xffwDtoList);
        }
        vo.setJlList(jlList);
        vo.setClList(clList);
        vo.setZnzbList(znzbList);
        vo.setJyqxList(jyqxList);
        return vo;
    }

    @Override
    public String addXfbb(TbQwXfbbVo xfbbVo) {
        if (StringUtils.isBlank(xfbbVo.getSsbmdm())) throw new BusinessException("请选择巡防部门！");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(xfbbVo.getSsbmdm());
        if (xfbbVo.getJd() == null || xfbbVo.getWd() == null) {
            xfbbVo.setJd(Constant.JD);
            xfbbVo.setWd(Constant.WD);
        }
        TbQwXfbb xfbb = new TbQwXfbb();
        BeanUtils.copyProperties(xfbbVo, xfbb);
        if (StringUtils.isBlank(xfbb.getBblx())) {
            xfbb.setBblx("01");
        }
        if (StringUtils.isBlank(xfbb.getQwlx())) {
            xfbb.setQwlx("00");
        }
        xfbb.setZb(JtsUtils.getPoint(xfbb.getJd(), xfbb.getWd()));
        xfbb.setZbhash(GeoHashKit.encode(xfbb.getJd(), xfbb.getWd()));
          if(StringUtils.isBlank(xfbb.getId())){
              xfbb.setId(UUIDGenerator.getUUID());
          }
        saveRelevanceData(xfbb, xfbbVo, xfbb.getId(), dept);
        xfbb.setXfbm(dept.getDeptname());
        xfbb.setXfbmid(dept.getDeptid());
        xfbb.setXfbmdm(dept.getDeptcode());
        xfbb.setSsbm(dept.getDeptname());
        xfbb.setSsbmid(dept.getDeptid());
        xfbb.setSsbmdm(dept.getDeptcode());
        xfbb.setSsxgajdm(dept.getFxjcode());
        xfbb.setSsxgajid(dept.getFxjid());
        xfbb.setSsxgaj(dept.getFxjname());
        xfbb.setSssgaj(dept.getDszname());
        xfbb.setSssgajdm(dept.getDszcode());
        xfbb.setSssgajid(dept.getDszid());
        xfbb.setXfsc(0);
        xfbb.setXflc(0);
        xfbb.setZbsj(new Date());
        xfbb.setXtSjly("2");
        tbQwXfbbMapper.insertEntity(xfbb);
        return xfbb.getId();
    }

    @Override
    public boolean deleteBatch(List<String> ids) {
        if (ids.size() > 0) {
            for (String id : ids) {
                deleteRelevanceData(id);
            }
            int rs = tbQwXfbbMapper.deleteXfbb(ids);
            return rs > 0;
        }
        return true;
    }

    @Override
    public boolean deleteById(String id) {
        deleteRelevanceData(id);
        List<String> ids = new ArrayList<>();
        ids.add(id);
        int rs = tbQwXfbbMapper.deleteXfbb(ids);
        return rs > 0;
    }

    @Override
    public Map<String, Integer> selectDeck() {
//        UserInfo userInfo = UserInfoManager.get();

        TbQwXzSearchDto dto = new TbQwXzSearchDto();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        // 查询街面巡组计划数
        Map<String, Object> mp = new HashMap<>();
        mp.put("dto", dto);
//        mp.put("useSql", PermissionsUtil.createSql("b", userInfo));
        Integer jhsl = tbQwXfbbMapper.selectJhsl(mp);
        // 查询街面巡组实际数量（已报备的数量）
        Integer sjsl = tbQwXfbbMapper.selectSjsl(mp);
        Map<String, Integer> map = tbQwXfbbMapper.selectPowerAndDayLength(dto.getSsbmdm());
        map.put("jhsl", jhsl);
        map.put("sjsl", sjsl);
        return map;
    }

    @Override
    public IPage<TbQwXfbb> selectDeckList(TbQwXfbbJmxzQuery dto) {
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        Map<String, Object> map = new HashMap<>();
        List<String> ztList = new ArrayList<>();
        List<String> qwList = new ArrayList<>();
        IPage<TbQwXfbb> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());

        if (StringUtils.isNotBlank(dto.getXfzt())) {
            ztList = Arrays.asList(dto.getXfzt().split(","));
        }
        if (StringUtils.isNotBlank(dto.getQwlx())) {
            qwList = Arrays.asList(dto.getQwlx().split(","));
        }
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
        map.put("list", ztList);
        map.put("qwList", qwList);
        int count = this.tbQwXfbbMapper.getCountZbxz(map);
        List<TbQwXfbb> list = this.tbQwXfbbMapper.getListZbxz(map);

        if (!CollectionUtils.isEmpty(list)) {
            for (TbQwXfbb xfbb : list) {
                if (StringUtils.isNotBlank(xfbb.getFzrSfzh())) {
                    SysUser user1 = this.tbBaseAdaptRemoteService.getUserOrFjInfoBySfzh(xfbb.getFzrSfzh());
                    xfbb.setLx(user1.getType());
                }
            }
        }
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<TbQwXfbb> selectNearbyDeck(TbQwXfbb tbQwXfbb) {
        return tbQwXfbbMapper.selectNearbyDeck(tbQwXfbb);
    }

    @Override
    public IPage<TbQwXfbbVo> queryPage(TbQwXfbbQuery xfbb) {
        IPage<TbQwXfbb> xfbbIPage = queryXfbb(xfbb);
        IPage<TbQwXfbbVo> voIPage = new Page<>(xfbb.getPageCurrent(), xfbb.getPageSize());
        voIPage.setTotal(xfbbIPage.getTotal());
        List<TbQwXfbb> records = xfbbIPage.getRecords();
        List<TbQwXfbbVo> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(records)) {
            List<String> ids = records.stream().map(TbQwXfbb::getId).collect(Collectors.toList());
            List<TbQwJl> jlList = tbQwJlMapper.queryListByYwid(ids);
            List<TbQwCl> clList = tbQwClMapper.queryListByYwid(ids);
            List<TbQwZnzb> znzbList = tbQwZnzbMapper.queryListByYwid(ids);
            List<TbQwJyqx> jyqxList = tbQwJyqxMapper.queryListByYwid(ids);
            List<TbQwXffw> xffwList = this.tbQwXffwMapper.selectList(
                    new LambdaQueryWrapper<TbQwXffw>()
                            .in(TbQwXffw::getYwid, ids)
                            .eq(TbQwXffw::getXtSjzt, "1")
            );
            for (TbQwXfbb record : records) {
                TbQwXfbbVo vo = new TbQwXfbbVo();
                BeanUtils.copyProperties(record, vo);
                List<TbQwJl> jl = jlList.stream().filter(item -> item.getYwid().equals(record.getId())).collect(Collectors.toList());
                List<TbQwCl> cl = clList.stream().filter(item -> item.getYwid().equals(record.getId())).collect(Collectors.toList());
                List<TbQwZnzb> znzb = znzbList.stream().filter(item -> item.getYwid().equals(record.getId())).collect(Collectors.toList());
                List<TbQwJyqx> jyqx = jyqxList.stream().filter(item -> item.getYwid().equals(record.getId())).collect(Collectors.toList());
                List<TbQwXffwDto> xffwDtoList = xffwList.stream().map(item -> {
                    TbQwXffwDto dto = new TbQwXffwDto();
                    BeanUtils.copyProperties(item, dto);
                    return dto;
                }).collect(Collectors.toList());
                vo.setXffwList(xffwDtoList);
                vo.setJlList(jl);
                vo.setClList(cl);
                vo.setZnzbList(znzb);
                vo.setJyqxList(jyqx);
                vos.add(vo);
            }
        }
        voIPage.setRecords(vos);
        return voIPage;
    }

    @Override
    public int startOrEndBb(TbQwXfbbStartOrEndBbDto dto) {
        TbQwXfbb bb = this.tbQwXfbbMapper.selectById(dto.getId());
        if (bb == null) return 0;
        if ("0".equals(dto.getBbzt())) {
            bb.setBbkssj(new Date());
            bb.setXfzt("0");
        } else {
            bb.setBbjssj(new Date());
            // 清除redis中缓存的巡防报备的位置
            String key = Constant.WZ_XFWZ + dto.getId();
            redisService.deleteObject(key);
            List<TbWzLswz> bbgj = tbQwXfbbMapper.getBbgj(bb.getId());
            if (!CollectionUtils.isEmpty(bbgj)) {
                int lc = 0;
                for (int i = 0; i < bbgj.size() - 1; i++) {
                    lc = DistanceUtils.getLc(lc, bbgj.get(i).getJd(), bbgj.get(i).getWd(), bbgj.get(i + 1).getJd(), bbgj.get(i + 1).getWd());
                }
                bb.setXflc(lc);
            }
        }
        bb.setBbzt(dto.getBbzt());
        bb.setBz("手动结束");
        this.tbQwXfbbMapper.updateById(bb);
        WebSocketObject obj;
        if (StringUtils.isNotBlank(bb.getFzrSfzh())) {
            SysUser user1 = this.tbBaseAdaptRemoteService.getUserOrFjInfoBySfzh(bb.getFzrSfzh());
            bb.setLx(user1.getType());
        }
        if ("1".equals(dto.getBbzt())) {
            // 将结束报备信息推送到前端
            obj = new WebSocketObject("05", bb, null);
            bb.setZb(null);
            this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
        } else if ("0".equals(dto.getBbzt())) {
            obj = new WebSocketObject("03", bb, null);
            bb.setZb(null);
            this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
        }
        return 1;
    }

    @Override
    public IPage<TbQwXfpbZq> selectJhjmxzList(TbQwXzSearchDto dto) {
//        UserInfo userInfo = UserInfoManager.get();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        IPage<TbQwXfpbZq> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageNum() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
//        String useSql = PermissionsUtil.createSql("b", userInfo);
//        map.put("useSql", useSql);
        // 查询街面巡组计划列表
        List<TbQwXfpbZq> list = this.tbQwXfbbMapper.selectJhslList(map);
        // 查询街面巡组计划数
        int count = this.tbQwXfbbMapper.selectJhsl(map);
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public IPage<TbQwXfbb> selectSjjmxzList(TbQwXzSearchDto dto) {
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
//        UserInfo userInfo = UserInfoManager.get();
        IPage<TbQwXfbb> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageNum() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
//        map.put("useSql", PermissionsUtil.createSql("b", userInfo));
        map.put("dto", dto);
        // 查询街面巡组计划列表
        List<TbQwXfbb> list = tbQwXfbbMapper.selectSjslList(map);
        // 查询街面巡组计划数
        int count = tbQwXfbbMapper.selectSjsl(map);
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public IPage<TbQwJl> selectJmllList(TbQwJmllSearchDto dto) {
//        UserInfo userInfo = UserInfoManager.get();
        dto.setXfbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getXfbmdm(), null));
        IPage<TbQwJl> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageNum() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
//        map.put("useSql", userInfo != null ? PermissionsUtil.createSql("a", userInfo) : "id");
        List<TbQwJl> list = this.tbQwJlMapper.getList(map);
        int count = this.tbQwJlMapper.getCount(map);
        page.setRecords(list);
        page.setTotal(count);
        return page;
    }

    @Override
    public TbQwXfbb getMybbTodayNew(String bblx) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("登录过期！！");
        }
//        if (StringUtils.isBlank(bblx)) {
//            bblx = "01";
//        }
        TbQwXfbb xfbb = this.tbQwXfbbMapper.getMybbTodayNew(String.valueOf(user.getIdEntityCard()), bblx);
        // 查询是否打卡
        if (xfbb != null) {
//            TbQwxfbbDk dk = this.tbQwxfbbDkMapper.selectOne(
//                    new LambdaQueryWrapper<TbQwxfbbDk>()
//                            .eq(TbQwxfbbDk::getBbid, xfbb.getId())
//                            .eq(TbQwxfbbDk::getXtSjzt, "1")
//            );
//            xfbb.setSfDk(dk != null);
            return xfbb;
        }
        return null;
    }

    @Override
    public TbQwXfbb getMybbLastBySfzh(String sfzh) {
        UserInfo user = UserInfoManager.get();
        String deptCode = user.getDeptCode();
        TbQwXfbb xfbb = this.baseMapper.selectOne(new LambdaQueryWrapper<TbQwXfbb>()
                .eq(TbQwXfbb::getFzrSfzh, sfzh)
                .eq(TbQwXfbb::getXtSjzt, "1")
                .eq(TbQwXfbb::getXtScbz, "0")
                .eq(StringUtils.isNotBlank(deptCode), TbQwXfbb::getSsbmdm, deptCode)
                .orderByDesc(TbQwXfbb::getBbkssj)
                .last(" limit 1")
        );
        if (!ObjectUtils.isEmpty(xfbb)) {
            xfbb.setZb(null);
            xfbb.setJd(null);
            xfbb.setWd(null);
            xfbb.setBbzt(null);
            xfbb.setBbjssj(null);
        }
        return xfbb;
    }

    @Override
    public List<TbQwXfbb> getFjbbByYsId(String ysid) {
        // 获取派出所的经纬度范围
        TbYsGajgVo pcs = this.tbYszxAdaptRemoteService.getInfo(ysid);
        // 查询所有的报备信息，在范围内的
        List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                new LambdaQueryWrapper<TbQwXfbb>()
                        .eq(TbQwXfbb::getXtSjzt, "1")
                        .eq(TbQwXfbb::getBbzt, "0")
        );
        List<TbQwXfbb> newList = new ArrayList<>();
        bbList.forEach(item -> {
            List<Coordinate> coorList = new ArrayList<>();
            pcs.getDtm().forEach(d -> {
                Coordinate coor = new Coordinate(d[0].doubleValue(), d[1].doubleValue());
                coorList.add(coor);
            });
            Coordinate[] coordinates = coorList.toArray(new Coordinate[0]);
            if (this.isInGeometry(coordinates, item.getJd() + "," + item.getWd())) {
                newList.add(item);
            }
        });
        return newList;
    }

    @Override
    public void authJsbbTs() {
        List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                new LambdaQueryWrapper<TbQwXfbb>()
                        .eq(TbQwXfbb::getBbzt, "0")
                        .eq(TbQwXfbb::getBblx, "02")
                        .eq(TbQwXfbb::getXtSjzt, "1")
        );
        if (!CollectionUtils.isEmpty(bbList)) {
            bbList.forEach(bb -> {
                bb.setBbzt("1");
                bb.setBbjssj(new Date());
                this.tbQwXfbbMapper.updateById(bb);
                // 清除redis中缓存的巡防报备的位置
                String key = Constant.WZ_XFWZ + bb.getId();
                redisService.deleteObject(key);
                //自动结束报备 ws通知前端
                WebSocketObject obj = new WebSocketObject("05", bb, null);
                bb.setZb(null);
                this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);

            });
        }
    }

    @Override
    public void authJsbb() {
        // 查询所有的已经报备的报备信息
        List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                new LambdaQueryWrapper<TbQwXfbb>()
                        .eq(TbQwXfbb::getBbzt, "0")
                        .eq(TbQwXfbb::getXtSjzt, "1")
        );
        // (使用remove容易出问题 所以使用list)
        List<TbQwXfbb> zxBbList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bbList)) {
            for (TbQwXfbb bb : bbList) {
                Date jssj;
                if (ObjectUtils.isNotEmpty(bb.getKssj()) && ObjectUtils.isNotEmpty(bb.getJssj())) {
                    if (bb.getKssj().getTime() > bb.getJssj().getTime()) {
                        String jssjString = DateUtils.getQueryDateString(
                                DateUtils.getNextDate(bb.getXfrq(), "D", +1), "01") + " "
                                + DateUtils.getQueryDateString(bb.getJssj(), "10");
                        jssj = DateUtils.strToDate(jssjString, "02");
                        System.out.println("--->>>>>>>>>>>>>>>>>>>>>" + jssjString);
                    } else {
                        String jssjString = DateUtils.getQueryDateString(bb.getXfrq(), "01") + " "
                                + DateUtils.getQueryDateString(bb.getJssj(), "10");
                        jssj = DateUtils.strToDate(jssjString, "02");
                        System.out.println("--->>>>>>>>>>>>>>>>>>>>>" + jssjString);
                    }
                    if (new Date().getTime() >= jssj.getTime()) {
                        bb.setBbzt("1");
                        bb.setBbjssj(new Date());
                        this.tbQwXfbbMapper.updateById(bb);
                        // 清除redis中缓存的巡防报备的位置
                        String key = Constant.WZ_XFWZ + bb.getId();
                        redisService.deleteObject(key);
                        //自动结束报备 ws通知前端
                        WebSocketObject obj = new WebSocketObject("05", bb, null);
                        bb.setZb(null);
                        this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
                    } else {
                        zxBbList.add(bb);
                    }
                } else {
                    zxBbList.add(bb);
                }
                //巡逻计算有问题  结束报备的时候 修改
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
                //获取报备轨迹 不使用fen
                List<TbWzLswz> bbgj = tbQwXfbbMapper.getBbgj(bb.getId());
                if (!CollectionUtils.isEmpty(bbgj)) {
                    int lc = 0;
                    for (int i = 0; i < bbgj.size() - 1; i++) {
                        lc = DistanceUtils.getLc(lc, bbgj.get(i).getJd(), bbgj.get(i).getWd(), bbgj.get(i + 1).getJd(), bbgj.get(i + 1).getWd());
                    }
                    tbQwXfbbMapper.update(new TbQwXfbb().setXflc(lc), new LambdaQueryWrapper<TbQwXfbb>().eq(TbQwXfbb::getId, bb.getId()));
                }
//                    }
//                }).start();
            }


        }
        if (!CollectionUtils.isEmpty(zxBbList)) {
            //三十分钟
            String lxsc = tbBaseAdaptRemoteService.getValue("XFBB_LXSC");
            long lxTime = (StringUtils.isEmpty(lxsc) ? 30 : Integer.parseInt(lxsc)) * 60;
            for (TbQwXfbb xfbb : zxBbList) {
                //已经是离线的就不在推送
                if (!xfbb.getXfzt().equals("2")) {
                    String key = Constant.WZ_XFWZ + xfbb.getId();
                    TbWzXfwz xfwz = redisService.getCacheObject(key);
                    if (ObjectUtils.isEmpty(xfwz)) {
                        //没有数据直接离线
                        xfbb.setXfzt("2");
                        this.tbQwXfbbMapper.updateById(xfbb);

                        if (StringUtils.isNotBlank(xfbb.getFzrSfzh())) {
                            SysUser user1 = this.tbBaseAdaptRemoteService.getUserOrFjInfoBySfzh(xfbb.getFzrSfzh());
                            xfbb.setLx(user1.getType());
                        }

                        WebSocketObject obj = new WebSocketObject("04", xfbb, null);
                        xfbb.setZb(null);
                        this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
                    } else {
                        //有数据
                        long l = (new Date().getTime() - xfwz.getZhgxsj().getTime()) / 1000;
                        //数据大于了三十分钟 直接离线
                        if (lxTime < l) {
                            xfbb.setXfzt("2");
                            this.tbQwXfbbMapper.updateById(xfbb);
                            if (StringUtils.isNotBlank(xfbb.getFzrSfzh())) {
                                SysUser user1 = this.tbBaseAdaptRemoteService.getUserOrFjInfoBySfzh(xfbb.getFzrSfzh());
                                xfbb.setLx(user1.getType());
                            }
                            WebSocketObject obj = new WebSocketObject("04", xfbb, null);
                            xfbb.setZb(null);
                            this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
                        }
                    }
                }
            }
        }


    }

    @Override
    public List<TbQwJlDto> getJlxxByBbid(String id) {
        TbQwXfbb bb = this.tbQwXfbbMapper.selectById(id);
        if (bb == null) {
            throw new BusinessException("报备信息不存在");
        }
        List<TbQwJlDto> list = new ArrayList<>();
        TbQwJlDto dto = new TbQwJlDto();
        dto.setJlId(bb.getFzrId());
        dto.setJllx("01");
        dto.setJlxm(bb.getFzrXm());
        dto.setSfzh(bb.getFzrSfzh());
        list.add(dto);
        List<TbQwJl> jlList = this.tbQwJlMapper.selectList(
                new LambdaQueryWrapper<TbQwJl>()
                        .eq(TbQwJl::getYwid, id)
                        .eq(TbQwJl::getXtSjzt, "1")
                        .eq(TbQwJl::getZblx, "3")
        );
        jlList.forEach(jl -> {
            TbQwJlDto vo = new TbQwJlDto();
            BeanUtils.copyProperties(jl, vo);
            list.add(vo);
        });
        return list;
    }

    @Override
    public TbQwXfbb getBbxxByJi(TbQwXfbbQueryByJlDto dto) {
        return this.tbQwXfbbMapper.getBbxxByJi(dto);
    }

    @Override
    public Map<String, Object> selectMfjCount(String bbrq) {
        Map<String, Object> map = new HashMap<>();
        // 如果查询时间为当天，则标志只查询报备中的数据
//        if (bbrq.equals(DateUtils.getQueryDateString(new Date(), "01"))) {
//            map.put("isToday", "1");
//        }
        TbQwXfbbJmxzQuery dto = new TbQwXfbbJmxzQuery();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        dto.setBbrq(bbrq);
        map.put("dto", dto);
//        UserInfo user = UserInfoManager.get();
//        map.put("useSql", PermissionsUtil.createSql("a", user));
        List<TbQwXfbb> list = this.tbQwXfbbMapper.getListZbxz(map);
        Map<String, Object> resMap = new HashMap<>();
        AtomicInteger mj = new AtomicInteger();
        AtomicInteger fj = new AtomicInteger();
        list.forEach(item -> {
            mj.addAndGet(item.getMjsl() == null ? 0 : item.getMjsl());
            fj.addAndGet(item.getFjsl() == null ? 0 : item.getFjsl());
        });
        resMap.put("mj", mj.intValue());
        resMap.put("fj", fj.intValue());
        return resMap;
    }

    @Override
    public List<TbQwXfbb> getBbList(String sbid) {
        return this.tbQwXfbbMapper.getBbList(sbid);
    }

    @Override
    public List<TbQwXfbb> getClBbList(String sbid) {
        return this.tbQwXfbbMapper.getClBbList(sbid);
    }

    @Override
    public IPage<TbQwXfbb> selectJmxz(TbQwJmxzSearchDto dto) {
        UserInfo user = UserInfoManager.get();
        if ("1".equals(dto.getType())) {
            return this.tbQwXfbbMapper.selectPage(
                    new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                    new LambdaQueryWrapper<TbQwXfbb>()
                            .eq(TbQwXfbb::getXtSjzt, "1")
                            .eq(TbQwXfbb::getBbzt, "0")
                            .like(StringUtils.isNotBlank(dto.getKeyword()), TbQwXfbb::getJzMc, dto.getKeyword())
                            .eq(TbQwXfbb::getSsbmid, String.valueOf(user.getDeptId()))
            );
        } else {
            return this.tbQwXfbbMapper.selectPage(
                    new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                    new LambdaQueryWrapper<TbQwXfbb>()
                            .eq(TbQwXfbb::getXtSjzt, "1")
                            .eq(TbQwXfbb::getBbzt, "0")
                            .and(StringUtils.isNotBlank(dto.getKeyword()),
                                    it -> it.like(TbQwXfbb::getJzMc, dto.getKeyword())
                                            .or()
                                            .like(TbQwXfbb::getSsbm, dto.getKeyword())
                            )
            );
        }
    }

    @Override
    public IPage<TbQwxfbbDkVO> selectXfbbDkPage(TbQwxfbbDkQuery query) {
        IPage<TbQwxfbbDk> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        if(StringUtils.isBlank(query.getSsbmdm())){
            UserInfo user = UserInfoManager.get();
            query.setSsbmdm(user.getDeptCode());
        }
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), Constant.DICT_ITEM_D_BZ_SF_YES));

        QueryWrapper<TbQwxfbbDk> qw = new QueryWrapper<>();
        qw.orderByDesc("xt_cjsj");
        qw.eq(StringUtils.isNotBlank(query.getBbid()), "bbid", query.getBbid());
        qw.eq(StringUtils.isNotBlank(query.getBxdid()), "bxdid", query.getBxdid());
        qw.eq(StringUtils.isNotBlank(query.getDkrxm()), "dkrxm", query.getDkrxm());
        qw.eq(StringUtils.isNotBlank(query.getDkrsfzh()), "dkrsfzh", query.getDkrsfzh());
        qw.likeRight("ssbmdm", query.getSsbmdm());

        //返回Page
        IPage<TbQwxfbbDkVO> resultPage = new Page<>(query.getPageCurrent(), query.getPageSize());

        //查询数据
        page = this.tbQwxfbbDkMapper.selectPage(page, qw);
        List<TbQwxfbbDk> list = page.getRecords();
        if(CollectionUtils.isEmpty(list)){
            return resultPage;
        }

        //转为VO
        List<TbQwxfbbDkVO> resultList = new ArrayList<>();
        for(TbQwxfbbDk entity : list){
            TbQwxfbbDkVO resultVO = BeanUtil.copyProperties(entity, TbQwxfbbDkVO.class);
            if(ObjectUtils.isNotEmpty(resultVO)){
                if(StringUtils.isNotBlank(resultVO.getBxdid())){
                    TbJcglBxd bxd = tbJcglAdaptRemoteService.getBxdById(resultVO.getBxdid());
                    if(ObjectUtils.isNotEmpty(bxd)){
                        resultVO.setBxdmc(bxd.getBxdMc());
                    }
                }
                resultList.add(resultVO);
            }
        }

        //组装VO返回
        resultPage.setRecords(resultList);
        resultPage.setTotal(page.getTotal());
        return resultPage;
    }

    @Override
    public void addXfbbDk(TbQwXfbbDkDto dto) {
        UserInfo user = UserInfoManager.get();

        TbQwxfbbDk dk = new TbQwxfbbDk();
        BeanUtils.copyProperties(dto, dk);
        dk.setDkrid(String.valueOf(user.getUserId()));
        dk.setDkrsfzh(user.getIdEntityCard());
        dk.setDkrxm(user.getUserName());
        dk.setSsbm(user.getDeptName());
        dk.setSsbmdm(user.getDeptCode());
        dk.setSsxgaj(dk.getSsxgaj());
        dk.setSsxgajdm(dk.getSsxgajdm());
        dk.setSssgaj(dk.getSssgaj());
        dk.setSssgajdm(dk.getSssgajdm());
        this.tbQwxfbbDkMapper.insert(dk);
    }

    @Override
    public Integer selectXfbbDkCount(String ssbmdm, String isChild) {
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm, isChild);
        QueryWrapper<TbQwxfbbDk> qw = new QueryWrapper<>();
        qw.likeRight("ssbmdm", ssbm);
        qw.ge("xt_cjsj", DateUtils.strToDate(DateUtils.getNowDate() + " 00:00:00", "02"));
        qw.le("xt_cjsj", DateUtils.strToDate(DateUtils.getNowDate() + " 23:59:59", "02"));
        return this.tbQwxfbbDkMapper.selectCount(qw);
    }

    @Override
    public boolean isDdWz(TbQwXfbbDkWzDto dto) {
        TbQwXfbb bb = this.tbQwXfbbMapper.selectById(dto.getBbid());
        if (bb == null || StringUtils.isBlank(bb.getXffwlx()) || StringUtils.isBlank(bb.getXffwid())) {
            return false;
        }
        List<BigDecimal[]> list;
        if ("1".equals(bb.getXffwlx())) {
            // 巡防区
            TbJcglXfqyDto xfqy = this.tbJcglAdaptRemoteService.getxfqById(bb.getXffwid());
            if (CollectionUtils.isEmpty(xfqy.getPgis())) return false;
            list = xfqy.getPgis();
            Coordinate[] coors = new Coordinate[list.size()];
            for (int i = 0; i < xfqy.getPgis().size(); i++) {
                Coordinate c = new Coordinate();
                c.x = xfqy.getPgis().get(i)[0].doubleValue();
                c.y = xfqy.getPgis().get(i)[1].doubleValue();
                coors[i] = c;
            }
            return this.isInGeometry(coors, dto.getJd() + "," + dto.getWd());
        } else if ("2".equals(bb.getXffwlx())) {
            // 快反点
            TbJcglKfdDto kfd = this.tbJcglAdaptRemoteService.getKfdById(bb.getXffwid());
            if (CollectionUtils.isEmpty(kfd.getWfzfw()) && CollectionUtils.isEmpty(kfd.getSfzfw())
                    && CollectionUtils.isEmpty(kfd.getYfzfw())) {
                return false;
            }
            list = kfd.getWfzfw();
            if (CollectionUtils.isEmpty(list)) {
                list = kfd.getSfzfw();
            }
            if (CollectionUtils.isEmpty(list)) {
                list = kfd.getYfzfw();
            }
            Coordinate[] coors = new Coordinate[list.size()];
            for (int i = 0; i < list.size(); i++) {
                Coordinate c = new Coordinate();
                c.x = list.get(i)[0].doubleValue();
                c.y = list.get(i)[1].doubleValue();
                coors[i] = c;
            }
            return this.isInGeometry(coors, dto.getJd() + "," + dto.getWd());
        } else if ("3".equals(bb.getXffwlx())) {
            // 警务站
            TbJcglJwz jwz = this.tbJcglAdaptRemoteService.getJwzById(bb.getXffwid());
            // 计算两点之间的距离
            if (jwz.getJd() != null || jwz.getWd() != null) return false;
            double jl = Kit.getDistance(jwz.getJd().doubleValue(), jwz.getWd().doubleValue(), dto.getJd(), dto.getWd());
            return !(jl >= 200);
        }
        return false;
    }

    @Override
    public TbQwXfbb getBbxxInfo(String id) {
        return this.tbQwXfbbMapper.selectById(id);
    }

    @Override
    public Map<String, Object> getJmjlCount() {
        UserInfo user = UserInfoManager.get();
        if (user == null) return null;
        List<TbQwXfbb> list = this.tbQwXfbbMapper.selectList(
                new LambdaQueryWrapper<TbQwXfbb>()
                        .eq(TbQwXfbb::getBbzt, "0")
                        .eq(TbQwXfbb::getXfrq, DateUtils.getQueryDateString(new Date(), "01"))
                        .and(it -> it.eq(TbQwXfbb::getSsbmid, String.valueOf(user.getDeptId())).or()
                                .eq(TbQwXfbb::getSsxgajid, String.valueOf(user.getDeptId())).or()
                                .eq(TbQwXfbb::getSssgajid, String.valueOf(user.getDeptId())).or()
                        )
        );
        if (CollectionUtils.isEmpty(list)) return null;
        // 负责人肯定是有的
        int count = list.size();
        count += list.stream().mapToInt(item -> ((item.getMjsl() != null ? item.getMjsl() : 0) +
                (item.getFjsl() != null ? item.getFjsl() : 0))).sum();
        Map<String, Object> map = new HashMap<>();
        map.put("orgid", String.valueOf(user.getDeptId()));
        map.put("orgcode", user.getDeptCode());
        map.put("orgname", user.getDeptName());
        map.put("jmjl", count);
        return map;
    }

    @Override
    public void checkXfbbSc() {
        List<TbQwXfbb> bbList = this.tbQwXfbbMapper.selectList(
                new LambdaQueryWrapper<TbQwXfbb>()
                        .eq(TbQwXfbb::getBbzt, "0")
                        .eq(TbQwXfbb::getXtSjzt, "1")
        );
        bbList.forEach(item -> {
            long now = new Date().getTime();
            long kssk = item.getBbkssj().getTime();
            item.setXfsc((int) ((now - kssk) / 1000));
            this.tbQwXfbbMapper.updateXfscById(item);
        });
    }

    @Override
    public IPage<TbQwXfbb> selectDeckListOther(TbQwXfbbJmxzQuery dto) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(dto.getBbrq())) {
            dto.setBbrq(DateUtils.getQueryDateString(new Date(), "01"));
        }
        // 如果查询时间为当天，则标志只查询报备中的数据
        if (dto.getBbrq().equals(DateUtils.getQueryDateString(new Date(), "01"))) {
            map.put("isToday", "1");
        }
        List<String> ztList = new ArrayList<>();
        IPage<TbQwXfbb> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
//        if (StringUtils.isBlank(dto.getXfzt())) {
//            return page;
//        }
        if (StringUtils.isNotBlank(dto.getXfzt())) {
            String xfzt = dto.getXfzt();
            if (xfzt.contains(",")) {
                String[] arrays = xfzt.split(",");
                ztList = Arrays.asList(arrays);
            } else {
                ztList.add(xfzt);
            }
        }
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
        map.put("list", ztList);
        map.put("ssbmdm", dto.getSsbmdm());
        int count = this.tbQwXfbbMapper.getCountZbxz(map);
        List<TbQwXfbb> list = this.tbQwXfbbMapper.getListZbxz(map);
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    /**
     * 泸州态势统计-各区县巡防时长和里程
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> getXfscAndLc(XfbbQuery dto) {
        HashMap<Object, Object> ssxgajxx = new HashMap<>();
        ssxgajxx.put("10111", "泸州机场");
        ssxgajxx.put("10929", "江阳区");
        ssxgajxx.put("11336", "龙马潭区");
        ssxgajxx.put("11379", "纳溪区");
        ssxgajxx.put("11382", "泸县");
        ssxgajxx.put("11436", "合江县");
        ssxgajxx.put("11503", "叙永县");
        ssxgajxx.put("11531", "古蔺县");
        if (StringUtils.isEmpty(dto.getKssj()) || StringUtils.isEmpty(dto.getJssj())) { // 为空的提示
            throw new BusinessException("请选择您要查询时间！");
        }
        Map<String, Object> map = new HashMap<>();
        // 巡防时长
        List<Map<String, Object>> sumXfsc = this.tbQwXfbbMapper.getSumXfsc(dto.getKssj(), dto.getJssj());
        // 巡防里程
        List<Map<String, Object>> sumXflc = this.tbQwXfbbMapper.getSumXflc(dto.getKssj(), dto.getJssj());

        List<Map<String, Object>> xfscResList = new ArrayList<>();
        List<Map<String, Object>> xflcResList = new ArrayList<>();
        ssxgajxx.keySet().forEach(item -> {
            Map<String, Object> resMap = new HashMap<>();
            // 时长
            List<Map<String, Object>> xfscList = sumXfsc.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (xfscList.size() == 1) {
                resMap.put("sum", xfscList.get(0).get("sum"));
            } else {
                resMap.put("sum", 0);
            }
            xfscResList.add(resMap);
            // 里程
            resMap = new HashMap<>();
            List<Map<String, Object>> xflcList = sumXflc.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (xflcList.size() == 1) {
                resMap.put("sum", xflcList.get(0).get("sum"));
            } else {
                resMap.put("sum", 0);
            }
            xflcResList.add(resMap);
        });
        map.put("xfscResList", xfscResList);
        map.put("xflcResList", xflcResList);
        return map;
    }

    @Override
    public Integer getBbCount(String ssbmdm, String time) {
        if(StringUtils.isBlank(time)){
            time = DateUtils.getNowDate();
        }
        try {
            ssbmdm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm,null);
            return this.tbQwXfbbMapper.selectCount(
                    new LambdaQueryWrapper<TbQwXfbb>()
                            .likeRight(!StringUtils.isEmpty(ssbmdm), TbQwXfbb::getSsbmdm, ssbmdm)
                            .eq(TbQwXfbb::getXfrq, time)
                            .isNotNull(TbQwXfbb::getBbzt)
            );
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Map<String, Integer> getScLc(String ssbmdm, String time) {
        return this.baseMapper.getScLc(ssbmdm, time);
    }


    // 判断点在范围内
    private boolean isInGeometry(Coordinate[] coordinates, String isPoint) {
        if (coordinates[0].x != coordinates[coordinates.length - 1].x || coordinates[0].y != coordinates[coordinates.length - 1].y) {
            coordinates[coordinates.length - 1] = new Coordinate(coordinates[0].x, coordinates[0].y);
        }
        String[] sp = isPoint.split(",");
        double xx = Double.parseDouble(sp[0]);
        double yy = Double.parseDouble(sp[1]);
        //点是否在多边形内判断
        Coordinate point = new Coordinate(xx, yy);
        PointLocator a = new PointLocator();
        GeometryFactory gf = new GeometryFactory();
        Geometry gfLineString = gf.createPolygon(coordinates);
        double degree = 500 / (2 * Math.PI * 6371004) * 360;
        BufferOp bufOp = new BufferOp(gfLineString);
        bufOp.setEndCapStyle(BufferOp.CAP_ROUND);
        Geometry bg = bufOp.getResultGeometry(degree);
        return a.intersects(point, bg);
    }


    // 获取巡防报备数据
    public IPage<TbQwXfbb> queryXfbb(TbQwXfbbQuery xfpb) {
        List<String> qwlxList = StringUtils.isNotBlank(xfpb.getQwlxs()) ? Arrays.asList(xfpb.getQwlxs().split(",")) : null;
        IPage<TbQwXfbb> page = new Page<>(xfpb.getPageCurrent(), xfpb.getPageSize());
        QueryWrapper<TbQwXfbb> queryWrapper = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(queryWrapper, userInfo);
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(xfpb.getSsbmdm(), null);
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(xfpb.getQwdjId()), TbQwXfbb::getQwdjId, xfpb.getQwdjId())
                .eq(StringUtils.isNotBlank(xfpb.getQwbcId()), TbQwXfbb::getQwbcId, xfpb.getQwbcId())
                .eq(StringUtils.isNotBlank(xfpb.getJzId()), TbQwXfbb::getJzId, xfpb.getJzId())
                .eq(StringUtils.isNotBlank(xfpb.getBblx()), TbQwXfbb::getBblx, xfpb.getBblx())
//                .eq(StringUtils.isNotBlank(xfpb.getXfbmdm()), TbQwXfbb::getXfbmdm, xfpb.getXfbmdm())
//                .eq(StringUtils.isNotBlank(xfpb.getXfbmid()), TbQwXfbb::getXfbmid, xfpb.getXfbmid())
                .eq(StringUtils.isNotBlank(xfpb.getBbzt()), TbQwXfbb::getBbzt, xfpb.getBbzt())
                .like(StringUtils.isNotBlank(xfpb.getFzrXm()), TbQwXfbb::getFzrXm, xfpb.getFzrXm())
                .like(StringUtils.isNotBlank(xfpb.getFzrSfzh()), TbQwXfbb::getFzrSfzh, xfpb.getFzrSfzh())
                .likeRight(StringUtils.isNotBlank(ssbm), TbQwXfbb::getSsbmdm, ssbm)
                .eq(StringUtils.isNotBlank(xfpb.getXtSjly()), TbQwXfbb::getXtSjly, xfpb.getXtSjly())
                .in(qwlxList != null, TbQwXfbb::getQwlx, qwlxList)
                .ge(ObjectUtils.isNotEmpty(xfpb.getBbkssj()), TbQwXfbb::getBbkssj, xfpb.getBbkssj())
                .le(ObjectUtils.isNotEmpty(xfpb.getBbjssj()), TbQwXfbb::getBbjssj, xfpb.getBbjssj());
        if (ObjectUtils.isNotEmpty(xfpb.getKsXfrq())) {
            queryWrapper.lambda().ge(TbQwXfbb::getXfrq, xfpb.getKsXfrq());
        }
        if (ObjectUtils.isNotEmpty(xfpb.getJsXfrq())) {
            queryWrapper.lambda().le(TbQwXfbb::getXfrq, xfpb.getJsXfrq());
        }

//        if (xfpb.getKsXfrq() != null && xfpb.getJsXfrq() != null) {
//            queryWrapper.lambda().between(TbQwXfbb::getXfrq, xfpb.getKsXfrq(), xfpb.getJsXfrq());
//        }
        queryWrapper.lambda().orderByAsc(TbQwXfbb::getBbzt).orderByDesc(TbQwXfbb::getBbkssj);
        return tbQwXfbbMapper.selectPage(page, queryWrapper);
    }

    // 保存关联数据
    public void saveRelevanceData(TbQwXfbb xfbb, TbQwXfbbVo vo, String ywid, DeptInfoVo dept) {
        if (vo != null) {
            List<TbQwJl> jlList = vo.getJlList();
            List<TbQwCl> clList = vo.getClList();
            List<TbQwZnzb> znzbList = vo.getZnzbList();
            List<TbQwJyqx> jyqxList = vo.getJyqxList();
            List<TbQwXffwDto> xffwList = vo.getXffwList();
            boolean fzr = true;
            if (!CollectionUtils.isEmpty(jlList)) {
                List<TbQwJl> collect = jlList.stream().filter(v -> v.getSfzh().equals(xfbb.getFzrSfzh())).collect(Collectors.toList());
                fzr = CollectionUtils.isEmpty(collect);
            } else {
                jlList = new ArrayList<>();
            }

            if (fzr) {
                SysUser userInfoBySfzh = this.tbBaseAdaptRemoteService.getUserOrFjInfoBySfzh(xfbb.getFzrSfzh());
                if(userInfoBySfzh == null){
                    throw new BusinessException("未查询到负责人，请核对后再报备！");
                }
                TbQwJl tbQwJl = new TbQwJl();
                tbQwJl.setYwid(xfbb.getId());
                if(userInfoBySfzh.getId() == null){
                    tbQwJl.setJlId(userInfoBySfzh.getIdEntityCard());
                    tbQwJl.setJllx(Constant.JLLX_FJ);
                }else {
                    tbQwJl.setJlId(String.valueOf(userInfoBySfzh.getId()));
                    tbQwJl.setJllx(Constant.JLLX_MJ);
                }
                tbQwJl.setJlxm(xfbb.getFzrXm());
                tbQwJl.setSfzh(xfbb.getFzrSfzh());
                tbQwJl.setXbdm(userInfoBySfzh.getSex());
                tbQwJl.setLxdh(userInfoBySfzh.getMobile());
                tbQwJl.setZblx("3");
                jlList.add(tbQwJl);
            }

            List<TbQwJl> mjLists = new ArrayList<>();
            List<TbQwJl> fjLists = new ArrayList<>();

            for (TbQwJl jl : jlList) {
                if (Constant.JLLX_MJ.equals(jl.getJllx())) {
                    mjLists.add(jl);
                } else {
                    fjLists.add(jl);
                }
            }


            xfbb.setPbmj(JSONArray.toJSONString(mjLists));
            xfbb.setPbfj(JSONArray.toJSONString(fjLists));
            xfbb.setMjsl(mjLists.size());
            xfbb.setFjsl(fjLists.size());
            for (TbQwJl jl : jlList) {
                jl.setId(UUIDGenerator.getUUID());
                jl.setZblx("3");
                jl.setYwid(ywid);
                jl.setXtSjly(StringUtils.isBlank(jl.getXtSjly()) ? "1" : jl.getXtSjly());
                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());
                tbQwJlMapper.insert(jl);
            }
//            }
            if (!CollectionUtils.isEmpty(clList)) {
                xfbb.setPbcl(JSONArray.toJSONString(clList));
                xfbb.setJcsl(clList.size());
                for (TbQwCl cl : clList) {
                    cl.setId(UUIDGenerator.getUUID());
                    cl.setYwid(ywid);
                    cl.setZblx("3");
                    cl.setXtSjzt("1");
                    cl.setXtSjly(StringUtils.isBlank(cl.getXtSjly()) ? "1" : cl.getXtSjly());
                    cl.setXtScbz("0");
                    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());
                    tbQwClMapper.insert(cl);
                }
            }
            if (!CollectionUtils.isEmpty(znzbList)) {
                xfbb.setTxzb(JSONArray.toJSONString(znzbList));
                xfbb.setTxzbsl(znzbList.size());
                for (TbQwZnzb znzb : znzbList) {
                    znzb.setId(UUIDGenerator.getUUID());
                    znzb.setYwid(ywid);
                    znzb.setZblx("3");
                    znzb.setXtSjly(StringUtils.isBlank(znzb.getXtSjly()) ? "1" : znzb.getXtSjly());
                    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());
                    tbQwZnzbMapper.insert(znzb);
                }
            }
            if (!CollectionUtils.isEmpty(jyqxList)) {
                int total = 0;
                List<TbQwJyqx> qxList = new ArrayList<>();
                for (TbQwJyqx jyqx : jyqxList) {
                    if (ObjectUtils.isNotEmpty(jyqx.getQxsl()) && jyqx.getQxsl() > 0) {
                        jyqx.setId(UUIDGenerator.getUUID());
                        jyqx.setYwid(ywid);
                        jyqx.setZblx("3");
                        jyqx.setXtSjly(StringUtils.isBlank(jyqx.getXtSjly()) ? "1" : jyqx.getXtSjly());
                        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());
                        tbQwJyqxMapper.insert(jyqx);
                        total = total + jyqx.getQxsl();
                        qxList.add(jyqx);
                    }
                }
                xfbb.setJyqx(JSONArray.toJSONString(qxList));
                xfbb.setJyqxsl(total);

            }
            if (!CollectionUtils.isEmpty(xffwList)) {
                xffwList.forEach(item -> {
                    TbQwXffw xffw = new TbQwXffw();
                    xffw.setId(UUIDGenerator.getUUID());
                    xffw.setYwid(ywid);
                    xffw.setGlbid(item.getGlbid());
                    xffw.setQwlx("2");
                    xffw.setXffwlx(item.getXffwlx());
                    xffw.setFwMc(item.getFwMc());
                    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);
                });
                xfbb.setXffwid(xffwList.stream().map(TbQwXffwDto::getGlbid).collect(Collectors.joining(",")));
            }
        }
    }

    // 删除关联数据
    public void deleteRelevanceData(String id) {
        this.tbQwJlMapper.deleteByYwid(id);
        this.tbQwClMapper.deleteByYwid(id);
        this.tbQwZnzbMapper.deleteByYwid(id);
        this.tbQwJyqxMapper.deleteByYwid(id);
        this.tbQwXffwMapper.deleteByYwid(id);
    }


    @Override
    public void updateXfzt() {
        List<TbQwXfbb> bbAll = this.baseMapper.getBbAll();
        if (!CollectionUtils.isEmpty(bbAll)) {
            for (TbQwXfbb bb : bbAll) {
                String pbmj = bb.getPbmj();
                String xlzt = "0";
                if (StringUtils.isNotBlank(pbmj)) {
                    List<TbQwJl> mjList = JSONObject.parseArray(pbmj, TbQwJl.class);
                    for (TbQwJl jl : mjList) {
                        BphJlxx getjlxx = tbLzotherAdaptRemoteService.getjlxx(jl.getSfzh());
                        if (getjlxx != null) {
                            BphJlxx bphJlxx = tbLzotherAdaptRemoteService.getjlxxCz(getjlxx);
                            if (bphJlxx != null) {
                                xlzt = "0";
                            } else {
                                xlzt = "1";
                                //停止循环
                                break;
                            }
                        }

                    }
                }
                this.baseMapper.updateByXlzt(xlzt, bb.getId());
            }


        }

    }

    @Override
    public Map<String, Integer> xfbbTj() {
        Map<String, Integer> xfMap = new HashMap();
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(null, null);
        List<TbQwXfbb> tbQwXfbbs = this.baseMapper.selectList(new LambdaQueryWrapper<TbQwXfbb>()
                .likeRight(StringUtils.isNotBlank(ssbm), TbQwXfbb::getSsbmdm, ssbm)
                .eq(TbQwXfbb::getBbzt, "0")
        );
        xfMap.put("xfbb", tbQwXfbbs.size());
        int xlry = 0;
        if (!CollectionUtils.isEmpty(tbQwXfbbs)) {
            for (TbQwXfbb xfbb : tbQwXfbbs) {
                xlry += xfbb.getMjsl() == null ? 0 : xfbb.getMjsl();
                xlry += xfbb.getFjsl() == null ? 0 : xfbb.getFjsl();
            }
        }
        xfMap.put("xlry", xlry);
        return xfMap;
    }


    @Override
    public IPage<Object> bmtj(XfbbTjQuery query) {
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        IPage<TbQwXfbbVo> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        return this.baseMapper.bmtj(page, query);
    }

    @Override
    public Object bmtjAll(XfbbTjQuery query) {
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        return this.baseMapper.bmtjAll(query);
    }

    @Override
    public IPage<Object> xqtj(XfbbTjQuery query) {
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        IPage<TbQwXfbbVo> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        return this.baseMapper.xqtj(page, query);
    }


    @Override
    public IPage<Object> grtj(XfbbTjQuery query) {
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        IPage<TbQwXfbbVo> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        return this.baseMapper.grtj(page, query);
    }

    @Override
    public List<TbQwXfbb> getBbidByXq(String xqid) {
        List<TbQwXfbb> bbidByXq = this.baseMapper.getBbidByXq(xqid);
        return bbidByXq;
    }

    @Override
    public void delRedisXfwz() {
        Set<String> keys = (Set<String>) redisService.keys(Constant.WZ_XFWZ + "*");
        for (String k : keys) {
            k = k.replaceAll("xfwz:", "");
            int i = baseMapper.selectCount(new LambdaQueryWrapper<TbQwXfbb>()
                    .eq(TbQwXfbb::getId, k)
                    .eq(TbQwXfbb::getBbzt, "0")
                    .eq(TbQwXfbb::getXtScbz, "0")
                    .eq(TbQwXfbb::getXtSjzt, "1")
            );
            if (i < 1) {
                redisService.deleteObject(Constant.WZ_XFWZ + k);
            }
        }
    }

    @Override
    public Integer updateXflc(String bbid) {
        List<TbWzLswz> bbgj = tbQwXfbbMapper.getBbgj(bbid);
        int lc = 0;
        if (!CollectionUtils.isEmpty(bbgj)) {
            for (int i = 0; i < bbgj.size() - 1; i++) {
                lc = DistanceUtils.getLc(lc, bbgj.get(i).getJd(), bbgj.get(i).getWd(), bbgj.get(i + 1).getJd(), bbgj.get(i + 1).getWd());
            }
            tbQwXfbbMapper.update(new TbQwXfbb().setXflc(lc), new LambdaQueryWrapper<TbQwXfbb>().eq(TbQwXfbb::getId, bbid));
        }
        return lc;
    }

    @Override
    public TbQwJl selectQwJlByBbInfo(String id, String xfllId) {
        if(StringUtils.isBlank(id) || StringUtils.isBlank(xfllId)){
            return null;
        }

        QueryWrapper<TbQwJl> qw = new QueryWrapper<>();
        qw.eq("xt_sjzt", "1");
        qw.eq("xt_scbz", "0");
        qw.eq("ywid", id);
        qw.eq("jl_id", xfllId);

        return this.tbQwJlMapper.selectOne(qw);
    }

    @Override
    public Boolean updateBbJzwz(TbQwXfbbDkWzDto dto) {
        UserInfo user = UserInfoManager.get();
        TbQwXfbb xfbb = this.tbQwXfbbMapper.getMybbTodayNew(String.valueOf(user.getIdEntityCard()), null);
        if(Objects.nonNull(xfbb)){
            dto.setBbid(xfbb.getId());
            this.tbQwXfbbMapper.updateBbJzwz(dto);
            xfbb.setZb(null);
            xfbb.setXfzt("0");
//            if (StringUtils.isNotBlank(xfbb.getFzrSfzh())) {
//                SysUser user1 = this.tbBaseAdaptRemoteService.getUserInfoBySfzh(xfbb.getFzrSfzh());
//                xfbb.setLx(user1.getType());
//            }
            WebSocketObject obj = new WebSocketObject("04", xfbb, null);
            try{
                this.tbWebSocketAdaptRemoteService.sendBbMessage(obj);
            }catch (Exception e){

            }
            TbWzLswz wz = new TbWzLswz();
            wz.setId(UUIDGenerator.getUUID());
            wz.setSjly("02");
            wz.setDwsj(new Date());
            wz.setYwid(xfbb.getId());
            wz.setJd(BigDecimal.valueOf(dto.getJd()));
            wz.setWd(BigDecimal.valueOf(dto.getWd()));
            Timestamp csdtTime = new Timestamp(System.currentTimeMillis());
            wz.setXtCjsj(csdtTime);
            wz.setXtSjly("1");
            wz.setXtSjzt("1");
            wz.setXtScbz("0");
//            wz.setZb(JtsUtils.getPoint(wz.getJd(), wz.getWd()));
            this.baseMapper.insertTbWzSblswz(wz);
        }
        return true;
    }

}
