package com.mosty.hczx.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.hczx.BpcrySaveDto;
import com.mosty.base.model.dto.hczx.TbHcBpcryInsertDto;
import com.mosty.base.model.dto.yszx.TbYsRyDto;
import com.mosty.base.model.entity.hczx.*;
import com.mosty.base.model.query.hczx.*;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.hczx.*;
import com.mosty.base.model.vo.yszx.TbYsRyBqUpdateDto;
import com.mosty.base.model.vo.yszx.TbYsRyVo;
import com.mosty.base.utils.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.config.mapper.SysDictItemMapper;
import com.mosty.common.core.util.http.HttpUtils;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.UUIDGenerator;
import com.mosty.hczx.mapper.*;
import com.mosty.hczx.remote.TbBaseAdaptRemoteService;
import com.mosty.hczx.remote.TbJcglAdaptRemoteService;
import com.mosty.hczx.remote.TbLzotherAdapRemoteService;
import com.mosty.hczx.remote.TbYszxAdapRemoteService;
import com.mosty.hczx.service.TbHcBpcryService;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.*;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class TbHcBpcryServiceImpl extends ServiceImpl<TbHcBpcryMapper, TbHcBpcry>
        implements TbHcBpcryService {

    private final TbHcTpMapper tbHcTpMapper;
    private final TbHcBpcryWpMapper tbHcBpcryWpMapper;
    private final TbHcBpcryBqMapper tbHcBpcryBqMapper;
    private final TbHcBpcclBqMapper tbHcBpcclBqMapper;
    private final TbHcBpcryTzbqMapper tbHcBpcryTzbqMapper;
    private final TbHcBpcclMapper tbHcBpcclMapper;
    private final TbYszxAdapRemoteService tbYszxAdapRemoteService;
    private final RedisService redisService;
    private final SysDictItemMapper sysDictItemMapper;
    private final TbLzotherAdapRemoteService tbLzotherAdapRemoteService;
    private final TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private final TbHcDtgzMapper tbHcDtgzMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;


    @Override
    public Integer selectCrewCount(String ssbmdm, String isChild) {
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm, isChild);
        return this.baseMapper.selectCrewCount(ssbm);
    }

    @Override
    public IPage<TbHcBpcryVo> selectCrewList(TbHcTodayBpcryQuery dto) {
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        IPage<TbHcBpcryVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
//        UserInfo userInfo = UserInfoManager.get();
//        map.put("useSql", PermissionsUtil.createSql("a", userInfo));
        int count = this.baseMapper.getCount(map);
        List<TbHcBpcry> list = this.baseMapper.getList(map);
        List<TbHcBpcryVo> rList = new ArrayList<>();
        list.forEach(item -> {
            TbHcBpcryVo vo = new TbHcBpcryVo();
            BeanUtils.copyProperties(item, vo);
            rList.add(vo);
        });
        page.setTotal(count);
        page.setRecords(rList);
        return page;
    }

    @Override
    @Transactional
    public TbHcBpcryVo selectRy(TbHcBpcryQuery dto) {
        UserInfo user = UserInfoManager.get();

        TbHcBpcry item = new TbHcBpcry();
        BeanUtils.copyProperties(dto, item);
        if (StringUtils.isNotBlank(dto.getSfzh())) {
            // 根据身份证号查询
            return this.selectRyBySfz(dto, user, item);
        }
        return null;
    }

    @Override
    public TbHcBpcryVo selectNwRy(TbHcBpcryQuery dto) {
        UserInfo user = UserInfoManager.get();

        TbHcBpcry item = new TbHcBpcry();
        BeanUtils.copyProperties(dto, item);
        if (StringUtils.isNotBlank(dto.getSfzh())) {
            //先查询两个小时前自己是否查询过此人
            TbHcBpcry tbHcBpcry = this.baseMapper.selectOne(new LambdaQueryWrapper<TbHcBpcry>()
                    .eq(TbHcBpcry::getSfzh, dto.getSfzh())
                    .ge(TbHcBpcry::getPcsj, DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "H", -2), "02"))
                    .eq(TbHcBpcry::getPcmjSfzh, user.getIdEntityCard()).last(" limit 1")
            );
            TbHcBpcryVo vo = new TbHcBpcryVo();
            if (ObjectUtils.isNotEmpty(tbHcBpcry)) {
                BeanUtils.copyProperties(tbHcBpcry, vo);
                if("ZDRY".equals(vo.getBqmc())){
                    vo.setPcbqsm("该人员为被盗抢人员，请使用移动警务终端查看详情");
                }else if("LKRY".equals(vo.getBqmc())){
                    vo.setPcbqsm("该人员为临控人员，请使用移动警务终端查看详情");
                }else{
                    vo.setPcbqsm("正常人员");
                }
                return vo;
            } else {
                Integer zdbqNum = this.getRyZdbqZtFromNw(dto, user);
                if(zdbqNum != null && zdbqNum != 0){
                    item.setId(UUIDGenerator.getUUID())
                            .setSfzh(dto.getSfzh())
//                            .setXm(ry.getXm())
//                            .setXbdm(ry.getXb())
//                            .setCsrq(ry.getSfzh().substring(6, 10) + "-" + ry.getSfzh().substring(10, 12) + "-" + ry.getSfzh().substring(12, 14))
//                            .setMzdm(ry.getMz())
//                            .setWhcddm(ry.getWhcd())
//                            .setJgdm(ry.getJgssx())
//                            .setZzxz(ry.getZzxz())
                            .setPcrq(new Date())
                            .setPcsj(new Date())
                            .setXtSjly("2");
//                    item.setXjzdz(ry.getZzxz());
                    item.setPcmjId(String.valueOf(user.getUserId())).setPcmjJh(user.getInDustRialId()).setPcmjSfzh(user.getIdEntityCard()).setPcmjXm(user.getUserName());
                    item.setSsbm(user.getDeptName());
                    item.setSsbmid(String.valueOf(user.getDeptId()));
                    item.setSsbmdm(user.getDeptCode());
                    item.setSsxgaj(user.getFxjDeptName());
                    item.setSsxgajid(String.valueOf(user.getFxjDeptId()));
                    item.setSsxgajdm(user.getFxjDeptCode());
                    item.setSssgaj(user.getDszDeptName());
                    item.setSssgajid(String.valueOf(user.getDszDeptId()));
                    item.setSssgajdm(user.getDszDeptCode());
                    item.setZdch(dto.getZdch());
                    item.setZdxh(dto.getZdxh());
                    item.setZdsim(dto.getZdsim());
                    if (dto.getJd() == null || dto.getWd() == null) {
                        // 默认为县公安局经纬度
                        dto.setJd(Constant.JD).setWd(Constant.WD);
                        item.setJd(Constant.JD).setWd(Constant.WD);
                    }

                    StringBuilder rybqdm = new StringBuilder();
                    StringBuilder rybq = new StringBuilder();
                    if (zdbqNum == 2) {
                        // 查询是否重点人员
                        rybqdm.append("重点人员").append(",");
                        rybq.append("ZDRY").append(",");
                        // 保存人员标签信息
                        TbHcBpcryBq bq = new TbHcBpcryBq();
                        bq.setPcywid(item.getId());
                        bq.setBqmc("重点人员");
                        bq.setBqbh("ZDRY");
                        bq.setXtSjly("1");
                        bq.setSsbmdm(String.valueOf(user.getDeptId()));
                        bq.setSsbm(user.getDeptName());
                        bq.setSsxgajdm(String.valueOf(user.getFxjDeptId()));
                        bq.setSsxgaj(user.getFxjDeptName());
                        bq.setSssgajdm(String.valueOf(user.getDszDeptId()));
                        bq.setSssgaj(user.getDszDeptName());
                        this.tbHcBpcryBqMapper.insert(bq);
                        vo.setPcbqsm("该人员为被盗抢人员，请使用移动警务终端查看详情");
                    }else if (zdbqNum == 3) {
                        rybqdm.append("临控人员").append(",");
                        rybq.append("LKRY").append(",");
                        // 保存人员标签信息
                        TbHcBpcryBq bq = new TbHcBpcryBq();
                        bq.setPcywid(item.getId());
                        bq.setBqmc("临控人员");
                        bq.setBqbh("LKRY");
                        bq.setXtSjly("1");
                        bq.setSsbmdm(String.valueOf(user.getDeptId()));
                        bq.setSsbm(user.getDeptName());
                        bq.setSsxgajdm(String.valueOf(user.getFxjDeptId()));
                        bq.setSsxgaj(user.getFxjDeptName());
                        bq.setSssgajdm(String.valueOf(user.getDszDeptId()));
                        bq.setSssgaj(user.getDszDeptName());
                        this.tbHcBpcryBqMapper.insert(bq);
                        vo.setPcbqsm("该人员为临控人员，请使用移动警务终端查看详情");
                    }else{
                        vo.setPcbqsm("正常人员");
                    }
                    item.setBqmc(rybq.toString().length() > 0 ? rybq.substring(0, rybq.toString().length() - 1) : "");
                    item.setBqxxsj(rybqdm.toString().length() > 0 ? rybqdm.substring(0, rybqdm.toString().length() - 1) : "");
                    item.setZb(JtsUtils.getPoint(dto.getJd(), dto.getWd())).setZbhash(GeoHashKit.encode(dto.getJd(), dto.getWd()));
                    item.setPcclJg("9");
                    item.setPcclJgmc("盘查");
                    this.baseMapper.insertEntity(item);

                    BeanUtils.copyProperties(item, vo);
                    return vo;
                }
            }
        }
        return null;
    }

    // 根据身份证号查询
    private TbHcBpcryVo selectRyBySfz(TbHcBpcryQuery dto, UserInfo user, TbHcBpcry item) {
        //先查询两个小时前自己是否查询过此人
        TbHcBpcry tbHcBpcry = this.baseMapper.selectOne(new LambdaQueryWrapper<TbHcBpcry>()
                .eq(TbHcBpcry::getSfzh, dto.getSfzh())
                .ge(TbHcBpcry::getPcsj, DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "H", -2), "02"))
                .eq(TbHcBpcry::getPcmjSfzh, user.getIdEntityCard()).last(" limit 1")
        );
        TbHcBpcryVo vo = new TbHcBpcryVo();
        if (ObjectUtils.isNotEmpty(tbHcBpcry)) {
            BeanUtils.copyProperties(tbHcBpcry, vo);
            return vo;
        } else {
            RypcVo ry = this.getRyBySfz(dto.getSfzh(), user);
            if (ry != null && StringUtils.isNotBlank(ry.getSfzh())) {
                item.setId(UUIDGenerator.getUUID())
                        .setSfzh(ry.getSfzh())
                        .setXm(ry.getXm())
                        .setXbdm(ry.getXb())
                        .setCsrq(
                                ry.getSfzh().substring(6, 10) + "-" +
                                        ry.getSfzh().substring(10, 12) + "-" +
                                        ry.getSfzh().substring(12, 14)
                        ).setMzdm(ry.getMz())
                        .setWhcddm(ry.getWhcd())
                        .setJgdm(ry.getJgssx())
                        .setZzxz(ry.getZzxz())
                        .setPcrq(new Date())
                        .setPcsj(new Date())
                        .setXtSjly("2");
                item.setXjzdz(ry.getZzxz());
                item.setPcmjId(String.valueOf(user.getUserId())).setPcmjJh(user.getInDustRialId())
                        .setPcmjSfzh(user.getIdEntityCard()).setPcmjXm(user.getUserName());
                item.setSsbm(user.getDeptName());
                item.setSsbmid(String.valueOf(user.getDeptId()));
                item.setSsbmdm(user.getDeptCode());
                item.setSsxgaj(user.getFxjDeptName());
                item.setSsxgajid(String.valueOf(user.getFxjDeptId()));
                item.setSsxgajdm(user.getFxjDeptCode());
                item.setSssgaj(user.getDszDeptName());
                item.setSssgajid(String.valueOf(user.getDszDeptId()));
                item.setSssgajdm(user.getDszDeptCode());

                item.setZdch(dto.getZdch());
                item.setZdxh(dto.getZdxh());
                item.setZdsim(dto.getZdsim());


                if (dto.getJd() == null || dto.getWd() == null) {
                    // 默认为县公安局经纬度
                    dto.setJd(Constant.JD).setWd(Constant.WD);
                    item.setJd(Constant.JD).setWd(Constant.WD);
                }
                item.setZb(JtsUtils.getPoint(dto.getJd(), dto.getWd()))
                        .setZbhash(GeoHashKit.encode(dto.getJd(), dto.getWd()));
                item.setPcclJg("9");
                item.setPcclJgmc("盘查");
                // 保存盘查数据
                this.baseMapper.insertEntity(item);

                // 保存信息到人员要素中
                this.saveRyYs(item);
                BeanUtils.copyProperties(item, vo);
            }
            if (ObjectUtils.isNotEmpty(vo)) {
                // 查询该人物的特征标签
                List<TbHcBpcryTzbq> tzList = this.tbHcBpcryTzbqMapper.selectList(
                        new LambdaQueryWrapper<TbHcBpcryTzbq>()
                                .eq(TbHcBpcryTzbq::getRysfzh, vo.getSfzh())
                );
                tzList = tzList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(TbHcBpcryTzbq::getTzbqdm))), ArrayList::new));
                vo.setTzList(tzList);
                return vo;

            }

        }
        return null;
    }

    // 保存信息到人员盘查库中
    private void saveRyYs(TbHcBpcry ry) {
        TbYsRyVo vo = this.tbYszxAdapRemoteService.getRyInfo(ry.getSfzh());
        TbYsRyDto dto = new TbYsRyDto();
        dto.setZjzl("1");
        dto.setZjhm(ry.getSfzh());
        dto.setXm(ry.getXm());
        dto.setCsrq(
                DateUtils.strToDate((ry.getSfzh().substring(6, 10) + "-" +
                        ry.getSfzh().substring(10, 12) + "-" +
                        ry.getSfzh().substring(12, 14)), "01")
        );
        dto.setMz(ry.getMzdm());
        dto.setJg(ry.getJgdm());
        dto.setHjdXzqh(ry.getSfzh().substring(0, 6));
        dto.setHjdXz(ry.getZzxz());
        dto.setJzdXzqh(ry.getSfzh().substring(0, 6));
        dto.setJzdXz(ry.getZzxz());
        dto.setLybm("tb_hc_bpcry");
        dto.setLyid(ry.getId());
        if (vo == null) {
            dto.setId(UUIDGenerator.getUUID());
            this.tbYszxAdapRemoteService.addRyYs(dto);
        } else {
            BeanUtils.copyProperties(vo, dto);
            this.tbYszxAdapRemoteService.updateRyYs(dto);
        }
    }

    // 保存信息到巡逻盘查库中
    private void saveRyToXlpc(TbHcBpcry item, UserInfo user) {
        BpcrySaveDto dto = new BpcrySaveDto();
        BeanUtils.copyProperties(item, dto);
        dto.setPcsj(DateUtils.getQueryDateString(item.getPcsj(), "02"));
        dto.setPcdjd(item.getJd().doubleValue());
        dto.setPcdwd(item.getWd().doubleValue());
        dto.setIndustrialid(item.getPcmjJh());
        dto.setUserid(item.getPcmjSfzh());
        dto.setUsername(item.getPcmjXm());
        dto.setSsdwdm(user.getDeptCode());
        dto.setSsdwmc(user.getDeptName());
        dto.setSsfsxdm(user.getFxjDeptCode());
        dto.setSsfsxmc(user.getFxjDeptName());
        dto.setSsdszdm(user.getDszDeptCode());
        dto.setSsdszmc(user.getDszDeptName());
        dto.setPccljg(item.getPcclJg());
        dto.setPccljgmc(item.getPcclJgmc());
        dto.setGlxtdm("73"); //德阳巡防
        try {
            Map map = Kit.beanToMap(dto);
            HttpUtils.executePost(Constant.XLPC_URL + "kkpcPczqBpcryxxb/save", map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 查询布控人员信息
    private BkryVo getBkry(String sfzh, UserInfo user) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("sfzh", sfzh);
            params.put("kkid", "");
            params.put("kkmc", "");
            params.put("userid", user.getIdEntityCard());
            params.put("username", user.getUserName());
            params.put("ssdwdm", user.getDeptCode());
            params.put("ssdwmc", user.getDeptName());
            params.put("ssfsxdm", user.getFxjDeptCode());
            params.put("ssfsxmc", user.getFxjDeptName());
            params.put("ssdszdm", user.getDszDeptCode());
            params.put("ssdszmc", user.getDszDeptName());
            params.put("industrialid", user.getInDustRialId());
            params.put("mobile", "");
            String result = HttpUtils.executePost(Constant.XLPC_URL + "lkRyxx/queryDetail", params);
            if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
                JSONObject json = JSONObject.parseObject(result);
                String code = json.getString("code");
                if ("0".equals(code)) {
                    String dataStr = json.getString("data");
                    return JSONObject.parseObject(dataStr, BkryVo.class);
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 查询是否情报重点人员
    private List<Map> getQbzdry(String sfzh, UserInfo user) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("sfzh", sfzh);
            params.put("userid", user.getIdEntityCard());
            params.put("username", user.getUserName());
            params.put("ssdwdm", user.getDeptCode());
            params.put("ssdwmc", user.getDeptName());
            params.put("ssfsxdm", user.getFxjDeptCode());
            params.put("ssfsxmc", user.getFxjDeptName());
            params.put("ssdszdm", user.getDszDeptCode());
            params.put("ssdszmc", user.getDszDeptName());
            params.put("industrialid", user.getInDustRialId());
            params.put("mobile", "");
            String result = HttpUtils.executePost(Constant.XLPC_URL + "requestservice/qbZdry/queryDetail", params);
            if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
                JSONObject json = JSONObject.parseObject(result);
                String code = json.getString("code");
                if ("0".equals(code)) {
                    String dataStr = json.getString("data");
                    return JSONObject.parseArray(dataStr, Map.class);
                }
            }
            return new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    // 根据身份证号查询人员信息
    private RypcVo getRyBySfz(String sfzh, UserInfo user) {
        try {
            TbYsRyVo vo = null;
            // 先查询人员要素表中的数据，如果存在，直接返回
//            if ("520109".equals(user.getDeptCode().substring(0, 6))) {
//                vo = this.tbYszxAdapRemoteService.getRyInfo(sfzh);
//            }
            if (vo != null) {
                RypcVo pc = new RypcVo();
                pc.setCsrq(
                        sfzh.substring(6, 10) + "-" +
                                sfzh.substring(10, 12) + "-" +
                                sfzh.substring(12, 14)
                );
                int a = Integer.parseInt(sfzh.substring(16, 17)) % 2;
                pc.setXb(a % 2 == 0 ? "2" : "1");
                pc.setMz(vo.getMz());
                pc.setSfzh(vo.getZjhm());
                pc.setXm(vo.getXm());
                pc.setZzxz(vo.getJzdXz());
                pc.setJgssx(vo.getHjdXzqh());
                return pc;
            }
            Map<String, Object> params = new HashMap<>();
            params.put("sfzh", sfzh);
            params.put("userid", user.getIdEntityCard());
            params.put("username", user.getUserName());
            params.put("ssdwdm", user.getDeptCode());
            params.put("ssdwmc", user.getDeptName());
            params.put("ssfsxdm", user.getFxjDeptCode());
            params.put("ssfsxmc", user.getFxjDeptName());
            params.put("ssdszdm", user.getDszDeptCode());
            params.put("ssdszmc", user.getDszDeptName());
            params.put("industrialid", user.getInDustRialId());
            params.put("mobile", "");
            String result = HttpUtils.executePost(Constant.XLPC_URL + "requestservice/czrk/queryDetail", params);
            if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
                JSONObject json = JSONObject.parseObject(result);
                String code = json.getString("code");
                String dataStr = json.getString("data");
                if ("0".equals(code)) {
                    JSONObject resJson = JSONObject.parseObject(dataStr);
                    return JSON.toJavaObject(resJson, RypcVo.class);
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取人员重点标签状态（从内网中查询）
     * @param dto 人员盘查DTO
     * @param user 用户信息
     * @return 人员重点标签状态
     */
    private Integer getRyZdbqZtFromNw(TbHcBpcryQuery dto, UserInfo user){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sfzh", dto.getSfzh());
        paramMap.put("userName", user.getUserName());
        paramMap.put("inDustRialId", user.getInDustRialId());
        paramMap.put("idEntityCard", user.getIdEntityCard());
        paramMap.put("phone", user.getPhone());
        paramMap.put("deptName", user.getDeptName());
        paramMap.put("deptCode", user.getDeptCode());
        paramMap.put("fxjDeptName", user.getFxjDeptName());
        paramMap.put("fxjDeptCode", user.getFxjDeptCode());
        paramMap.put("dszDeptName", user.getDszDeptName());
        paramMap.put("dszDeptCode", user.getDszDeptCode());
        paramMap.put("zdxh", dto.getZdxh());
        paramMap.put("zdch", dto.getZdch());
        paramMap.put("zdsim", dto.getZdsim());
        paramMap.put("jd", dto.getJd());
        paramMap.put("wd", dto.getWd());

        String sync = OkHttpUtils.builder().url(Constant.NW_URL)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addParam("ywlx", "ZY")
                .addParam("url", Constant.NW_RYZDBQ_URL)
                .addParam("token", "46296c279b51420cb64bd5cb6d8ec3d8")
                .addParam("sbid", "ZY")
                .addParam("sbzid", "ZY")
                .addParam("data", paramMap)
                .post(true)
                .sync();
        if (com.mosty.common.base.util.StringUtils.isNotBlank(sync)) {
            JSONObject json = JSONObject.parseObject(sync);
            String errno = json.getString("errno");
            String dataStr = json.getString("data");
            if ("0".equals(errno)) {
                JSONObject dataJson = JSONObject.parseObject(dataStr);
                return Integer.parseInt(dataJson.getString("code"));
            }
        }
        return -1;
    }

    @Override
    @Transactional
    public TbHcBpcryVo saveBpcryNfc(TbHcBpcry bpcry) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录");
        }
        bpcry.setId(UUIDGenerator.getUUID());
        bpcry.setPcmjId(String.valueOf(user.getUserId())).setPcmjJh(user.getInDustRialId())
                .setPcmjSfzh(user.getIdEntityCard()).setPcmjXm(user.getUserName());
        bpcry.setSsbm(user.getDeptName());
        bpcry.setSsbmid(String.valueOf(user.getDeptId()));
        bpcry.setSsbmdm(user.getDeptCode());
        bpcry.setSsxgaj(user.getFxjDeptName());
        bpcry.setSsxgajid(String.valueOf(user.getFxjDeptId()));
        bpcry.setSsxgajdm(user.getFxjDeptCode());
        bpcry.setSssgaj(user.getDszDeptName());
        bpcry.setSssgajid(String.valueOf(user.getDszDeptId()));
        bpcry.setSssgajdm(user.getDszDeptCode());
        bpcry.setXtSjly("2");
        bpcry.setPcrq(new Date());
        bpcry.setPcsj(new Date());
        bpcry.setCsrq(
                bpcry.getSfzh().substring(6, 10) + "-" +
                        bpcry.getSfzh().substring(10, 12) + "-" +
                        bpcry.getSfzh().substring(12, 14)
        );

        if (bpcry.getJd() == null || bpcry.getWd() == null) {
            // 默认为县公安局经纬度
            bpcry.setJd(Constant.JD).setWd(Constant.WD);

            bpcry.setZb(JtsUtils.getPoint(bpcry.getJd(), bpcry.getWd()));
            bpcry.setZbhash(GeoHashKit.encode(bpcry.getJd(), bpcry.getWd()));
        }

        bpcry.setPcclJg("9");
        bpcry.setPcclJgmc("盘查");
        // 查询当月数量
        this.baseMapper.insertEntity(bpcry);
//        // 保存信息到巡逻盘查库中
//        this.saveRyToXlpc(bpcry, user);
        // 保存信息到人员要素中
        this.saveRyYs(bpcry);
        TbHcBpcryVo vo = new TbHcBpcryVo();
        BeanUtils.copyProperties(bpcry, vo);
        // 查询该人物的特征标签
        List<TbHcBpcryTzbq> tzList = this.tbHcBpcryTzbqMapper.selectList(
                new LambdaQueryWrapper<TbHcBpcryTzbq>()
                        .eq(TbHcBpcryTzbq::getRysfzh, vo.getSfzh())
        );
        tzList = tzList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(TbHcBpcryTzbq::getTzbqdm))), ArrayList::new));
        vo.setTzList(tzList);
        return vo;
    }


    @Override
    @Transactional
    public void saveBpcry(TbHcBpcryInsertDto dto) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录");
        }
        if (StringUtils.isBlank(dto.getId())) {
            throw new BusinessException("盘查Id不存在");
        }
        TbHcBpcry ry = this.baseMapper.selectById(dto.getId());
        if (ry == null) {
            throw new BusinessException("盘查对象不存在");
        }
        ry.setPcclJg(dto.getPcclJg());
        ry.setPcclJgmc(dto.getPcclJgmc());
        ry.setPcclYjdwdm(dto.getPcclYjdwdm());
        ry.setPcclYjdw(dto.getPcclYjdw());
        ry.setPcclYjyy(dto.getPcclYjyy());
        ry.setPcclId(dto.getPcclId());
        // 查询当月数量
        ry.setSsdwdycs(0);
        this.baseMapper.updateEntity(ry);
        // 保存图片信息
        List<String> tpIdList = dto.getTpIdList();
        this.saveTp(tpIdList, "tb_hc_bpcry", ry.getId());
        // 保存物品信息
        List<TbHcBpcryWpVo> ryWpList = dto.getRyWpList();
        this.saveRyTp(ryWpList, ry);
        // 保存人员特征标签信息
        List<TbHcBpcryTzbq> tzbqList = dto.getTzbqList();
        this.saveTzbq(tzbqList, ry);
