package com.mosty.base.manager.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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.manager.mapper.TbJcglXfclMapper;
import com.mosty.base.manager.mapper.TbSbGzjrMapper;
import com.mosty.base.manager.mapper.TpjcglZnzbMapper;
import com.mosty.base.manager.remote.TbBaseAdaptRemoteService;
import com.mosty.base.manager.service.TbJcglZbjlService;
import com.mosty.base.manager.service.TpjcglZnzbService;
import com.mosty.base.model.dto.base.SysMessageInfoInsertDto;
import com.mosty.base.model.dto.base.SysMessageItemInsertDto;
import com.mosty.base.model.dto.jcgl.TbJcglZnzbSearchDto;
import com.mosty.base.model.dto.qwzx.AppSearchQuery;
import com.mosty.base.model.entity.jcgl.*;
import com.mosty.base.model.query.jcgl.TbJcglZnzbQuery;
import com.mosty.base.model.query.jcgl.TbJcglZyzbQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.jcgl.TbJcglSbdwVo;
import com.mosty.base.model.vo.jcgl.TbJcglZnzbVo;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.IDCardUtil;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.base.constant.enums.DeletedEnum;
import com.mosty.common.base.exception.Asserts;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.config.entity.SysDict;
import com.mosty.common.config.entity.SysDictItem;
import com.mosty.common.config.service.SysDictItemService;
import com.mosty.common.config.service.SysDictService;
import com.mosty.common.core.business.entity.vo.SysUserDeptVO;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
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 javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
@Service
public class TpjcglZnzbServiceImpl extends ServiceImpl<TpjcglZnzbMapper, TbJcglZnzb>
        implements TpjcglZnzbService {


    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbJcglZbjlService tbJcglZbjlService;
    private final TbSbGzjrMapper tbSbGzjrMapper;
    private final TbJcglXfclMapper tbJcglXfclMapper;
    private final SysDictService sysDictService;
    private final SysDictItemService sysDictItemService;
    private final RedisService redisService;

    /**
     * 下发智能装备
     *
     * @param zb
     */
    @Override
    public void xfZnzb(TbJcglZnzb zb) {
        if (StringUtils.isNotBlank(zb.getId()) && StringUtils.isNotBlank(zb.getSsbmid())) {
            TbJcglZnzb tbJcglZnzb = this.baseMapper.selectById(zb.getId());
            DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(zb.getSsbmdm());
            tbJcglZnzb.setSsbm(dept.getDeptname());
            tbJcglZnzb.setSsbmid(dept.getDeptid());
            tbJcglZnzb.setSsbmdm(dept.getDeptcode());
            tbJcglZnzb.setSsxgajdm(dept.getFxjcode());
            tbJcglZnzb.setSsxgajid(dept.getFxjid());
            tbJcglZnzb.setSsxgaj(dept.getFxjname());
            tbJcglZnzb.setSssgaj(dept.getDszname());
            tbJcglZnzb.setSssgajdm(dept.getDszcode());
            tbJcglZnzb.setSssgajid(dept.getDszid());
            tbJcglZnzb.setXtSjly("1");
            tbJcglZnzb.setId(UUIDGenerator.getUUID());
            tbJcglZnzb.setXfid(zb.getId());
            tbJcglZnzb.setSfbs("0");
            tbJcglZnzb.setXtCjsj(new Timestamp(System.currentTimeMillis()));
            //存入装备日志
            addZbjl(tbJcglZnzb, "2");
            this.baseMapper.insert(tbJcglZnzb);
        }
    }


    /**
     * 报损
     *
     * @param
     */
    @Override
    public void bsZnzb(String id) {
        if (StringUtils.isNotBlank(id)) {
            TbJcglZnzb tbJcglZnzb = this.baseMapper.selectById(id);
            //存入装备日志
            tbJcglZnzb.setSfbs("1");
            addZbjl(tbJcglZnzb, "1");
            this.baseMapper.updateById(tbJcglZnzb);
        }
    }


    /**
     * 回退
     *
     * @param
     */
    @Override
    public void htZnzb(String id) {
        if (StringUtils.isNotBlank(id)) {
            TbJcglZnzb tbJcglZnzb = this.baseMapper.selectById(id);
            //存入装备日志
            addZbjl(tbJcglZnzb, "3");
            this.baseMapper.deleteById(tbJcglZnzb.getId());
        }
    }


    public void addZbjl(TbJcglZnzb zb, String sjly) {
        TbJcglZbjl dto = new TbJcglZbjl();
        dto.setSjbm("tb_jcgl_znzb");
        dto.setGlid(zb.getId());
        dto.setSjly(sjly);
        dto.setZblx("1");
        UserInfo user = UserInfoManager.get();
        dto.setCzr(user.getUserName());
        dto.setCzrSfz(user.getIdEntityCard());
        dto.setCzrSsbmid(String.valueOf(user.getDeptId()));
        dto.setCzrSsbm(user.getDeptName());
        dto.setCzrSsbmdm(user.getDeptCode());
        dto.setXfSsbmid(zb.getSsbmid());
        dto.setXfSsbm(zb.getSsbm());
        dto.setXfSsbmdm(zb.getSsbmdm());
        dto.setExt("1");
        tbJcglZbjlService.addEntity(dto);
    }


    @Override
    public int addZnzb(TbJcglZnzb zb) {
        if (StringUtils.isNotBlank(zb.getScode())) {
            TbJcglZnzb dto = new TbJcglZnzb();
            BeanUtils.copyProperties(zb, dto);
            //查询设备类型信息
            List<TbJcglZnzb> tbJcglZnzbs = this.baseMapper.selectList(
                    new QueryWrapper<TbJcglZnzb>().eq("sbbh", zb.getSbbh())
                            .eq("xt_scbz", 0)
            );
            if (tbJcglZnzbs.size() > 0) throw new BusinessException("设备编号已存在");
            dto.setId(UUIDGenerator.getUUID());
            if (StringUtils.isNotBlank(dto.getSsbmdm())) {
                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(dto.getSsbmdm());
                dto.setSsbm(dept.getDeptname());
                dto.setSsbmid(dept.getDeptid());
                dto.setSsbmdm(dept.getDeptcode());
                dto.setSsxgajdm(dept.getFxjcode());
                dto.setSsxgajid(dept.getFxjid());
                dto.setSsxgaj(dept.getFxjname());
                dto.setSssgaj(dept.getDszname());
                dto.setSssgajdm(dept.getDszcode());
                dto.setSssgajid(dept.getDszid());
            }
            dto.setXtSjly("1");
            // 新增关联表数据
            if (StringUtils.isNotEmpty(dto.getSbbh())) {
                TbJcglSbdwVo vo = new TbJcglSbdwVo();
                BeanUtils.copyProperties(dto, vo);
                redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
            }
            return this.baseMapper.insert(dto);
        }
        return -1;
    }

    @Override
    public IPage<TbJcglZnzbVo> getZnzb(TbJcglZnzb zb, IPage<TbJcglZnzb> page) {
        zb.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(zb.getSsbmdm(), zb.getIsChild()));
        IPage<TbJcglZnzb> resPage = this.baseMapper.selectPage(page,
                new LambdaQueryWrapper<TbJcglZnzb>()
                        .eq(StringUtils.isNotBlank(zb.getScode()), TbJcglZnzb::getScode, zb.getScode())
                        .likeRight(StringUtils.isNotBlank(zb.getSsbmdm()), TbJcglZnzb::getSsbmdm, zb.getSsbmdm())
                        .like(StringUtils.isNotBlank(zb.getSbmc()), TbJcglZnzb::getSbmc, zb.getSbmc())
                        .eq(zb.getCgrq() != null, TbJcglZnzb::getCgrq, zb.getCgrq()));
        IPage<TbJcglZnzbVo> resList = new Page<>(zb.getPageNo(), zb.getPageSize());
        List<TbJcglZnzbVo> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resPage.getRecords())) {
            for (TbJcglZnzb record : resPage.getRecords()) {
                TbJcglZnzbVo vo = new TbJcglZnzbVo();
                BeanUtils.copyProperties(record, vo);
                list.add(vo);
            }
        }
        resList.setTotal(resPage.getTotal());
        resList.setPages(resPage.getPages());
        resList.setRecords(list);
        return resList;
    }

    @Override
    public void editZnzb(TbJcglZnzb zb) {
        if (StringUtils.isNotBlank(zb.getScode())) {
            //查询设备类型信息
            List<TbJcglZnzb> tbJcglZnzbs = this.baseMapper.selectList(
                    new QueryWrapper<TbJcglZnzb>().eq("sbbh", zb.getSbbh())
                            .eq("xt_scbz", 0)
                            .ne("id", zb.getId())
            );
            if (tbJcglZnzbs.size() > 0) {
                throw new BusinessException("设备编号已存在");
            } else if (StringUtils.isNotBlank(zb.getSsbmdm())) {
                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(zb.getSsbmdm());
                zb.setSsbm(dept.getDeptname());
                zb.setSsbmid(dept.getDeptid());
                zb.setSsbmdm(dept.getDeptcode());
                zb.setSsxgajdm(dept.getFxjcode());
                zb.setSsxgajid(dept.getFxjid());
                zb.setSsxgaj(dept.getFxjname());
                zb.setSssgaj(dept.getDszname());
                zb.setSssgajdm(dept.getDszcode());
                zb.setSssgajid(dept.getDszid());
            }
            if (StringUtils.isNotEmpty(zb.getSbbh())) {
                TbJcglSbdwVo vo = new TbJcglSbdwVo();
                BeanUtils.copyProperties(zb, vo);
                redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
            }
            this.baseMapper.updateById(zb);
        }
    }

    @Override
    public void deleteZnzb(List<String> id) {
        //批量注销
        TbJcglZnzb tbJcglZnzb = new TbJcglZnzb();
        tbJcglZnzb.setXtScbz("1");
        if (id.size() > 0) {
            this.baseMapper.deleteZb(id);
        }
    }

    @Override
    public TbJcglZnzbVo selectZbxq(String id) {
        TbJcglZnzb zb = this.baseMapper.selectById(id);
        if (zb != null) {
            TbJcglZnzbVo vo = new TbJcglZnzbVo();
            BeanUtils.copyProperties(zb, vo);
            return vo;
        }
        return null;
    }

    @Override
    public IPage<TbJcglZnzb> znzbDqtx(TbJcglZnzbQuery zb, IPage<TbJcglZnzb> page) {
        SimpleDateFormat defaultDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = DateUtils.getSystemDateString();
        Date dqDate = DateUtils.stepMonth(new Date(), 2);
        String dqsj = defaultDateFormatter.format(dqDate);
        QueryWrapper<TbJcglZnzb> qw = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);
        zb.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(zb.getSsbmdm(), null));
        if (zb != null) {
            qw.lambda().eq(StringUtils.isNotBlank(zb.getScode()), TbJcglZnzb::getScode, zb.getScode())
                    .like(StringUtils.isNotBlank(zb.getSbmc()), TbJcglZnzb::getSbmc, zb.getSbmc())
                    .likeRight(StringUtils.isNotBlank(zb.getSsbmdm()), TbJcglZnzb::getSsbmdm, zb.getSsbmdm())
                    .eq(StringUtils.isNotBlank(zb.getCgrq()), TbJcglZnzb::getCgrq, zb.getCgrq())
                    .eq(TbJcglZnzb::getXtScbz, 0)
                    .eq(StringUtils.isNotBlank(zb.getSfzy()), TbJcglZnzb::getSfzy, zb.getSfzy())
                    .eq(StringUtils.isNotBlank(zb.getSfrh()), TbJcglZnzb::getSfrh, zb.getSfrh())
                    .ge(TbJcglZnzb::getDqsj, currentDate)
                    .le(TbJcglZnzb::getDqsj, dqsj);
        }
        return this.baseMapper.selectPage(page, qw);
    }


    @Override
    public Object checkZnzb() {
        // 查询所有装备。判断他的状态和是否发送消息(故障不判断，故障)
        List<TbJcglZnzb> zbList = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbJcglZnzb>()
                        .eq(TbJcglZnzb::getXtSjzt, "1")
        );
        zbList.forEach(zb -> {
            // 判断是否临期(提前两个月)
            Date zbTime = zb.getDqsj();
            Date now = new Date();
            if ("4".equals(zb.getZbzt())) {
                if (!"4".equals(zb.getZbzt())) {
                    zb.setZbzt("4");
                }
                if (!"1".equals(zb.getSftx())) {
                    // 发送提醒
                    this.sendMsg(zb, "0");
                    zb.setSftx("1");
                }
                this.baseMapper.updateById(zb);
            } else {
                if (DateUtils.getQueryDateString(zbTime, "01")
                        .equals(DateUtils.getQueryDateString(now, "01"))
                        || now.getTime() >= zbTime.getTime()) {
                    if (!"3".equals(zb.getZbzt())) {
                        zb.setZbzt("3");
                    }
                    if (!"1".equals(zb.getSftx())) {
                        // 发送提醒
                        this.sendMsg(zb, "1");
                        zb.setSftx("1");
                    }
                    this.baseMapper.updateById(zb);
                } else {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(now);
                    cal.add(Calendar.MONTH, +2);
                    now = cal.getTime();
                    System.err.println("   now:" + DateUtils.getQueryDateString(now, "02"));
                    System.err.println("zbTime:" + DateUtils.getQueryDateString(zbTime, "02"));
                    if (now.getTime() >= zbTime.getTime()) {
                        if (!"2".equals(zb.getZbzt())) {
                            zb.setZbzt("2");
                        }
                        if (!"1".equals(zb.getSftx())) {
                            // 发送提醒
                            this.sendMsg(zb, "2");
                            zb.setSftx("1");
                        }
                        this.baseMapper.updateById(zb);
                    }
                }
            }
        });
        return null;
    }

    @Override
    public IPage<TbJcglZnzbVo> getFjzbList(TbJcglZnzbSearchDto dto) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("dto", dto);
        List<TbJcglZnzbVo> list = this.baseMapper.getFjzbList(map);
        int count = this.baseMapper.getFjzbCount(map);
        IPage<TbJcglZnzbVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public IPage<TbJcglZnzbVo> getZnzbList(AppSearchQuery dto) {
        UserInfo user = UserInfoManager.get();
        IPage<TbJcglZnzb> page;
        //本部门
        if ("1".equals(dto.getType())) {
            page = this.baseMapper.selectPage(
                    new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                    new LambdaQueryWrapper<TbJcglZnzb>()
                            .eq(TbJcglZnzb::getXtSjzt, "1")
                            .eq(StringUtils.isNotBlank(dto.getScode()), TbJcglZnzb::getScode, dto.getScode())
                            .like(StringUtils.isNotBlank(dto.getKeyword()), TbJcglZnzb::getSbmc, dto.getKeyword())
                            .eq(StringUtils.isNotBlank(user.getDeptCode()), TbJcglZnzb::getSsbmdm, user.getDeptCode())
            );
        } else {
//            String ssbmdm = user.getDeptCode();
            String ssbmdm = this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), "1");
            page = this.baseMapper.selectPage(
                    new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                    new LambdaQueryWrapper<TbJcglZnzb>()
                            .eq(TbJcglZnzb::getXtSjzt, "1")
                            .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglZnzb::getSsbmdm, ssbmdm)
                            .eq(StringUtils.isNotBlank(dto.getScode()), TbJcglZnzb::getScode, dto.getScode())
                            .and(StringUtils.isNotBlank(dto.getKeyword()),
                                    it -> it.like(TbJcglZnzb::getSbmc, dto.getKeyword())
                                            .or()
                                            .like(TbJcglZnzb::getSsbm, dto.getKeyword())
                            )
            );
        }
        IPage<TbJcglZnzbVo> resPage = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        List<TbJcglZnzbVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                TbJcglZnzbVo vo = new TbJcglZnzbVo();
                BeanUtils.copyProperties(item, vo);
                voList.add(vo);
            });
        }
        resPage.setTotal(page.getTotal());
        resPage.setRecords(voList);
        return resPage;
    }

    /**
     * 给用户发送提醒消息
     *
     * @param zb
     * @param type 0.故障 1.到期  2.临期
     */
    private void sendMsg(TbJcglZnzb zb, String type) {
        System.err.println(type);
        SysMessageInfoInsertDto dto = new SysMessageInfoInsertDto();
        List<SysMessageItemInsertDto> itemList = new ArrayList<>();
        if (!StringUtils.isBlank(zb.getSsbmid())) {
            // 查询部门下的所有的人员信息列表
            List<SysUserDeptVO> list = this.tbBaseAdaptRemoteService.getUserList(zb.getSsbmid());
            list.forEach(item -> {
                SysMessageItemInsertDto itemDto = new SysMessageItemInsertDto();
                itemDto.setXxjsrXm(item.getUserName());
                itemDto.setXxjsrSfzh(item.getIdEntityCard());
                itemDto.setXxjsrId(String.valueOf(item.getId()));
                itemDto.setXxjsbm(zb.getSsbm());
                itemDto.setXxjsbmId(zb.getSsbmid());
                itemList.add(itemDto);
            });
            if (itemList.size() > 0) {
                dto.setItemList(itemList);
                String xxnr = "智能装备《" + zb.getSbmc() + "（" + zb.getSbbh() + "）》";
                if ("0".equals(type)) {
                    xxnr += "发生故障，请排查。";
                } else if ("1".equals(type)) {
                    xxnr += "已到期，请立即维护或更换";
                } else {
                    xxnr += "即将到期，到期时间" + DateUtils.getQueryDateString(zb.getDqsj(), "01") + "，请立即维护或更换";
                }
                dto.setXxnr(xxnr);
                dto.setXxlx("1");
                dto.setXxzt("2");
                this.tbBaseAdaptRemoteService.sendMsg(dto);
            }
        }
    }

    @Override
    public String importData(List<TbJcglZnzb> list, boolean updateSupport) {
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TbJcglZnzb item : list) {
            try {
                if (org.springframework.util.StringUtils.isEmpty(item.getSbbh())
                        || org.springframework.util.StringUtils.isEmpty(item.getSbmc())
                        || org.springframework.util.StringUtils.isEmpty(item.getScode())
                        || ObjectUtils.isEmpty(item.getCgrq())
                        || ObjectUtils.isEmpty(item.getDqsj())
                        || ObjectUtils.isEmpty(item.getSsbmdm())
                ) {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、账号 " + item.getSbmc() + " 信息不全,请仔细核查！");
                    continue;
                }
                TbJcglZnzb znzb = this.baseMapper.selectOne(new LambdaQueryWrapper<TbJcglZnzb>()
                        .eq(TbJcglZnzb::getSbbh, item.getSbbh())
                        .eq(TbJcglZnzb::getXtSjzt, "1")
                        .eq(TbJcglZnzb::getXtScbz, "0")
                        .last(" limit 1")
                );
                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(item.getSsbmdm());
                if (ObjectUtils.isNotEmpty(dept)) {
                    item.setSsbm(dept.getDeptname());
                    item.setSsbmid(dept.getDeptid());
                    item.setSsbmdm(dept.getDeptcode());
                    item.setSsxgajdm(dept.getFxjcode());
                    item.setSsxgajid(dept.getFxjid());
                    item.setSsxgaj(dept.getFxjname());
                    item.setSssgaj(dept.getDszname());
                    item.setSssgajdm(dept.getDszcode());
                    item.setSssgajid(dept.getDszid());
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、所属部门编码不存在 " + item.getSsbmdm() + " 信息不全,请仔细核查！");
                    continue;
                }
                item.setXtSjzt("1");
                item.setXtScbz("0");
                item.setZbzt("1");
                item.setSftx("1");

                if (ObjectUtils.isEmpty(znzb)) {
                    item.setId(UUIDGenerator.getUUID());
                    if (StringUtils.isNotEmpty(item.getSbbh())) {
                        TbJcglSbdwVo vo = new TbJcglSbdwVo();
                        BeanUtils.copyProperties(item, vo);
                        redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                    }
                    this.baseMapper.insert(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "装备 " + item.getSbmc() + " 导入成功");
                } else if (updateSupport) {
                    item.setId(znzb.getId());
                    if (StringUtils.isNotEmpty(item.getSbbh())) {
                        TbJcglSbdwVo vo = new TbJcglSbdwVo();
                        BeanUtils.copyProperties(item, vo);
                        redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                    }
                    this.baseMapper.updateById(item);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、装备 " + item.getSbmc() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、装备编号： " + item.getSbbh() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备 " + item.getSbmc() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Map<String, Object>> sblxTj(String type, String ssbmdm) {
        ssbmdm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm, null);
        List<Map<String, Object>> maps = new ArrayList<>();
        if (StringUtils.isNotBlank(type) && type.equals("2")) {
            //器械装备
            maps = this.baseMapper.sblxTj(ssbmdm);
            if (!CollectionUtils.isEmpty(maps)) {
                maps.forEach(v -> {
                    String scode = v.get("scode").toString();
                    SysDictItem dict = this.baseMapper.selectDict("D_BZ_JYQXFL", scode);
                    if (ObjectUtils.isNotEmpty(dict)) {
                        v.put("name", dict.getZdmc());
                    }
                });
            }

        } else {
            //智能装备
            QueryWrapper<SysDict> dictWrapper = new QueryWrapper<>();
            dictWrapper.and(wrapper -> wrapper.eq("zdbh", "D_BZ_ZBLX_LZ"));
            SysDict sysDict = sysDictService.getOne(dictWrapper);
            Asserts.check(sysDict == null, "字典编号 %s 对应的字典不存在", "D_BZ_ZBLX_LZ");
//            SysDictItem dict = this.baseMapper.selectDict("D_BZ_ZBLX_LZ", scode);
            List<SysDictItem> list = this.sysDictItemService.list(new QueryWrapper<SysDictItem>().lambda()
                    .eq(SysDictItem::getZdId, sysDict.getId())
                    .eq(SysDictItem::getXtZxbz, DeletedEnum.NATURE.code)
            );
            if (!CollectionUtils.isEmpty(list)) {
                for (SysDictItem item : list) {
                    Map<String, Object> tjMap = new HashMap<>();
                    tjMap.put("scode", item.getDm());
                    tjMap.put("name", item.getZdmc());
                    int sl = this.baseMapper.selectCount(new QueryWrapper<TbJcglZnzb>().lambda()
                            .likeRight(TbJcglZnzb::getSsbmdm, ssbmdm)
                            .likeRight(TbJcglZnzb::getScode, item.getDm())
                            .isNull(TbJcglZnzb::getXfid)
                            .isNull(TbJcglZnzb::getSfbs)
                            .eq(TbJcglZnzb::getXtScbz, DeletedEnum.NATURE.code)

                    );
                    tjMap.put("sl", sl);
                    Integer xfs = this.baseMapper.selectCount(new LambdaQueryWrapper<TbJcglZnzb>()
                            .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglZnzb::getSsbmdm, ssbmdm)
                            .likeRight(TbJcglZnzb::getScode, item.getDm())
                            .isNotNull(TbJcglZnzb::getXfid)
                    );
                    tjMap.put("xfs", xfs);
                    //获取报损数量
                    Integer bss = this.baseMapper.selectCount(new LambdaQueryWrapper<TbJcglZnzb>()
                            .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglZnzb::getSsbmdm, ssbmdm)
                            .likeRight(TbJcglZnzb::getScode, item.getDm())
                            .eq(TbJcglZnzb::getSfbs, "1")
                    );
                    tjMap.put("bss", bss);
                    maps.add(tjMap);
                }
            }
        }
        return maps;
    }

    @Override
    public Map<String, Object> zyZbtj(String ssbmdm) {
        Map<String, Object> map = new HashMap<>();
        ssbmdm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm, null);
        //获取装备数量
        List<TbJcglZnzb> tbJcglZnzbs = this.baseMapper.selectList(new LambdaQueryWrapper<TbJcglZnzb>()
                .isNull(TbJcglZnzb::getXfid)
                .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglZnzb::getSsbmdm, ssbmdm)
        );
        int zbs = 0;
        if (!CollectionUtils.isEmpty(tbJcglZnzbs)) {
            zbs = tbJcglZnzbs.size();
        }
        //获取车辆数据
        List<TbJcglXfcl> tbJcglXfcls = this.tbJcglXfclMapper.selectList(new LambdaQueryWrapper<TbJcglXfcl>()
                .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglXfcl::getSsbmdm, ssbmdm)
        );
        int cls = 0;
        if (!CollectionUtils.isEmpty(tbJcglXfcls)) {
            cls = tbJcglXfcls.size();
        }
        String currentDate = DateUtils.getSystemDateString();
        String dqsj = DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "M", 2), "01");
        //临期装备
        List<TbJcglZnzb> tbJcglZnzbs1 = this.baseMapper.selectList(new LambdaQueryWrapper<TbJcglZnzb>()
                .isNull(TbJcglZnzb::getXfid)
                .likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglZnzb::getSsbmdm, ssbmdm)
                .ge(TbJcglZnzb::getDqsj, currentDate)
                .le(TbJcglZnzb::getDqsj, dqsj)
        );
        int dqs = 0;
        if (!CollectionUtils.isEmpty(tbJcglZnzbs1)) {
            dqs = tbJcglZnzbs1.size();
        }
        map.put("dqs", dqs);
        map.put("zbs", zbs);
        map.put("cls", cls);
        return map;
    }

    /**
     * 专业装备
     *
     * @param
     */
    @Override
    public List<TbJcglZnzb> getZyzb(TbJcglZyzbQuery tbJcglZyzbQuery) {

        QueryWrapper<TbJcglZnzb> tb = new QueryWrapper<>();

//        if (StringUtils.isNotBlank(tbJcglZyzbQuery.getSsbmdm())) {
//            DeptInfo sysDeptLevel = sysRoleService.getSysDeptLevel(tbJcglZyzbQuery.getSsbmdm());
//            PermissionsUtil.queryWrapperUtilByDeptInfo(tb, sysDeptLevel);
//        } else if (StringUtils.isNotBlank(tbJcglZyzbQuery.getSsbmid())) {
//            DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByDeptId(tbJcglZyzbQuery.getSsbmid());
//            DeptInfo sysDeptLevel = sysRoleService.getSysDeptLevel(dept.getDeptcode());
//            PermissionsUtil.queryWrapperUtilByDeptInfo(tb, sysDeptLevel);
//        } else {
//            UserInfo user = UserInfoManager.getUser();
//            PermissionsUtil.queryWrapperUtil(tb, user);
//        }
//
        tbJcglZyzbQuery.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(tbJcglZyzbQuery.getSsbmdm(), null));
        tb.lambda()
                .eq(TbJcglZnzb::getSfzy, "1")
                .likeRight(StringUtils.isNotBlank(tbJcglZyzbQuery.getSsbmdm()), TbJcglZnzb::getSsbmdm, tbJcglZyzbQuery.getSsbmdm())
                .eq(StringUtils.isNotBlank(tbJcglZyzbQuery.getSfrh()), TbJcglZnzb::getSfrh, tbJcglZyzbQuery.getSfrh());
        List<TbJcglZnzb> tbJcglZnzbs = this.baseMapper.selectList(tb);
        if (!CollectionUtils.isEmpty(tbJcglZnzbs)) {
            //查询装备是否感知接入
            for (TbJcglZnzb zyzb : tbJcglZnzbs) {
                Integer integer = this.tbSbGzjrMapper.selectCount(new LambdaQueryWrapper<TbSbGzjr>()
                        .eq(StringUtils.isNotBlank(tbJcglZyzbQuery.getGlid()), TbSbGzjr::getGlid, tbJcglZyzbQuery.getGlid())
                        .eq(StringUtils.isNotBlank(tbJcglZyzbQuery.getJrlx()), TbSbGzjr::getJrlx, tbJcglZyzbQuery.getJrlx())
                        .eq(StringUtils.isNotBlank(zyzb.getSbbh()), TbSbGzjr::getSbbm, zyzb.getSbbh()));
                zyzb.setGzjr(integer);
            }


        }
        return tbJcglZnzbs;
    }

    //    @Override
    @PostConstruct
    public void znzbToRedis() {
        //先删除所有然后同步
        redisService.deleteObject(redisService.keys(Constant.PGIS_SB + "*"));
        //同步智能装备
        List<TbJcglZnzb> tbJcglZnzbs = this.baseMapper.selectList(new LambdaQueryWrapper<TbJcglZnzb>());
        if (!CollectionUtils.isEmpty(tbJcglZnzbs)) {
            for (TbJcglZnzb znzb : tbJcglZnzbs) {
                if (StringUtils.isNotEmpty(znzb.getSbbh())) {
                    TbJcglSbdwVo vo = new TbJcglSbdwVo();
                    BeanUtils.copyProperties(znzb, vo);
                    redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                }
            }
        }
        //同步车辆
        List<TbJcglXfcl> xfclList = this.tbJcglXfclMapper.selectList(new LambdaQueryWrapper<TbJcglXfcl>());
        if (!CollectionUtils.isEmpty(xfclList)) {
            for (TbJcglXfcl xfcl : xfclList) {
                if (StringUtils.isNotEmpty(xfcl.getGpsId())) {
                    TbJcglSbdwVo vo = new TbJcglSbdwVo();
                    BeanUtils.copyProperties(xfcl, vo);
                    vo.setSbbh(xfcl.getGpsId());
                    vo.setSbmc(xfcl.getCph());
                    vo.setScode("05");
                    redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                }
            }
        }
        System.out.println("PostConstruct------------》存入redis数据");
    }
}
