package com.mosty.sjzx.service.impl;

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.mosty.base.model.dto.jcgl.TbJcglPzfzDto;
import com.mosty.base.model.dto.sjzx.*;
import com.mosty.base.model.entity.jcgl.TbJcglKhbm;
import com.mosty.base.model.entity.jcgl.TbJcglPzfz;
import com.mosty.base.model.entity.qwzx.TbQwXfBxfsq;
import com.mosty.base.model.query.sjzx.TbSjQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.jcgl.TbJcglKhbmVo;
import com.mosty.base.utils.GeoHashKit;
import com.mosty.base.utils.JtsUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.base.model.query.yjzl.TbYjxxQuery;
import com.mosty.base.model.query.yjzl.TbZlxxQuery;
import com.mosty.base.model.vo.yszx.TbYsDlQuery;
import com.mosty.base.model.vo.yszx.TbYsGajgQuery;
import com.mosty.base.model.entity.sjzx.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.base.util.DateUtils;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.base.model.query.sjzx.SearchDto;
import com.mosty.base.model.query.sjzx.TbJqPageListQuery;
import com.mosty.common.util.PermissionsUtil;
import com.mosty.sjzx.mapper.*;
import com.mosty.sjzx.remote.*;
import com.mosty.sjzx.service.TbJqService;
import com.mosty.sjzx.service.TbSjService;
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.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 事件表(TbSj)表服务实现类
 *
 * @author zhangHaiJun
 * @since 2022-07-14 11:42:31
 */
@Service("tbSjService")
@AllArgsConstructor
public class TbSjServiceImpl implements TbSjService {
    private TbSjMapper tbSjMapper;
    private TbYszxAdapRemoteService tbYszxAdapRemoteService;
    private TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private TbYjzlAdaptRrmoteService tbYjzlAdaptRrmoteService;
    private TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private TbSjSpbfMapper tbSjSpbfMapper;
    private TbRzSpbfAdaptRemoteService tbRzSpbfAdaptRemoteService;
    private TbJqMapper tbJqMapper;
    private TbJqService tbJqService;
    private TbSjDzMapper tbSjDzMapper;
    private TbSjRzMapper tbSjRzMapper;

    @Override
    public Object bxdCreate() {
        String kssj = com.mosty.base.utils.DateUtils.getQueryDateString(com.mosty.base.utils.DateUtils.getNextDate(new Date(), "D", -30), "01");
        String jssj = com.mosty.base.utils.DateUtils.getQueryDateString(new Date(), "01");
        // 查询最近30天的所有的警情数据
        List<TbJq> jqList = this.tbJqMapper.selectList(
                new LambdaQueryWrapper<TbJq>()
                        .ge(TbJq::getBjrq, kssj)
                        .le(TbJq::getBjrq, jssj)
                        .last(" and jd is not null and wd is not null and bjlb is not null")
        );
        List<BxdCreatedDto> list = jqList.stream().map(item -> {
            BxdCreatedDto dto = new BxdCreatedDto();
            dto.setJd(item.getJd());
            dto.setWd(item.getWd());
            dto.setSsbmdm(item.getSsbmdm());
            if ("01000000".equals(item.getBjlb())) {
                dto.setPzlx("01");
            } else if ("02000000".equals(item.getBjlb())) {
                dto.setPzlx("02");
            } else {
                dto.setPzlx("03");
            }
            return dto;
        }).collect(Collectors.toList());
        // 查询最近30天的所有的预警数据
        List<Map<String, Object>> yjList = this.tbJqMapper.getYjxx30Day(kssj, jssj);
        list.addAll(yjList.stream().map(item -> {
            BxdCreatedDto dto = new BxdCreatedDto();
            dto.setJd(new BigDecimal(String.valueOf(item.get("jd"))));
            dto.setWd(new BigDecimal(String.valueOf(item.get("wd"))));
            String yjlx = String.valueOf(item.get("yj_lx"));
            if ("1".equals(yjlx)) {
                dto.setPzlx("04");
            } else if ("2".equals(yjlx)) {
                dto.setPzlx("05");
            } else if ("3".equals(yjlx)) {
                dto.setPzlx("06");
            }
            return dto;
        }).collect(Collectors.toList()));
        // 查询最近30天的所有的盘查人员数据
        List<Map<String, Object>> ryList = this.tbJqMapper.getPcryList(kssj, jssj);
        list.addAll(ryList.stream().map(item -> {
            BxdCreatedDto dto = new BxdCreatedDto();
            dto.setJd(new BigDecimal(String.valueOf(item.get("jd"))));
            dto.setWd(new BigDecimal(String.valueOf(item.get("wd"))));
            dto.setSsbmdm(String.valueOf(item.get("ssbmdm")));
            dto.setPzlx("07");
            return dto;
        }).collect(Collectors.toList()));
        // 查询最近30天的所有的盘查车辆数据
        List<Map<String, Object>> clList = this.tbJqMapper.getPcclList(kssj, jssj);
        list.addAll(clList.stream().map(item -> {
            BxdCreatedDto dto = new BxdCreatedDto();
            dto.setJd(new BigDecimal(String.valueOf(item.get("jd"))));
            dto.setWd(new BigDecimal(String.valueOf(item.get("wd"))));
            dto.setPzlx("08");
            dto.setSsbmdm(String.valueOf(item.get("ssbmdm")));
            return dto;
        }).collect(Collectors.toList()));
        return this.filterJwd(list);
    }