//        // 保存信息到巡逻盘查库中
//        this.saveRyToXlpc(ry, user);
    }


    @Override
    public Map<String, Object> getRyBqBySfzh(String sfzh) {
        UserInfo user = UserInfoManager.get();
        // 查询是否重点人员
        List<Map> zdryList = this.getQbzdry(sfzh, user);
        StringBuilder rybqdm = new StringBuilder();
        StringBuilder rybq = new StringBuilder();
        if (zdryList != null && zdryList.size() > 0) {
            zdryList.forEach(it -> {
                rybqdm.append(it.get("matchname")).append(",");
                rybq.append(it.get("matchtype")).append(",");
            });
        }
        // 查询是否布控人员
        BkryVo bkryVo = this.getBkry(sfzh, user);
        if (bkryVo != null) {
            rybqdm.append("临控人员").append(",");
            rybq.append("LKRY").append(",");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("bqmc", rybq.toString().length() > 0 ? rybq.substring(0, rybq.toString().length() - 1) : "");
        map.put("bqxxsj", rybqdm.toString().length() > 0 ? rybqdm.substring(0, rybqdm.toString().length() - 1) : "");
        return map;
    }


    @Override
    public Map<String, Object> getRyBq(String id) {
        UserInfo user = UserInfoManager.get();
        TbHcBpcry item = this.baseMapper.selectById(id);
        // 查询是否重点人员
        List<Map> zdryList = this.getQbzdry(item.getSfzh(), user);
        StringBuilder rybqdm = new StringBuilder();
        StringBuilder rybq = new StringBuilder();
        if (zdryList != null && zdryList.size() > 0) {
            zdryList.forEach(it -> {
                rybqdm.append(it.get("matchname")).append(",");
                rybq.append(it.get("matchtype")).append(",");
                // 保存人员标签信息
                TbHcBpcryBq bq = new TbHcBpcryBq();
                bq.setPcywid(item.getId());
                bq.setBqmc(it.get("matchtype").toString());
                bq.setBqbh(it.get("matchname").toString());
                bq.setXtSjly("1");
                bq.setSsbmdm(String.valueOf(user.getDeptId()));
                bq.setSsbm(user.getDeptName());
                bq.setSsxgajdm(String.valueOf(user.getFxjDeptId()));
                bq.setSsxgaj(user.getFxjDeptName());
                bq.setSssgajdm(String.valueOf(user.getDszDeptId()));
                bq.setSssgaj(user.getDszDeptName());


                this.tbHcBpcryBqMapper.insert(bq);
                // 修改人员标签要素表中的数据
                TbYsRyBqUpdateDto dto = new TbYsRyBqUpdateDto();
                dto.setSfzh(item.getSfzh());
                dto.setBqdm(it.get("matchname").toString());
                dto.setBqmc(it.get("matchtype").toString());
                this.tbYszxAdapRemoteService.updateRyBqYs(dto);
            });
        }
        // 查询是否布控人员
        BkryVo bkryVo = this.getBkry(item.getSfzh(), user);
        if (bkryVo != null) {
            rybqdm.append("临控人员").append(",");
            rybq.append("LKRY").append(",");
            // 保存人员标签信息
            TbHcBpcryBq bq = new TbHcBpcryBq();
            bq.setPcywid(item.getId());
            bq.setBqmc("临控人员");
            bq.setBqbh("LKRY");
            bq.setXtSjly("1");

            bq.setSsbmdm(String.valueOf(user.getDeptId()));
            bq.setSsbm(user.getDeptName());
            bq.setSsxgajdm(String.valueOf(user.getFxjDeptId()));
            bq.setSsxgaj(user.getFxjDeptName());
            bq.setSssgajdm(String.valueOf(user.getDszDeptId()));
            bq.setSssgaj(user.getDszDeptName());


            this.tbHcBpcryBqMapper.insert(bq);
            // 修改人员标签要素表中的数据
            TbYsRyBqUpdateDto dto = new TbYsRyBqUpdateDto();
            dto.setSfzh(item.getSfzh());
            dto.setBqdm("LKRY");
            dto.setBqmc("临控人员");
            this.tbYszxAdapRemoteService.updateRyBqYs(dto);
        }
        item.setBqmc(rybq.toString().length() > 0 ? rybq.substring(0, rybq.toString().length() - 1) : "");
        item.setBqxxsj(rybqdm.toString().length() > 0 ? rybqdm.substring(0, rybqdm.toString().length() - 1) : "");
        this.baseMapper.updateEntity(item);
//        //在这里推送数据到巡逻盘查 带上标签的推送 不能再核查哪里直接推送要出问题呢
//        this.saveRyToXlpc(item, user);

        Map<String, Object> map = new HashMap<>();
        map.put("bqmc", item.getBqmc());
        map.put("bqxxsj", item.getBqxxsj());
        return map;
    }

//    private final String[] jmxzjqList = new String[]{"02030200", "02030300", "02030400", "02030500", "02040100", "02050100",
//            "02050400", "02121700", "02130000"};

    /**
     * 泸州态势统计-各区县盘查工作
     *
     * @param dto
     * @return 10111    泸州机场分局
     * 10929	江阳区分局
     * 11336	龙马潭区分局
     * 11379	纳溪区
     * 11382	泸县
     * 11436	合江县
     * 11503	叙永县
     * 11531	古蔺县
     */
    @Override
    public Map<String, Object> getGqxpc(RyClTjQuery 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>> ryList = this.baseMapper.selectPcryTj(dto.getKssj(), dto.getJssj());
        // 盘查车辆
        List<Map<String, Object>> clList = this.tbHcBpcclMapper.selectPcclTj(dto.getKssj(), dto.getJssj());
        // 重点人员
        List<Map<String, Object>> zdryList = this.baseMapper.selectZdryTj(dto.getKssj(), dto.getJssj());
        // 重点车辆
        List<Map<String, Object>> zdclList = this.tbHcBpcclMapper.selectZdclTj(dto.getKssj(), dto.getJssj());

        List<Map<String, Object>> ryResList = new ArrayList<>();
        List<Map<String, Object>> clResList = new ArrayList<>();
        List<Map<String, Object>> zdryResList = new ArrayList<>();
        List<Map<String, Object>> zdclResList = new ArrayList<>();
        ssxgajxx.keySet().forEach(item -> {
            // 人员
            Map<String, Object> resMap = new HashMap<>();
            List<Map<String, Object>> list = ryList.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (list.size() == 1) {
                resMap.put("count", list.get(0).get("count"));
            } else {
                resMap.put("count", 0);
            }
            ryResList.add(resMap);

            // 车
            resMap = new HashMap<>();
            List<Map<String, Object>> cllist1 = clList.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (cllist1.size() == 1) {
                resMap.put("count", cllist1.get(0).get("count"));
            } else {
                resMap.put("count", 0);
            }
            clResList.add(resMap);

            // 重点人员
            resMap = new HashMap<>();
            List<Map<String, Object>> zdrylist1 = zdryList.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (zdrylist1.size() == 1) {
                resMap.put("count", zdrylist1.get(0).get("count"));
            } else {
                resMap.put("count", 0);
            }
            zdryResList.add(resMap);
            // 重点车辆
            resMap = new HashMap<>();
            List<Map<String, Object>> zdcllist1 = zdclList.stream().filter(it -> String.valueOf(it.get("ssxgajid")).equals(item)).collect(Collectors.toList());
            resMap.put("ssxgaj", ssxgajxx.get(item));
            resMap.put("ssxgajid", item);
            if (zdcllist1.size() == 1) {
                resMap.put("count", zdcllist1.get(0).get("count"));
            } else {
                resMap.put("count", 0);
            }
            zdclResList.add(resMap);
        });
        map.put("ryResList", ryResList);
        map.put("clResList", clResList);
        map.put("zdryResList", zdryResList);
        map.put("zdclResList", zdclResList);
        return map;
    }

    @Override
    public List<RyZpSearchVo> getRyListByZp(MultipartFile file) {
        if (file == null) {
            return new ArrayList<>();
        }
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录");
        }
        String base64 = Kit.fileToBase64(file);
        Map<String, Object> params = new HashMap<>();
        params.put("xp", base64);
        params.put("userid", user.getIdEntityCard());
        params.put("username", user.getUserName());
        params.put("ssdwdm", user.getDeptCode());
        params.put("ssdwmc", user.getDeptName());
        params.put("ssfsxdm", user.getFxjDeptCode());
        params.put("ssfsxmc", user.getFxjDeptName());
        params.put("ssdszdm", user.getDszDeptCode());
        params.put("ssdszmc", user.getDszDeptName());
        params.put("industrialid", user.getInDustRialId());
        params.put("mobile", "");
        String result = HttpUtils.executePost(Constant.XLPC_URL + "kkpcPczqZp/queryYtRxbd", params);
        if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            String code = json.getString("code");
            if ("0".equals(code)) {
                String dataStr = json.getString("data");
                List<RyZpSearchVo> list = JSONObject.parseArray(dataStr, RyZpSearchVo.class);
                if (!CollectionUtils.isEmpty(list)) {
                    list.forEach(item -> {
                        // 查询人像图片
                        item.setUrl(Constant.XLPC_URL + "kkpcPczqZp/getYtImg.jpg?uri_base64=" + item.getXp());
                    });
                }
                return list;
            }
        }
        return new ArrayList<>();
    }

    @Override
    public List<Map> getRyListBySjhm(String mobile) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录");
        }
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("mobile", mobile);
            params.put("userid", user.getIdEntityCard());
            params.put("username", user.getUserName());
            params.put("ssdwdm", user.getDeptCode());
            params.put("ssdwmc", user.getDeptName());
            params.put("ssfsxdm", user.getFxjDeptCode());
            params.put("ssfsxmc", user.getFxjDeptName());
            params.put("ssdszdm", user.getDszDeptCode());
            params.put("ssdszmc", user.getDszDeptName());
            params.put("industrialid", user.getInDustRialId());
            String result = HttpUtils.executePost(Constant.XLPC_URL + "requestservice/czrk/queryListByMobile", params);
            if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
                JSONObject json = JSONObject.parseObject(result);
                String code = json.getString("code");
                if ("0".equals(code)) {
                    String dataStr = json.getString("data");
                    return JSONObject.parseArray(dataStr, Map.class);
                }
            }
            return new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Integer> getRypcCount(TbHcBpcryQuery dto) {
        if (StringUtils.isBlank(dto.getJssj()) && StringUtils.isBlank(dto.getKssj())) {
            String systemDateString = DateUtils.getSystemDateString();
            dto.setKssj(systemDateString);
            dto.setJssj(systemDateString);
        }
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        Map<String, Object> map = new HashMap<>();
        Map<String, Integer> ryMap = new HashMap<>();
        dto.setPcclJg("");
        map.put("dto", dto);
        int All = this.baseMapper.getCountRy(map);
        ryMap.put("All", All);
        dto.setPcclJg("1");
        map.put("dto", dto);
        int fx = this.baseMapper.getCountRy(map);
        ryMap.put("fx", fx);
        dto.setPcclJg("2");
        map.put("dto", dto);
        int yj = this.baseMapper.getCountRy(map);
        ryMap.put("yj", yj);
        dto.setPcclJg("9");
        map.put("dto", dto);
        int pc = this.baseMapper.getCountRy(map);
        ryMap.put("pc", pc);
        return ryMap;
    }

    @Override
    public IPage<TbHcBpcryVo> getRypcList(TbHcBpcryQuery dto) {
        if (StringUtils.isBlank(dto.getJssj()) && StringUtils.isBlank(dto.getKssj())) {
            String systemDateString = DateUtils.getSystemDateString();
            dto.setKssj(systemDateString);
            dto.setJssj(systemDateString);
        }
        IPage<TbHcBpcryVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        int count = this.baseMapper.getCountRy(map);
        List<TbHcBpcry> list = this.baseMapper.getListRy(map);
        List<TbHcBpcryVo> rList = new ArrayList<>();
        list.forEach(item -> {
            TbHcBpcryVo vo = new TbHcBpcryVo();
            BeanUtils.copyProperties(item, vo);
            // 查询人员照片信息
            List<TbHcTp> tpList = this.tbHcTpMapper.selectList(
                    new LambdaQueryWrapper<TbHcTp>()
                            .eq(TbHcTp::getLybm, "tb_hc_bpcry")
                            .eq(TbHcTp::getLyid, item.getId())
                            .orderByAsc(TbHcTp::getOrderno)
            );
            if(!CollectionUtils.isEmpty(tpList)){
                List<TbHcTpVo> collect = tpList.stream().map(v -> {
                    TbHcTpVo tbHcTpVo = new TbHcTpVo();
                    BeanUtils.copyProperties(v, tbHcTpVo);
                    return tbHcTpVo;
                }).collect(Collectors.toList());
                vo.setTpList(collect);
            }
            // 查询物品信息
            List<TbHcBpcryWp> wpList = this.tbHcBpcryWpMapper.selectList(
                    new LambdaQueryWrapper<TbHcBpcryWp>()
                            .eq(TbHcBpcryWp::getPcywid, item.getId())
            );
            List<TbHcBpcryWpVo> wpVoList = new ArrayList<>();
            wpList.forEach(wp -> {
                TbHcBpcryWpVo wpVo = new TbHcBpcryWpVo();
                BeanUtils.copyProperties(wp, wpVo);
                // 获取物品图片
                List<TbHcTp> wpTpList = this.tbHcTpMapper.selectList(
                        new LambdaQueryWrapper<TbHcTp>()
                                .eq(TbHcTp::getLybm, "tb_hc_bpcry_wp")
                                .eq(TbHcTp::getLyid, wp.getId())
                                .orderByAsc(TbHcTp::getOrderno)
                );
                List<String> wpTpIdList = wpTpList.stream().map(TbHcTp::getFjid).collect(Collectors.toList());
                wpVo.setWpTpIdList(wpTpIdList);
                wpVoList.add(wpVo);
            });
            vo.setWpVoList(wpVoList);
            rList.add(vo);
        });
        page.setTotal(count);
        page.setRecords(rList);
        return page;
    }

    @Override
    public List<TbHcBpcryVo> getRyOf2h() {
        UserInfo user = UserInfoManager.get();
        if (user != null) {
            String sfzh = user.getIdEntityCard();
            // 两小时之前
            String time = DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "H", -1), "02");
            List<TbHcBpcry> list = this.baseMapper.getRyOf2h(sfzh, time);
            List<TbHcBpcryVo> voList = new ArrayList<>();
            list.forEach(item -> {
                TbHcBpcryVo vo = new TbHcBpcryVo();
                BeanUtils.copyProperties(item, vo);
                voList.add(vo);
            });
            return voList;
        }
        return new ArrayList<>();
    }

    // 保存人员特征标签信息
    private void saveTzbq(List<TbHcBpcryTzbq> tzbqList, TbHcBpcry ry) {
        this.tbHcBpcryTzbqMapper.delete(
                new LambdaQueryWrapper<TbHcBpcryTzbq>()
                        .eq(TbHcBpcryTzbq::getRysfzh, ry.getSfzh())
        );
        if (!CollectionUtils.isEmpty(tzbqList)) {
            tzbqList.forEach(bq -> {
                bq.setId(UUIDGenerator.getUUID());
                bq.setPcywid(ry.getId());
                bq.setXtSjly("1");
                this.tbHcBpcryTzbqMapper.insert(bq);
            });
        }
    }

    // 保存人员物品列表信息
    private void saveRyTp(List<TbHcBpcryWpVo> ryWpList, TbHcBpcry ry) {
        if (!CollectionUtils.isEmpty(ryWpList)) {
            ryWpList.forEach(wpVo -> {
                TbHcBpcryWp wp = new TbHcBpcryWp();
                BeanUtils.copyProperties(wpVo, wp);
                wp.setId(UUIDGenerator.getUUID());
                wp.setPcywid(ry.getId());
                wp.setXtSjly("2");
                wp.setSsbmdm(ry.getSsbmdm());
                wp.setSsbm(ry.getSsbm());
                wp.setSsbmid(ry.getSsbmid());
                wp.setSsxgajdm(ry.getSsxgajdm());
                wp.setSsxgaj(ry.getSsxgaj());
                wp.setSsxgajid(ry.getSsxgajid());
                wp.setSssgajdm(ry.getSssgajdm());
                wp.setSssgaj(ry.getSssgaj());
                wp.setSssgajid(ry.getSssgajid());

                this.tbHcBpcryWpMapper.insert(wp);
                // 保存物品图片
                List<String> wpTpIdList = wpVo.getWpTpIdList();
                this.saveTp(wpTpIdList, "tb_hc_bpcry_wp", wp.getId());
            });
        }
    }

    // 保存图片信息
    private void saveTp(List<String> tpIdList, String lybm, String lyid) {
        if (!CollectionUtils.isEmpty(tpIdList)) {
            tpIdList.forEach(item -> {
                TbHcTp tp = new TbHcTp();
                tp.setId(UUIDGenerator.getUUID());
                tp.setLybm(lybm);
                tp.setLyid(lyid);
                tp.setXtSjly("2");
                tp.setFjid(item);
                this.tbHcTpMapper.insert(tp);
            });
        }
    }

    @Override
    public List<RyZpSearchVo> getRyListByBase64(String base64Str) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("xp", base64Str);
        params.put("userid", user.getIdEntityCard());
        params.put("username", user.getUserName());
        params.put("ssdwdm", user.getDeptCode());
        params.put("ssdwmc", user.getDeptName());
        params.put("ssfsxdm", user.getFxjDeptCode());
        params.put("ssfsxmc", user.getFxjDeptName());
        params.put("ssdszdm", user.getDszDeptCode());
        params.put("ssdszmc", user.getDszDeptName());
        params.put("industrialid", user.getInDustRialId());
        params.put("mobile", "");
        String result = HttpUtils.executePost(Constant.XLPC_URL + "kkpcPczqZp/queryYtRxbd", params);
        if (com.mosty.common.base.util.StringUtils.isNotBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            String code = json.getString("code");
            if ("0".equals(code)) {
                String dataStr = json.getString("data");
                List<RyZpSearchVo> list = JSONObject.parseArray(dataStr, RyZpSearchVo.class);
                if (!CollectionUtils.isEmpty(list)) {
                    list.forEach(item -> {
                        // 查询人像图片
                        item.setUrl(Constant.XLPC_URL + "kkpcPczqZp/getYtImg.jpg?uri_base64=" + item.getXp());
                    });
                }
                return list;
            }
        }
        return new ArrayList<>();
    }


    private void pushSse(TbHcDtgz dtgz) {
        TbHcDtgz sseMs = dtgz;
        Map<String, SseEmitter> sseCache = Constant.HcSse;
        for (String key : sseCache.keySet()) {
            String glid = StringUtils.split("_", key)[0];
            if (glid.equals(dtgz.getGlid())) {
                SseEmitter sseEmitter = Constant.HcSse.get(key);
                if (sseEmitter != null) {
                    System.out.println("SSE发送数据---》" + JSONObject.toJSONString(sseMs));
                    try {
                        sseEmitter.send(JSONObject.toJSONString(sseMs));
                    } catch (Exception e) {
                        sseCache.remove(key);
                        System.out.println("SSE发送失败-------->" + e.getMessage());
                    }
                }
            }
        }

    }

    public static String sfzhToCsrq(String sfzh) {
        try {
            return sfzh.substring(6, 10) + "-" + sfzh.substring(10, 12) + "-"
                    + sfzh.substring(12, 14);
        } catch (Exception ex) {
            return "";
        }
    }

    @Override
    public Map<String, Object> xfzgtjAll(HcTjQuery query) {
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        Map<String, Object> map = new HashMap<>();
        //总数
        int zs = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                .likeRight(TbHcBpcryBq::getSsbmdm, query.getSsbmdm())
                .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
        map.put("zs", zs);
        //查询在逃
        int zt = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                .likeRight(TbHcBpcryBq::getSsbmdm, query.getSsbmdm())
                .like(TbHcBpcryBq::getBqmc, "ZT")
                .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
        map.put("zt", zt);
        //查询临控
        int lk = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                .likeRight(TbHcBpcryBq::getSsbmdm, query.getSsbmdm())
                .like(TbHcBpcryBq::getBqmc, "LK")
                .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
        map.put("lk", lk);
        //查询涉毒
        int sd = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                .likeRight(TbHcBpcryBq::getSsbmdm, query.getSsbmdm())
                .like(TbHcBpcryBq::getBqmc, "XFD")
                .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
        map.put("sd", sd);
        //查询前科
        int qk = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                .likeRight(TbHcBpcryBq::getSsbmdm, query.getSsbmdm())
                .like(TbHcBpcryBq::getBqmc, "QK")
                .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
        map.put("qk", qk);
        map.put("qt", (zs - zt - lk - sd - qk) < 0 ? 0 : (zs - zt - lk - sd - qk));
        return map;
    }


    @Override
    public Map<String, List<Map<String, Object>>> getZgtj(HcTjQuery query) {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        if (StringUtils.isBlank(query.getKssj())) {
            query.setKssj(DateUtils.getNowDate() + " 00:00:00");
        }
        map.put("ryzg", this.baseMapper.getRyBqtj(query));
        map.put("clzg", this.baseMapper.getClBqtj(query));
        return map;
    }


    @Override
    public IPage<Map<String, Object>> xfzgtj(HcTjQuery query) {
        //首先查询部门分页 分页以后查询数据
        IPage<HcTjQuery> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        query.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), null));
        IPage<String> bmdmList = this.baseMapper.getSsbm(page, query);
        if (ObjectUtils.isNotEmpty(bmdmList) && !CollectionUtils.isEmpty(bmdmList.getRecords())) {
            List<String> records = bmdmList.getRecords();
            List<Map<String, Object>> list = new ArrayList<>();
            for (String s : records) {
                Map<String, Object> map = new HashMap<>();
                map.put("ssbmdm", s);
                DeptInfoVo deptInfoVo = this.tbBaseAdaptRemoteService.getOrgByOrgcode(s);
                map.put("ssbm", deptInfoVo.getDeptname());
                //总数
                int zs = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                        .eq(TbHcBpcryBq::getSsbmdm, s)
                        .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                        .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
                map.put("zs", zs);
                //查询在逃
                int zt = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                        .eq(TbHcBpcryBq::getSsbmdm, s)
                        .like(TbHcBpcryBq::getBqmc, "ZT")
                        .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                        .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
                map.put("zt", zt);
                //查询临控
                int lk = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                        .eq(TbHcBpcryBq::getSsbmdm, s)
                        .like(TbHcBpcryBq::getBqmc, "LK")
                        .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                        .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
                map.put("lk", lk);
                //查询涉毒
                int sd = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                        .eq(TbHcBpcryBq::getSsbmdm, s)
                        .like(TbHcBpcryBq::getBqmc, "XFD")
                        .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                        .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
                map.put("sd", sd);
                //查询前科
                int qk = this.tbHcBpcryBqMapper.selectCount(new LambdaQueryWrapper<TbHcBpcryBq>()
                        .eq(TbHcBpcryBq::getSsbmdm, s)
                        .like(TbHcBpcryBq::getBqmc, "QK")
                        .ge(StringUtils.isNotBlank(query.getKssj()), TbHcBpcryBq::getXtCjsj, query.getKssj())
                        .le(StringUtils.isNotBlank(query.getJssj()), TbHcBpcryBq::getXtCjsj, query.getJssj()));
                map.put("qk", qk);
                map.put("qt", (zs - zt - lk - sd - qk) < 0 ? 0 : (zs - zt - lk - sd - qk));
                list.add(map);
            }
            IPage<Map<String, Object>> iPage = new Page<>();
            BeanUtils.copyProperties(bmdmList, iPage);
            iPage.setRecords(list);
            return iPage;
        }
        return new Page<>();
    }

    @Override
    public Map<String, Integer> bpcryTj() {
        Map<String, Integer> ryMap = new HashMap();
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(null, null);
        Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<TbHcBpcry>()
                .likeRight(StringUtils.isNotBlank(ssbm), TbHcBpcry::getSsbmdm, ssbm)
                .ge(TbHcBpcry::getPcsj, DateUtils.getSystemDateString())
        );
        ryMap.put("all", integer);
        Integer zt = this.baseMapper.selectCount(new LambdaQueryWrapper<TbHcBpcry>()
                .likeRight(StringUtils.isNotBlank(ssbm), TbHcBpcry::getSsbmdm, ssbm)
                .ge(TbHcBpcry::getPcsj, DateUtils.getSystemDateString())
                .and(v -> v.like(TbHcBpcry::getBqmc, "ZT").or().like(TbHcBpcry::getBqmc, "在逃"))
        );
        ryMap.put("zt", zt);
        Integer sd = this.baseMapper.selectCount(new LambdaQueryWrapper<TbHcBpcry>()
                .likeRight(StringUtils.isNotBlank(ssbm), TbHcBpcry::getSsbmdm, ssbm)
                .ge(TbHcBpcry::getPcsj, DateUtils.getSystemDateString())
                .and(v -> v.like(TbHcBpcry::getBqmc, "D").or().like(TbHcBpcry::getBqmc, "毒"))
        );
        ryMap.put("sd", sd);
        return ryMap;
    }

    @Override
    public int getSjpcr(String ssbmdm, String time) {
        return this.baseMapper.selectCount(
                new LambdaQueryWrapper<TbHcBpcry>()
                        .likeRight(!StringUtils.isEmpty(ssbmdm), TbHcBpcry::getSsbmdm, ssbmdm)
                        .eq(TbHcBpcry::getPcrq, time)
        );

    }

}