    @Override
    public IPage<TbSjDto> getPageList(TbSjQuery dto) {
//        UserInfo user = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, user);

        QueryWrapper<TbSj> qw = new QueryWrapper<>();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));

        IPage<TbSj> page = this.tbSjMapper.selectPage(
                new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                qw.lambda()
                        .eq(!StringUtils.isEmpty(dto.getSjFl()), TbSj::getSjFl, dto.getSjFl())
                        .likeRight(!StringUtils.isEmpty(dto.getSsbmdm()), TbSj::getSsbmdm, dto.getSsbmdm())
        );
        IPage<TbSjDto> resPage = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        List<TbSjDto> resList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                TbSjDto vo = new TbSjDto();
                BeanUtils.copyProperties(item, vo);
                resList.add(vo);
            });
        }
        resPage.setRecords(resList);
        resPage.setTotal(page.getTotal());
        return resPage;
    }

    // 计算必巡点
    private Object filterJwd(List<BxdCreatedDto> points) {
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(100);
        List<NeighborDTO> neighborList = Collections.synchronizedList(new ArrayList<>(30000));
        // 计算每个点一定范围内所有点坐标
        for (BxdCreatedDto point : points) {
            // 范围，从系统配置中获取，没有的话直接范围为500
            String fw = this.tbBaseAdaptRemoteService.getValue("BXDFW");
            int bxdfw = StringUtils.isNotBlank(fw) ? Integer.parseInt(fw) : 500;
            threadPool.execute(new DistanceRunnable(point, points, neighborList, bxdfw));
        }
        // 等待线程池执行完毕
        while (neighborList.size() != points.size()) {
            System.out.println(neighborList.size());
        }
        threadPool.shutdown();
        // 排序
        Collections.sort(neighborList);
        // 筛选(附近点位低于20个不进入计算)
        Map<BxdCreatedDto, Long> map = new HashMap<>();
        Iterator<NeighborDTO> it = neighborList.iterator();
        // 计算必巡点点位 默认20个点位开始计算
        String dw = this.tbBaseAdaptRemoteService.getValue("BXDDW");
        int bxddw = StringUtils.isNotBlank(dw) ? Integer.parseInt(dw) : 500;
        while (it.hasNext()) {
            NeighborDTO neighborDTO = it.next();
            Map<BxdCreatedDto, Long> neighbors = neighborDTO.getNeighbors();
            if (map.containsKey(neighborDTO.getPoint()) || neighbors.size() <= bxddw) {
                it.remove();
            }
            map.putAll(neighbors);
        }
        // 业务操作
        List<Map<String, Object>> rList = new ArrayList<>();
        // 查询重点区域的分值配置
        List<TbJcglPzfzDto> fzList = this.tbJcglAdaptRemoteService.getFzList();
        for (NeighborDTO item : neighborList) {
            BxdCreatedDto point = item.getPoint();
            Map<BxdCreatedDto, Long> neighbors = item.getNeighbors();
            int size = neighbors.size() + 1;
            int score = 0;
            int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
            for (BxdCreatedDto i : neighbors.keySet()) {
                score += this.getFz(fzList, i.getPzlx());
                switch (i.getPzlx()) {
                    case "01":
                        a++;
                        break;
                    case "02":
                        b++;
                        break;
                    case "03":
                        c++;
                        break;
                    case "04":
                        d++;
                        break;
                    case "05":
                        e++;
                        break;
                    case "06":
                        f++;
                        break;
                    case "07":
                        g++;
                        break;
                    case "08":
                        h++;
                        break;
                }
            }
            // // 获取分值阈值，超过阈值生成必巡点
            String yz = this.tbBaseAdaptRemoteService.getValue("BXDFZYZ");
            int fzyz = StringUtils.isNotBlank(yz) ? Integer.parseInt(yz) : 100;
            if (score >= fzyz) {
                String bz = String.format("刑事警情：%s个，行政警情：%s个  其他警情：%s个  人员预警：%s个  " +
                        "车辆预警：%s个  事件预警：%s个  盘查重点人员：%s个  盘查重点车辆：%s个", a, b, c, d, e, f, g, h);
                System.err.println(bz);
                System.err.println("point: " + point.getJd() + ", " + point.getWd() + " n: " + size + " s：" + score);

                Map<String, Object> mp = new HashMap<>();
                mp.put("jd", point.getJd());
                mp.put("wd", point.getWd());
                mp.put("score", size + 1);
                mp.put("bz", bz);
                mp.put("ssbmdm", item.getPoint().getSsbmdm());
                rList.add(mp);
            }
        }
        this.tbJcglAdaptRemoteService.createdBxd(rList);
        return rList;
    }

    // 获取系统配置的分值
    private int getFz(List<TbJcglPzfzDto> fzList, String pzlx) {
        int score = -1;
        List<TbJcglPzfzDto> tempList = fzList.stream().filter(item -> pzlx.equals(item.getPzlx())).collect(Collectors.toList());
        if (tempList.size() > 0) {
            TbJcglPzfzDto dto = tempList.get(0);
            score = dto.getPzfz();
        }
        if (score == -1) {
            switch (pzlx) {
                case "01":
                case "02":
                case "04":
                case "05":
                case "07":
                case "08":
                    score = 2;
                    break;
                case "03":
                case "06":
                    score = 1;
                    break;
            }
        }
        return score;
    }

    @Override
    public Object queryAll(SearchDto dto) {
//        UserInfo user = UserInfoManager.get();
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        // 警情
        if ("01".equals(dto.getType())) {
            TbJqPageListQuery query = new TbJqPageListQuery();
            query.setPageNum(dto.getPageNum());
            query.setPageSize(dto.getPageSize());
            query.setBjnr(dto.getKeyword());
            return this.tbJqService.selectPageList(query);
        } else if ("02".equals(dto.getType())) {
            // 预警
            TbYjxxQuery query = new TbYjxxQuery();
            query.setPageNum(dto.getPageNum());
            query.setPageSize(dto.getPageSize());
            query.setYjNr(dto.getKeyword());
            return tbYjzlAdaptRrmoteService.getPageList(query);
        } else if ("03".equals(dto.getType())) {
            //指令
            TbZlxxQuery query = new TbZlxxQuery();
            query.setPageNum(dto.getPageNum());
            query.setPageSize(dto.getPageSize());
            query.setZlnr(dto.getKeyword());
            return tbYjzlAdaptRrmoteService.selectInstructList(query);
        } else if ("04".equals(dto.getType())) {
            // 事件
            QueryWrapper<TbSj> qw = new QueryWrapper<>();
//            PermissionsUtil.queryWrapperUtil(qw, user);

            return this.tbSjMapper.selectPage(
                    new Page<>(dto.getPageNum(), dto.getPageSize()),
                    qw.lambda().eq(TbSj::getXtSjzt, "1")
                            .like(TbSj::getSjNr, dto.getKeyword())
                            .likeRight(StringUtils.isNotBlank(dto.getSsbmdm()), TbSj::getSsbmdm, dto.getSsbmdm())

            );
        } else if ("05".equals(dto.getType())) {
            // 地理要素
            TbYsDlQuery query = new TbYsDlQuery();
            query.setPageNum(dto.getPageNum());
            query.setPageSize(dto.getPageSize());
            query.setJsnr(dto.getKeyword());
            return tbYszxAdapRemoteService.queryAll(query);
        } else if ("06".equals(dto.getType())) {
            // 公安机关
            TbYsGajgQuery query = new TbYsGajgQuery();
            query.setPageNum(dto.getPageNum());
            query.setPageSize(dto.getPageSize());
            query.setJsnr(dto.getKeyword());
            return tbYszxAdapRemoteService.getGajgAll(query);
        }
        return null;
    }

    @Override
    public TbSjDto queryById(String id) {
        TbSj sj = this.tbSjMapper.selectById(id);
        TbSjDto dto = new TbSjDto();
        BeanUtils.copyProperties(sj, dto);
        return dto;
    }

    @Override
    @Transactional
    public TbSjDto insert(TbSj tbSj) {
        TbSjDto dto = new TbSjDto();
        UserInfo user = UserInfoManager.get();
        // 查询来源id是否存在
        TbSj sj = this.tbSjMapper.selectOne(
                new QueryWrapper<TbSj>()
                        .eq("yw_id", tbSj.getYwId())
                        .eq("xt_sjzt", "1")
                        .eq("sj_fl", tbSj.getSjFl()));
        if (null != sj) {
            BeanUtils.copyProperties(sj, dto);
            // 保存事件日志
            this.insertSjRz(sj, user);
            return dto;
        } else {
            if (!StringUtils.isBlank(tbSj.getYwId()) && !StringUtils.isBlank(tbSj.getSjFl())) {
                switch (tbSj.getSjFl()) {
                    case "01":
                        break;
                    case "02":
                        // 警情转事件
                        this.jqTurnSj(tbSj, user);
                        break;
                    case "03":
                        break;
                    case "04":
                        break;
                }
            } else {
                // 手动添加事件
                this.insertSj(tbSj, user);
            }
        }
        BeanUtils.copyProperties(tbSj, dto);
        return dto;
    }

    // 手动添加事件
    private void insertSj(TbSj tbSj, UserInfo user) {
        tbSj.setQcHx(tbSj.getQcHx() != null && tbSj.getQcHx() != 0 ? tbSj.getQcHx() : 50);
        tbSj.setQcJj(tbSj.getQcJj() != null && tbSj.getQcJj() != 0 ? tbSj.getQcJj() : 150);
        tbSj.setQcGz(tbSj.getQcGz() != null && tbSj.getQcGz() != 0 ? tbSj.getQcGz() : 300);
        tbSj.setId(UUIDGenerator.getUUID());
        tbSj.setCzkssj(new Date());
        tbSj.setQcGxcs(0);
        tbSj.setSjFssj(new Date());
        tbSj.setQcGxsj(new Date());
        if (tbSj.getCsjd() != null && tbSj.getCswd() != null) {
            tbSj.setCszb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setCszbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setDqjd(tbSj.getCsjd());
            tbSj.setDqwd(tbSj.getCswd());
            tbSj.setDqzb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setDqzbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
        }
        tbSj.setDqdz(tbSj.getCsdz());
        if (user != null) {
            tbSj.setSsbm(user.getDeptName());
            tbSj.setSsbmid(String.valueOf(user.getDeptId()));
            tbSj.setSsbmdm(user.getDeptCode());
            tbSj.setSsxgaj(user.getFxjDeptName());
            tbSj.setSsxgajid(String.valueOf(user.getFxjDeptId()));
            tbSj.setSsxgajdm(user.getFxjDeptCode());
            tbSj.setSssgaj(user.getDszDeptName());
            tbSj.setSssgajid(String.valueOf(user.getDszDeptId()));
            tbSj.setSssgajdm(user.getDszDeptCode());
        }
        tbSj.setXtSjly("1");
        tbSj.setSjFl("99");
        tbSj.setDqdzxzqh(tbSj.getCsdzxzqh());
        this.tbSjMapper.insertEntity(tbSj);
        // 添加地址信息
        this.insertSjdz(tbSj, user);
        // 保存事件日志
        this.insertSjRz(tbSj, user);
    }

    // 警情转事件
    private void jqTurnSj(TbSj tbSj, UserInfo user) {
        TbJq tbjq = this.tbJqMapper.selectById(tbSj.getYwId());
        if (null != tbjq) {
            tbSj.setSjJb(tbjq.getJqjb());
            tbSj.setSjFssj(tbjq.getBjsj());
            tbSj.setSjNr(tbjq.getBjnr());
            tbSj.setCsjd(tbjq.getJd());
            tbSj.setSjBt("重大警情事件");
            tbSj.setBjrxm(tbjq.getBjrXm());
            tbSj.setBjrlxdh(tbjq.getBjdh());
            tbSj.setCswd(tbjq.getWd());
            tbSj.setDqjd(tbjq.getJd());
            tbSj.setDqwd(tbjq.getWd());
            tbSj.setCsdz(tbjq.getSfdz());
            if (tbjq.getJd() != null && tbjq.getWd() != null) {
                tbSj.setCszb(JtsUtils.getPoint(tbjq.getJd(), tbjq.getWd()));
                tbSj.setDqzb(JtsUtils.getPoint(tbjq.getJd(), tbjq.getWd()));
                tbSj.setCszbhash(GeoHashKit.encode(tbjq.getJd(), tbjq.getWd()));
                tbSj.setDqzbhash(GeoHashKit.encode(tbjq.getJd(), tbjq.getWd()));
            }
            tbSj.setCzkssj(new Date());
            DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(tbjq.getSsbmdm());
            tbSj.setSsbm(dept.getDeptname());
            tbSj.setSsbmid(dept.getDeptid());
            tbSj.setSsbmdm(dept.getDeptcode());
            tbSj.setSsxgajdm(dept.getFxjcode());
            tbSj.setSsxgajid(dept.getFxjid());
            tbSj.setSsxgaj(dept.getFxjname());
            tbSj.setSssgaj(dept.getDszname());
            tbSj.setSssgajdm(dept.getDszcode());
            tbSj.setSssgajid(dept.getDszid());
        }
        tbSj.setQcHx(tbSj.getQcHx() != null && tbSj.getQcHx() != 0 ? tbSj.getQcHx() : 50);
        tbSj.setQcJj(tbSj.getQcJj() != null && tbSj.getQcJj() != 0 ? tbSj.getQcJj() : 150);
        tbSj.setQcGz(tbSj.getQcGz() != null && tbSj.getQcGz() != 0 ? tbSj.getQcGz() : 300);
        tbSj.setId(UUIDGenerator.getUUID());
        tbSj.setCzkssj(new Date());
        tbSj.setQcGxcs(0);
        tbSj.setQcGxsj(new Date());
        if (tbSj.getCsjd() != null && tbSj.getCswd() != null) {
            tbSj.setCszb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setCszbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setDqjd(tbSj.getCsjd());
            tbSj.setDqwd(tbSj.getCswd());
            tbSj.setDqzb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setDqzbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
        }
        tbSj.setDqdz(tbSj.getCsdz());
        tbSj.setXtSjly("1");
        tbSj.setDqdzxzqh(tbSj.getCsdzxzqh());
        this.tbSjMapper.insertEntity(tbSj);
        // 添加地址信息
        this.insertSjdz(tbSj, user);
        // 保存事件日志
        this.insertSjRz(tbSj, user);
    }

    // 添加日志信息
    private void insertSjRz(TbSj tbSj, UserInfo user) {
        int count = this.tbSjRzMapper.selectCount(
                new LambdaQueryWrapper<TbSjRz>()
                        .eq(TbSjRz::getSjId, tbSj.getId())
                        .like(TbSjRz::getRzms, "进入事件处置")
        ) + 1;
        TbSjRz rz = new TbSjRz();
        rz.setId(UUIDGenerator.getUUID());
        rz.setSjId(tbSj.getId());
        if (user != null) {
            rz.setRzms(DateUtils.getTime() + "," + user.getDeptName() +
                    "（" + user.getUserName() + "）进入事件处置，准备开始处置事件，该事件第" + count + "次进入处置页面");
            rz.setCzryId(String.valueOf(user.getUserId()));
            rz.setCzryXm(user.getUserName());
            rz.setCzrySfzh(user.getIdEntityCard());
            rz.setSsbm(tbSj.getSsbm());
            rz.setSsbmdm(tbSj.getSsbmdm());
            rz.setSsxgaj(tbSj.getSsxgaj());
            rz.setSsxgajdm(tbSj.getSsxgajdm());
            rz.setSssgaj(tbSj.getSssgaj());
            rz.setSssgajdm(tbSj.getSssgajdm());
            rz.setSsbmid(tbSj.getSsbmid());
            rz.setSsxgajid(tbSj.getSsxgajid());
            rz.setSssgajid(tbSj.getSssgajid());
        } else {
            rz.setRzms(DateUtils.getTime() + "," + "进入事件处置，准备开始处置事件！！");
        }
        rz.setCzsj(new Date());
        rz.setXtSjly("1");
        this.tbSjRzMapper.insert(rz);
    }

    // 添加地址信息
    private void insertSjdz(TbSj tbSj, UserInfo user) {
        TbSjDz dz = new TbSjDz();
        dz.setId(UUIDGenerator.getUUID());
        dz.setSjId(tbSj.getId());
        dz.setDztzSj(new Date());
        if (user != null) {
            dz.setDztzRyid(String.valueOf(user.getUserId()));
            dz.setDztzRysfzh(user.getIdEntityCard());
            dz.setDztzRyxm(user.getUserName());
        }
        if (tbSj.getCsjd() != null && tbSj.getCswd() != null) {
            dz.setJd(tbSj.getCsjd());
            dz.setWd(tbSj.getCswd());
            dz.setZb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            dz.setZbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
            dz.setDzxzqh(tbSj.getCsdzxzqh());
            dz.setDz(tbSj.getCsdz());
        }
        dz.setSsbm(tbSj.getSsbm());
        dz.setSsbmdm(tbSj.getSsbmdm());
        dz.setSsxgaj(tbSj.getSsxgaj());
        dz.setSsxgajdm(tbSj.getSsxgajdm());
        dz.setSssgaj(tbSj.getSssgaj());
        dz.setSssgajdm(tbSj.getSssgajdm());
        dz.setSsbmid(tbSj.getSsbmid());
        dz.setSsxgajid(tbSj.getSsxgajid());
        dz.setSssgajid(tbSj.getSssgajid());
        dz.setXtSjly("1");
        this.tbSjDzMapper.insertEntity(dz);
    }

    @Override
    @Transactional
    public void editQc(TbSjQcszDto dto) {
        UserInfo user = UserInfoManager.get();
        TbSj sj = new TbSj();
        BeanUtils.copyProperties(dto, sj);
        TbSj entity = this.tbSjMapper.queryById(dto.getId());
        sj.setQcGxcs(entity.getQcGxcs() + 1);
        sj.setQcGxsj(new Date());
        this.tbSjMapper.updateEntity(sj);
        // 记录日志
        TbSjRz rz = new TbSjRz();
        rz.setId(UUIDGenerator.getUUID());
        rz.setSjId(entity.getId());
        if (user != null) {
            rz.setRzms(DateUtils.getTime() + "," + user.getDeptName() +
                    "（" + user.getUserName() + "）设置了圈层距离，分别为核心圈：" + dto.getQcHx() +
                    "米，警戒圈：" + dto.getQcJj() + "米，关注圈：" + dto.getQcGz() + "米。");
            rz.setCzryId(String.valueOf(user.getUserId()));
            rz.setCzryXm(user.getUserName());
            rz.setCzrySfzh(user.getIdEntityCard());
            rz.setSsbm(user.getDeptName());
            rz.setSsbmid(String.valueOf(user.getDeptId()));
            rz.setSsbmdm(user.getDeptCode());
            rz.setSsxgaj(user.getFxjDeptName());
            rz.setSsxgajid(String.valueOf(user.getFxjDeptId()));
            rz.setSsxgajdm(user.getFxjDeptCode());
            rz.setSssgaj(user.getDszDeptName());
            rz.setSssgajid(String.valueOf(user.getDszDeptId()));
            rz.setSssgajdm(user.getDszDeptCode());
        } else {
            rz.setRzms(DateUtils.getTime() +
                    ",设置了圈层距离，分别为核心圈：" + dto.getQcHx() +
                    "米，警戒圈：" + dto.getQcJj() + "米，关注圈：" + dto.getQcGz() + "。");
        }
        rz.setCzsj(new Date());
        rz.setXtSjly("1");
        this.tbSjRzMapper.insert(rz);
    }

    @Override
    @Transactional
    public void updateJwd(TbSjUpdateJwdDto dto) {
        UserInfo user = UserInfoManager.get();
        TbSj entity = this.tbSjMapper.queryById(dto.getId());
        if (entity != null) {
            entity.setDqjd(dto.getDqjd());
            entity.setDqwd(dto.getDqwd());
            entity.setDqdz(dto.getDqdz());
            entity.setDqdzxzqh(dto.getDqdzxzqh());
            if (dto.getDqjd() != null && dto.getDqwd() != null) {
                entity.setDqzb(JtsUtils.getPoint(dto.getDqjd(), dto.getDqwd()));
                entity.setDqzbhash(GeoHashKit.encode(dto.getDqjd(), dto.getDqwd()));
            }
            // 如果没有初始经纬度，这里将第一次设置的改为初始经纬度
            if (entity.getCsjd() == null || entity.getCswd() == null) {
                entity.setCsjd(dto.getDqjd());
                entity.setCswd(dto.getDqwd());
                entity.setCsdz(dto.getDqdz());
                entity.setCsdzxzqh(dto.getDqdzxzqh());
                entity.setCszb(JtsUtils.getPoint(dto.getDqjd(), dto.getDqwd()));
                entity.setCszbhash(GeoHashKit.encode(dto.getDqjd(), dto.getDqwd()));
            }
            this.tbSjMapper.updateEntity(entity);
            // 记录坐标变更
            TbSjDz dz = new TbSjDz();
            dz.setId(UUIDGenerator.getUUID());
            dz.setSjId(dto.getId());
            dz.setDztzSj(new Date());
            if (user != null) {
                dz.setDztzRyid(String.valueOf(user.getUserId()));
                dz.setDztzRysfzh(user.getIdEntityCard());
                dz.setDztzRyxm(user.getUserName());
            }
            dz.setJd(dto.getDqjd());
            dz.setWd(dto.getDqwd());
            if (dz.getJd() != null && dz.getWd() != null) {
                dz.setZb(JtsUtils.getPoint(dz.getJd(), dz.getWd()));
                dz.setZbhash(GeoHashKit.encode(dz.getJd(), dz.getWd()));
                if (user != null) {
                    dz.setSsbm(user.getDeptName());
                    dz.setSsbmid(String.valueOf(user.getDeptId()));
                    dz.setSsbmdm(user.getDeptCode());
                    dz.setSsxgaj(user.getFxjDeptName());
                    dz.setSsxgajid(String.valueOf(user.getFxjDeptId()));
                    dz.setSsxgajdm(user.getFxjDeptCode());
                    dz.setSssgaj(user.getDszDeptName());
                    dz.setSssgajid(String.valueOf(user.getDszDeptId()));
                    dz.setSssgajdm(user.getDszDeptCode());
                }
            }
            dz.setXtSjly("1");
            this.tbSjDzMapper.insertEntity(dz);
        } else {
            throw new BusinessException("未查询到事件信息");
        }
    }

    @Override
    @Transactional
    public void addSjRz(TbSjRzDto dto) {
        UserInfo user = UserInfoManager.get();
        TbSjRz rz = new TbSjRz();
        rz.setId(UUIDGenerator.getUUID());
        if (user != null) {
            rz.setCzryId(String.valueOf(user.getUserId()));
            rz.setCzryXm(user.getUserName());
            rz.setCzrySfzh(user.getIdEntityCard());
            rz.setSsbm(user.getDeptName());
            rz.setSsbmid(String.valueOf(user.getDeptId()));
            rz.setSsbmdm(user.getDeptCode());
            rz.setSsxgaj(user.getFxjDeptName());
            rz.setSsxgajid(String.valueOf(user.getFxjDeptId()));
            rz.setSsxgajdm(user.getFxjDeptCode());
            rz.setSssgaj(user.getDszDeptName());
            rz.setSssgajid(String.valueOf(user.getDszDeptId()));
            rz.setSssgajdm(user.getDszDeptCode());
        }
        rz.setCzsj(new Date());
        rz.setXtSjly("1");
        this.tbSjRzMapper.insert(rz);
    }

    @Override
    public boolean deleteById(String id) {
        return this.tbSjMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean finishDispose(TbSj dto) {
        TbSj tbSj = this.tbSjMapper.selectById(dto.getId());
        if (tbSj == null) throw new BusinessException("事件未找到！！");
        tbSj.setCzjssj(new Date());
        tbSj.setCzzt(dto.getCzzt());
        tbSj.setCzsm(dto.getCzsm());
        if (tbSj.getDqjd() != null && tbSj.getDqwd() != null) {
            tbSj.setDqzb(JtsUtils.getPoint(tbSj.getDqjd(), tbSj.getDqwd()));
            tbSj.setDqzbhash(GeoHashKit.encode(tbSj.getDqjd(), tbSj.getDqwd()));
        }

        if (tbSj.getCsjd() != null && tbSj.getCswd() != null) {
            tbSj.setCszb(JtsUtils.getPoint(tbSj.getCsjd(), tbSj.getCswd()));
            tbSj.setCszbhash(GeoHashKit.encode(tbSj.getCsjd(), tbSj.getCswd()));
        }
        tbSjMapper.updateEntity(tbSj);
        //更新视频表的结束时间
        List<TbSjSpbf> sjsp = tbSjSpbfMapper.selectList(
                new QueryWrapper<TbSjSpbf>()
                        .eq(StringUtils.isNotBlank(tbSj.getId()), "sj_id", tbSj.getId())
                        .isNull("bfjssj")
        );
        if (!(sjsp != null && sjsp.size() > 0)) {
            TbSjSpbf tbSjSpbf = new TbSjSpbf();
            tbSjSpbf.setBfjssj(DateUtils.getNowDate());
            tbSjSpbfMapper.update(tbSjSpbf, new QueryWrapper<TbSjSpbf>()
                    .eq(StringUtils.isNotBlank(tbSj.getId()), "sj_id", tbSj.getId()));
        }
        //修改日志
        tbRzSpbfAdaptRemoteService.updateLyId(tbSj.getId());
        return true;
    }
}

