package com.dcsoft.system.visitor.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.domain.R;
import com.dcsoft.common.core.enums.ExamineEnum;
import com.dcsoft.common.core.enums.MatterEnum;
import com.dcsoft.common.core.enums.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.CollUtil;
import com.dcsoft.common.core.utils.SpringUtils;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.common.sms.config.properties.SmsProperties;
import com.dcsoft.common.sms.entity.SmsResult;
import com.dcsoft.common.sms.service.SmsTemplate;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.api.model.LoginUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.domain.vo.KeyLabelVo;
import com.dcsoft.system.domain.vo.OfficialAccountVo;
import com.dcsoft.system.domain.vo.SysFileVo;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.DingtalkMsgVo;
import com.dcsoft.system.uniubi.domain.Person;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.FileUtils;
import com.dcsoft.system.utils.UuidUtil;
import com.dcsoft.system.visitor.domain.*;
import com.dcsoft.system.visitor.service.IVisCarryStuffService;
import com.dcsoft.system.visitor.service.IVisVisitorExamineService;
import com.dcsoft.system.visitor.service.IVisitorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 访客信息Controller
 *
 * @author 倪春
 * @date 2023-03-09
 */
@Slf4j
@RestController
@RequestMapping("/visitor")
public class VisitorController extends BaseController {
    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private IVisVisitorExamineService visVisitorExamineService;

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private ISysBlackListService sysBlackListService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISysRuleService sysRuleService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysBranchService sysBranchService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Resource
    private IVisCarryStuffService visCarryStuffService;

    @Resource
    private ISysUserService sysUserService;

    @Value("${qd.url}")
    public String qdUrl;

    @Value("${dingTalk.getToken}")
    public String getToken;

    @Value("${dingTalk.asyncsendV2}")
    public String asyncsendV2;

    @Value("${dingTalk.agentId}")
    public String dingAgentId;

    @Value("${weixin.token}")
    public String weixinToken;

    @Value("${weixin.send}")
    public String weixinSend;

    @Value("${system.type}")
    public String systemType;

    @Value("${sdk.saveVisitor}")
    public String saveVisitor;

    @Value("${sdk.updateVisitorExamine}")
    public String updateVisitorExamine;

    @Value("${sdk.saveVisitorAuditing}")
    public String saveVisitorAuditing;

    @Value("${sdk.upload}")
    public String upload;

    @Value("${photo.url}")
    public String url;

    @Value("${property_dep_id}")
    public String propertyDepId;

    @Value("${minio.url}")
    public String minioUrl;

    @Value("${minio.gwurl}")
    public String minioGwurl;

    @Value("${applet.appid}")
    public String appid;

    @Value("${applet.secret}")
    public String secret;

    @Value("${weCom.corpid}")
    public String corpid;

    @Value("${weCom.corpsecret}")
    public String weComSecret;

    @Value("${weCom.agentid}")
    public String weComAgentid;

    @Value("${sms.parkName:'兴安智慧园区'}")
    private String parkName;

    // 正则表达式匹配大部分国家的手机号码格式
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    private static final String APPROVE_KEY = "APPROVE_KEY:APPROVE";

    /**
     * 查询访客信息列表
     */
//    @RequiresPermissions("visitor:visitor:list")
    @GetMapping("/list")
    public TableDataInfo list(Visitor visitor) {
        if(StringUtils.isNotEmpty(visitor.getTabFlag())) {
            if(StringUtils.isEmpty(visitor.getPeoplePhone())) {
                Long userId = SecurityUtils.getUserId();
                if(userId > 1) {
                    List<SysPeople> people = sysPeopleService.querySysPeopleInfo(userId);
                    if(CollectionUtils.isEmpty(people)) {
                        return getDataTable(new ArrayList<>());
                    }
                    String collect = people.stream().map(SysPeople::getPhone).collect(Collectors.joining(","));
                    visitor.setPeoplePhone(collect);
                    String collected = people.stream().map(e -> String.valueOf(e.getId())).collect(Collectors.joining(","));
                    visitor.setNextStepReviewer(collected);
                }
            } else {
                SysPeople sysPeople = sysPeopleService.queryPeopleName(visitor.getPeoplePhone(), new ArrayList<>());
                if(sysPeople != null) {
//                    visitor.setPosition(sysPeople.getPosition());
                    visitor.setNextStepReviewer(String.valueOf(sysPeople.getId()));
                }
            }
        }

        startPage();
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        Map<String, String> map = dictDataService.queryDictData("sys_company_type");
        List<SysBranch> sysBranches = sysBranchService.queryPropertyDept(null);
        Map<String, String> collect = sysBranches.stream().collect(Collectors.toMap(SysBranch::getId, SysBranch::getName));
        for (Visitor visitor1 : list) {
            String s = map.get(visitor1.getDeptId());
            if(StringUtils.isNotEmpty(s)) {
                visitor1.setDeptName(s);
                continue;
            }
            visitor1.setDeptName(collect.get(visitor1.getDeptId()));
        }
        return getDataTable(list);
    }

    /**
     * 小程序查询我的访客信息列表
     */
    @GetMapping("/app/list")
    public TableDataInfo appList(Visitor visitor) {
        LoginUser user = SecurityUtils.getLoginUser();
        visitor.setCreateBy(user.getUsername());
        log.info("访客信息列表入参:{}", JSON.toJSONString(visitor));

        startPage();
        List<Visitor> list = visitorService.selectAppVisitorList(visitor);
        Map<String, String> map = dictDataService.queryDictData("sys_company_type");
//        Map<String, String> parkMap = dictDataService.queryDictData("sys_park_group");
        List<SysBranch> sysBranches = sysBranchService.queryPropertyDept(null);
        Map<String, String> collect = sysBranches.stream().collect(Collectors.toMap(SysBranch::getId, SysBranch::getName));
        for (Visitor visitor1 : list) {
            String s = map.get(visitor1.getDeptId());
            if (StringUtils.isNotEmpty(s)) {
                visitor1.setDeptName(s);
            } else {
                visitor1.setDeptName(collect.get(visitor1.getDeptId()));
            }
            visitor1.setMatterName(MatterEnum.getByCode(visitor1.getMatter()));
//            visitor1.setParkName(parkMap.get(visitor1.getPark()));
        }
        log.info("访客信息列表:{}", JSON.toJSONString(list));
        return getDataTable(list);
    }

    /**
     * 查询审批状态枚举类型
     * @return
     */
    @GetMapping("/app/getExamineEnum")
    public AjaxResult getExamineEnum() {
        List<KeyLabelVo> list = new ArrayList();
        for (ExamineEnum examine : ExamineEnum.values()) {
            KeyLabelVo keyLabelVo = new KeyLabelVo();
            keyLabelVo.setKey(examine.getCode());
            keyLabelVo.setLabel(examine.getValue());
            keyLabelVo.setColor(examine.getColor());
            list.add(keyLabelVo);
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出访客信息列表
     */
    @RequiresPermissions("visitor:visitor:export")
    @Log(title = "访客信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Visitor visitor) {
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        ExcelUtil<Visitor> util = new ExcelUtil<Visitor>(Visitor.class);
        util.exportExcel(response, list, "访客信息数据");
    }

    /**
     * 获取访客信息详细信息（详情）
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);

        Map<String, String> map = dictDataService.queryDictData("sys_company_type");
        visitor.setMatterName(MatterEnum.getByCode(visitor.getMatter()));
        visitor.setDeptName(map.get(visitor.getDeptId()));
        return success(visitor);
    }

    @GetMapping(value = "/queryVisitorById")
    public AjaxResult queryVisitorById(Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);
        return success(visitor);
    }

    /**
     * 获取访客信息详细信息(审批链接进来)
     */
    @PostMapping(value = "/getVisitorInfo")
    public AjaxResult getVisitorInfo(@RequestBody JSONObject js) throws Exception {
        String str = js.getString("data");
        if (StringUtils.isBlank(str)) {
            throw new ServiceException("参数为空，请联系管理员!");
        }

        String type = str.substring(str.length() - 1);
        String data = str.substring(0, str.length() - 1);

        //数据进行解密 1是临时访客，2是
        Object cacheObject = null;
        if (StringUtils.equals("1", type)) {
            cacheObject = redisService.getCacheObject(CacheConstants.VISITOR_SMS_CODE + data);
        }
        if (StringUtils.equals("2", type)) {
            cacheObject = redisService.getCacheObject(CacheConstants.VIS_CARRY_STUFF_CODE + data);
        }

        if (ObjectUtil.isNull(cacheObject)) {
            throw new ServiceException("链接不存在或已过期！");
        }

        String[] split = String.valueOf(cacheObject).split("&");
        Long id = Long.parseLong(split[0]);
        String telephone = split[1];

        if (StringUtils.equals("2", type)) {
            VisExitOutVo visCarryStuff = getVisCarryStuff(id, str);
            visCarryStuff.setTelephone(telephone);
            return success(visCarryStuff);
        }

        Visitor visitor = visitorService.selectVisitorById(id);
        visitor.setTelephone(telephone);

        //审核链接进来
        VisitorReviewProcessVo visitor2 = new VisitorReviewProcessVo();
        visitor2.setVisitorId(visitor.getId());
        visitor2.setApproveData(str);
        VisitorReviewProcessVo visitorReviewProcessVo = visitorService.queryReviewProcess(visitor2);
        if (ObjectUtil.isNotNull(visitorReviewProcessVo) && StrUtil.isNotBlank(visitorReviewProcessVo.getState())) {
            if (StringUtils.equals(visitor.getExamineState(), ExamineEnum.IN_REVIEW.getCode())) {
                visitor.setExamineState(visitorReviewProcessVo.getState());
            }
            visitor.setRejectReason(visitorReviewProcessVo.getRejectReason());
        }

        Map<String, String> map = dictDataService.queryDictData("sys_company_type");
        visitor.setMatterName(MatterEnum.getByCode(visitor.getMatter()));
        visitor.setDeptName(map.get(visitor.getDeptId()));
        return success(visitor);
    }

    /**
     * 查询携物申请信息
     *
     * @param id
     * @param str
     * @return
     */
    private VisExitOutVo getVisCarryStuff(Long id, String str) {
        VisExitOutVo stuffVo = visCarryStuffService.selectVisExitOutById(id);

        //查询物品信息列表
        VisStuffInfoVo visStuffInfoVo = new VisStuffInfoVo();
        visStuffInfoVo.setExitId(stuffVo.getId());
        List<VisStuffInfoVo> stuffList = visCarryStuffService.selectStuffList(visStuffInfoVo);
        if (CollUtil.isNotEmpty(stuffList)) {
            //处理字典
            Map<String, String> map = dictDataService.queryDictData("vis_out_stuff_type");
            stuffList.forEach(stuff -> {
                if (StrUtil.isNotBlank(stuff.getType())) {
                    stuff.setTypeName(map.get(stuff.getType()));
                }
                if (StrUtil.isNotBlank(stuff.getBackType())) {
                    stuff.setBackTypeName(map.get(stuff.getBackType()));
                }
                if (StrUtil.isNotBlank(stuff.getImgUrls())) {
                    stuff.setImgUrlList(Arrays.asList(stuff.getImgUrls().split(",")));
                }
                if (StrUtil.isNotBlank(stuff.getBackImgUrls())) {
                    stuff.setBackImgUrlList(Arrays.asList(stuff.getBackImgUrls().split(",")));
                }
            });
            stuffVo.setVisStuffInfoList(stuffList);
        }

        //查询审核流程信息
        List<VisitorReviewProcessVo> reviewProcess = visCarryStuffService.queryVisitorReviewProcessList(id);
        if (CollUtil.isNotEmpty(reviewProcess)) {
            boolean flag = true;
            for (VisitorReviewProcessVo process : reviewProcess) {
                if (!flag) {
                    process.setState(null);
                }
                if (Constants.ONE.equals(process.getState())) {
                    flag = false;
                }
            }

            stuffVo.setReviewProcessList(reviewProcess);
        }

        //查询审核节点，查看当前点击审核链接的人审核状态
        VisitorReviewProcessVo visExitOutVo = new VisitorReviewProcessVo();
        visExitOutVo.setExitId(id);
        visExitOutVo.setApproveData(str);
        VisitorReviewProcessVo reviewProcessVo = visCarryStuffService.queryReviewProcessNew(visExitOutVo);
        if (ObjectUtil.isNotNull(reviewProcessVo) && StrUtil.isNotBlank(reviewProcessVo.getState())) {
            stuffVo.setExamineState(reviewProcessVo.getState());
        }

        return stuffVo;
    }


    /**
     * 新增访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Visitor visitor) throws Exception {
        if (visitor.getStartTime().getTime() > visitor.getEndTime().getTime()) {
            throw new ServiceException("您输入的开始时间不能大于结束时间");
        }

        if (visitorService.queryVisitorByIdCountOld(visitor.getPhone()) > 0) {
            throw new ServiceException("该手机号已存在访客预约信息");
        }

        if (visitorService.queryVisitor(visitor) > 0) {
            throw new ServiceException("您已预约");
        }

        log.info("新增访客信息：{}", visitor);
        int i = visitorService.insertVisitor(visitor);
        List<Visitor> itemList = visitor.getItemList();
        // 随访人员
        if (!CollectionUtils.isEmpty(itemList)) {
            for (Visitor item : itemList) {
                if (!validatePhoneNumber(item.getPhone())) {
                    throw new ServiceException("您输入的随访人员手机号格式不正确");
                }
                item.setParentId(visitor.getId());
                item.setSource(Constants.ONE);
                item.setUserId(visitor.getUserId());
                item.setDeptId(visitor.getDeptId());
                item.setCreateTime(visitor.getCreateTime());
                item.setStartTime(visitor.getStartTime());
                item.setEndTime(visitor.getEndTime());
                visitorService.insertVisitor(item);
            }
        }

        // 保存附件
        if(!CollectionUtils.isEmpty(visitor.getFileList())) {
            saveSysFile(visitor.getFileList(), String.valueOf(visitor.getId()));
        }

        // 审核通知企微发送消息（小程序来源）
        String appletLink = getAppletLink(String.valueOf(visitor.getId()), "pages/visitor/visitor/examineIndex");
        SysPeople sysPeople = sysPeopleService.selectSysPeopleByUserId(visitor.getUserId());
        log.info("审核通知链接:{}", appletLink);
        sendWeCom(sysPeople.getPhone(), appletLink + " --访客姓名：" + visitor.getName());

        // 访客审核
        SysBranch sysBranch = sysBranchService.selectSysBranchById(visitor.getDeptId());
        if(sysBranch != null && Constants.ZERO.equals(sysBranch.getIsExamine())) {
            VisVisitorExamine examine = new VisVisitorExamine();
            examine.setExamine(Constants.ZERO);
            visitor.setExamine(examine);
            updateVisitorExamine(visitor);
        }
        return toAjax(i);
    }

    /**
     * 新增访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping("/app/add")
    @Transactional
    public AjaxResult appAdd(@RequestBody Visitor visitor) throws Exception {
        log.info("appAdd-入参：{}", JSON.toJSONString(visitor));
        if (visitor.getStartTime().getTime() > visitor.getEndTime().getTime()) {
            throw new ServiceException("您输入的开始时间不能大于结束时间");
        }

        //判断访客和随访人是否存在预约过的信息
        List<String> phones = new ArrayList<>();
        if (CollUtil.isNotEmpty(visitor.getItemList())) {
            phones = visitor.getItemList().stream().map(Visitor::getPhone).collect(Collectors.toList());
        }
        phones.add(visitor.getPhone());
        List<String> strings = visitorService.addVisitorCheck(phones, visitor.getStartTime());
        if (CollUtil.isNotEmpty(strings)) {
            throw new ServiceException("手机号：" + strings.get(0) + "在该时间段已有申请");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        visitor.setCreateBy(loginUser.getUsername());
        log.info("新增访客信息：{}", visitor);
        int i = visitorService.insertVisitor(visitor);

        // 随访人员
        List<Visitor> itemList = visitor.getItemList();
        if (CollUtil.isNotEmpty(visitor.getItemList())) {
            for (Visitor item : itemList) {
                item.setParentId(visitor.getId());
                item.setSource(Constants.ONE);
                item.setUserId(visitor.getUserId());
                item.setDeptId(visitor.getDeptId());
                item.setFlag(visitor.getFlag());
                item.setStartTime(visitor.getStartTime());
                item.setEndTime(visitor.getEndTime());
                item.setMatter(visitor.getMatter());
                item.setCreateTime(visitor.getCreateTime());
                item.setStartTime(visitor.getStartTime());
                item.setEndTime(visitor.getEndTime());
                item.setVisitorType(visitor.getVisitorType());
                item.setVisitingUnit(visitor.getVisitingUnit());
                item.setUserName(visitor.getUserName());
                visitorService.insertVisitor(item);
            }
        }

        // 保存附件
        if(!CollectionUtils.isEmpty(visitor.getFileList())) {
            saveSysFile(visitor.getFileList(), String.valueOf(visitor.getId()));
        }

        // 审核通知企微发送消息（小程序来源）
        SysPeople sysPeople = sysPeopleService.selectSysPeopleByUserId(visitor.getUserId());
        String url = getExamineUrl(String.valueOf(visitor.getId()), sysPeople.getPhone());
        log.info("add发送审核链接：{}", url);

        //发送企微信息
        try {
            sendWeCom(sysPeople.getPhone(), url + " --访客姓名：" + visitor.getName());
        } catch (Exception e) {
            log.error("访客add-sendWeCom异常：", e);
        }

        return toAjax(i);
    }

    /**
     * 保存附件
     */
    private void saveSysFile(List<SysFileVo> fileList, String visitorId) {
        SysFileVo sysFile = new SysFileVo();
        sysFile.setBusinessId(visitorId);
        sysFile.setBusinessType("sys_visitor_insurance");
        visitorService.deleteFile(sysFile);
        List<SysFileVo> sysFiles = new ArrayList<>();
        for (SysFileVo fileVo : fileList) {
            SysFileVo file = new SysFileVo();
            file.setBusinessId(visitorId);
            file.setFileName(fileVo.getFileName());
            file.setUrl(fileVo.getUrl());
            file.setBusinessType("sys_visitor_insurance");
            file.setId(UUID.randomUUID().toString().replace("-", ""));
            sysFiles.add(file);
        }
        visitorService.saveFile(sysFiles);

    }

    /**
     * 验证手机号码是否有效
     *
     * @param number 要验证的手机号码
     * @return 如果手机号码有效返回true，否则返回false
     */
    public boolean validatePhoneNumber(String number) {
        return PHONE_NUMBER_PATTERN.matcher(number).matches();
    }

    /**
     * 获取审核链接
     *
     * @return
     */
    public String getExamineUrl(String id, String telephone) {
        //生成8位短参作为缓存key
        String code = UuidUtil.getShortUuid();
        try {
            while (redisService.hasKey(code)) {
                code = UuidUtil.getShortUuid();
            }
            redisService.setCacheObject(CacheConstants.VISITOR_SMS_CODE + code, id + "&" + telephone, 30L, TimeUnit.DAYS);
        } catch (Exception e) {
            throw new ServiceException("缓存数据异常：" + e);
        }
        return "https://fk.xyxaks.cn/h5/?c=" + code + "1";
    }

    /**
     * 钉工牌消息通知
     */
    public void asyncsendV2(String phone, String msgType, String content) {
        DingtalkMsgVo msgVo = new DingtalkMsgVo();
        DingtalkMsgVo.Text text = new DingtalkMsgVo.Text();
        text.setContent(content);
        msgVo.setMsgtype(msgType);
        msgVo.setText(text);
        Map<String, Object> map = new HashMap<>();
        map.put("agent_id", dingAgentId);
        map.put("msg", msgVo);
        map.put("userid_list", getDingUserId(phone));
        String body = HttpUtil.createPost(asyncsendV2 + "?access_token=" + getToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(body);
        log.info("钉工牌消息通知接口返回结果：" + body);
        if (!Constants.ZERO.equals(object.get("errcode").toString())) {
            log.error("钉工牌消息通知接口异常码:" + object.get("errcode").toString());
            //throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "钉工牌消息通知接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }

    }

    /**
     * 通过手机号获取userId(钉钉)
     * @param phone
     * @return
     */
    private String getDingUserId(String phone) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phone);
        String body = HttpUtil.createPost("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token=" + getToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        if(!Constants.ZERO.equals(object.get("errcode").toString())) {
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "通过手机号获取userId(钉钉)" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
        String string = object.get("result").toString();
        JSONObject jsonObject = JSON.parseObject(string);
        return jsonObject.get("userid").toString();
    }

    /**
     * 获取钉工牌token
     */
    private String getToken() {
        String body = HttpUtil.createGet(getToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        return object.get("access_token").toString();
    }

    /**
     * 获取微信公众号token
     *
     * @return
     */
    private String getWxToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.WEIXIN_TOKEN);
        if (StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        String body = HttpUtil.createGet(weixinToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        String string = object.get("access_token").toString();
        redisService.setCacheObject(CacheConstants.LOGIN_TOKEN, string, Long.valueOf(object.get("expires_in").toString()), TimeUnit.SECONDS);
        return string;
    }

    private void weixinSend(String openId, String wxToken, String url) {
        String s = Constants.CONTENT.replaceAll("%", openId);
        String s1 = s.replaceAll("#", url);
        String body = HttpUtil.createPost(weixinSend + wxToken)
                .body(s1)
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        if (!"0".equals(object.get("errcode").toString())) {
            log.error("微信公众号消息通知接口异常");
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "微信公众号消息通知接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }
    }

    /**
     * 获取小程序token
     * @return
     */
    private String getAppletToken() {
        String body = HttpUtil.createGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid +"&secret=" + secret).execute().body();
        JSONObject object = JSON.parseObject(body);
        String string = object.get("access_token").toString();
        return string;
    }

    /**
     * 生成微信小程序链接
     * @return
     */
    private String getAppletLink(String id, String path) {
        Map<String, Object> map = new HashMap<>();
        map.put("path", path);
        map.put("query", "id=" + id);
        map.put("is_expire", true);
        map.put("expire_type", 1);
        map.put("expire_interval", 1);
        map.put("env_version", "release");
//        map.put("env_version", "trial");
        String body = HttpUtil
                .createPost("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + getAppletToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        String string = object.get("errcode").toString();
        if(!"0".equals(string)) {
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "生成微信小程序链接接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }
        return object.get("url_link").toString();
    }

    /**
     * 查询加密URLLink
     * @param urlLink
     * @return
     * @throws Exception
     */
    @GetMapping("/queryUrlLink")
    public AjaxResult queryUrlLink(String urlLink) throws Exception {
        String cacheObject = redisService.getCacheObject(CacheConstants.WEIXIN_URL_LINK + urlLink);
        if(StringUtils.isEmpty(cacheObject)) {
            return AjaxResult.success();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("url_link", cacheObject);
        map.put("query_type", 0);
        String body = HttpUtil.createPost("https://api.weixin.qq.com/wxa/query_urllink?access_token=" + getAppletToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        if(!"0".equals(object.get("errcode").toString())) {
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "查询加密URLLink" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }
        String string = object.get("url_link_info").toString();
        JSONObject jsonObject = JSON.parseObject(string);
        return AjaxResult.success(jsonObject.get("query"));
    }

    /**
     * 企微消息发送
     * @param phone
     * @param content
     */
    public void sendWeCom(String phone, String content) {
        // 获取userId
        String weComUserId = getWeComUserId(phone);
        DingtalkMsgVo.Text text = new DingtalkMsgVo.Text();
        text.setContent(content);
        Map<String, Object> map = new HashMap<>();
        map.put("touser", weComUserId);
        map.put("msgtype", "text");
        map.put("agentid", weComAgentid);
        map.put("text", text);
        map.put("safe", 0);
        map.put("enable_id_trans", 0);
        map.put("enable_duplicate_check", 0);
        map.put("duplicate_check_interval", 1800);
        String body = HttpUtil.createPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + getWeComToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        log.info("企微消息发送：{}结果：{}", phone, body);
        if(!Constants.ZERO.equals(object.get("errcode").toString())) {
            log.error("企微消息发送失败" + object.get("errcode").toString());
        }
    }

    /**
     * 更具手机号获取userId
     * @param phone
     * @return
     */
    private String getWeComUserId(String phone) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phone);
        String body = HttpUtil.createPost("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + getWeComToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        if(!Constants.ZERO.equals(object.get("errcode").toString())) {
            log.error("更具手机号获取userId" + object);
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "获取企微userId" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }
        return object.get("userid").toString();
    }


    /**
     * 获取企微token
     * @return
     */
    private String getWeComToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.WE_COM_TOKEN);
        if (StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        String body = HttpUtil.createGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + weComSecret).execute().body();
        JSONObject object = JSON.parseObject(body);
        if(!Constants.ZERO.equals(object.get("errcode").toString())) {
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "获取企微token" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }
        String string = object.get("access_token").toString();
        redisService.setCacheObject(CacheConstants.WE_COM_TOKEN, string, 7000L, TimeUnit.SECONDS);
        return string;

    }


    /**
     * 获取时间
     *
     * @param startDate
     * @param endDate
     */
    private List<Visitor> getTime(String startDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<Visitor> list = new ArrayList<>();
        while (!start.isAfter(end)) {
            Visitor gather = new Visitor();
            gather.setCreateTime(sdf.parse(start.toString()));
            list.add(gather);
            start = start.plusDays(1);
        }
        return list;
    }

    /**
     * 新增访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addVis(@RequestBody Visitor visitor) {
        int i = visitorService.insertVisitor(visitor);
        List<Visitor> itemList = visitor.getItemList();
        for (Visitor item : itemList) {
            item.setParentId(visitor.getId());
            //随访人员增加人员注册
//            item=admitCreate(item);
            visitorService.insertVisitor(item);
        }
        return toAjax(i);
    }

    private Visitor admitCreate(Visitor item) {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if ("true".equals(cloud)) {
            String data = sysApiService.admitCreate(item);
            JSONObject json = JSONObject.parseObject(data);
            if ("1".equals(json.get("result") + "")) {
                JSONObject obj = (JSONObject) json.get("data");
                String admitGuid = obj.get("admitGuid") + "";
                item.setGuid(admitGuid);
                //人像注册，如果注册失败将人像置空
                if (StringUtils.isNotEmpty(item.getAvatar())) {
                    String datas = sysApiService.faceRegister(item);
                    JSONObject jsons = JSONObject.parseObject(datas);
                    if ("1".equals(jsons.get("result") + "")) {
                        JSONObject objs = (JSONObject) jsons.get("data");
                        String faceGuid = objs.get("faceGuid") + "";
                        item.setFaceGuid(faceGuid);
                    }
                }
            }
        } else {
            //判断设备人员是否能注册上设备后再删除掉
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(new SysEquipment());
            if (list.size() > 0) {
                Person person = new Person();
                person.setName(item.getName());
                person.setiDNumber(item.getIdcard());
                person.setPhone(item.getPhone());
                String ip = list.get(0).getIp();
                String pass = list.get(0).getPassword();
                String data = sdkService.personCreate(person, ip, pass);
                JSONObject json = JSONObject.parseObject(data);
                if ("1".equals(json.get("result") + "")) {
                    JSONObject obj = (JSONObject) json.get("data");
                    String admitGuid = obj.get("id") + "";
                    item.setGuid(admitGuid);
                    String datas = sdkService.imageCreateUrl(admitGuid, item.getAvatar(), ip, pass);
                    JSONObject jsons = JSONObject.parseObject(datas);
                    if ("1".equals(jsons.get("result") + "")) {
                        String faceGuid = jsons.get("data") + "";
                        item.setFaceGuid(faceGuid);
                        sdkService.imageDeletel(faceGuid, ip, pass);
                    }
                    //再删除以上的注册信息
                    sdkService.personDelete(admitGuid, ip, pass);
                }
            }
        }
        return item;
    }

    /**
     * 修改访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Visitor visitor) throws Exception {
        if(!CollectionUtils.isEmpty(visitor.getFileList())) {
            saveSysFile(visitor.getFileList(), String.valueOf(visitor.getId()));
        }

        // 校验图片
//        checkPhoto(visitor.getAvatar(), visitor.getName());

        visitorService.deleteVisitorItemByParentId(visitor.getId());
        List<Visitor> itemList = visitor.getItemList();
        for (Visitor item : itemList) {
            if (!validatePhoneNumber(item.getPhone())) {
                throw new ServiceException("您输入的随访人员手机号格式不正确");
            }
            item.setParentId(visitor.getId());
            item.setSource(Constants.ONE);
            item.setUserId(visitor.getUserId());
            item.setDeptId(visitor.getDeptId());
            item.setCreateTime(visitor.getCreateTime());
            item.setStartTime(visitor.getStartTime());
            item.setEndTime(visitor.getEndTime());
            visitorService.insertVisitor(item);
        }

        return toAjax(visitorService.updateVisitor(visitor));
    }


    /**
     * 流程审核
     */
    @Log(title = "流程审核", businessType = BusinessType.UPDATE)
    @PostMapping("/approve")
    @Transactional
    public AjaxResult approve(@RequestBody Visitor visitor) {
        log.info("流程审核入参 {}", JSON.toJSONString(visitor));
        try {
            String telephone = StringUtils.isBlank(visitor.getTelephone()) ? "1" : visitor.getTelephone();
            Boolean lock = redisService.lock(APPROVE_KEY, telephone, 60 * 5, TimeUnit.SECONDS);
            log.info("流程审核-lock:{}", lock);
            if (!lock) {
                log.error("approve-审核人员正在审核中");
                return error("正在审核中");
            }

            //查询当前审核地址是否已审核
            VisitorReviewProcessVo visitorReviewProcessVo = new VisitorReviewProcessVo();
            visitorReviewProcessVo.setVisitorId(visitor.getId());
            visitorReviewProcessVo.setApproveData(visitor.getApproveData());
            VisitorReviewProcessVo visitorReviewProcess = visitorService.queryReviewProcess(visitorReviewProcessVo);
            if (ObjectUtil.isNotNull(visitorReviewProcess) && !StringUtils.equals(ExamineEnum.IN_REVIEW.getCode(), visitorReviewProcess.getState())) {
                log.error("approve-当前审核链接已审核");
                return error("当前链接已审核，请刷新页面！");
            }

            //查询当前审核人基本信息
            SysPeople sysPeople = sysPeopleService.queryPeopleName(telephone, null);
            visitor.setUserId(sysPeople.getId());
            visitor.setReviewer(String.valueOf(sysPeople.getId()));

            //查询当前访客信息
            Visitor visitor1 = visitorService.selectVisitorSimpleById(visitor.getId());
            visitor.setCurrentNode(visitor1.getCurrentNode() + 1);

            //赋值公共字段
            VisVisitorExamine examine = visitor.getExamine();
            examine.setVisitorId(visitor.getId());
            visitor.setState(examine.getExamine());
            visitor.setApproveNode(visitor1.getCurrentNode());

            //审核通过
            if (Constants.ZERO.equals(examine.getExamine())) {
                //被访人审核
                if (visitor1.getCurrentNode() == 1) {
                    visitor.setNextStepReviewer(visitor.getReviewer2());

                    List<Visitor> list = new ArrayList<>();
                    Visitor visitor2 = new Visitor();
                    visitor2.setId(visitor.getId());
                    visitor2.setReviewer(String.valueOf(sysPeople.getId()));
                    visitor2.setRejectReason(visitor.getRejectReason());
                    visitor2.setState(ExamineEnum.PASSED.getCode());
                    visitor2.setApproveNode(1);
                    visitor2.setApproveData(visitor.getApproveData());
                    list.add(visitor2);
                    Visitor visitor3 = new Visitor();
                    visitor3.setId(visitor.getId());
                    visitor3.setState(ExamineEnum.IN_REVIEW.getCode());
                    visitor3.setReviewer(visitor.getReviewer2());
                    visitor3.setApproveNode(2);
                    list.add(visitor3);
                    Visitor visitor4 = new Visitor();
                    visitor4.setId(visitor.getId());
                    visitor4.setState(ExamineEnum.IN_REVIEW.getCode());
                    visitor4.setReviewer(visitor.getReviewer3());
                    visitor4.setApproveNode(3);
                    list.add(visitor4);
                    //保存审核环节表
                    visitorService.saveVisitorReviewProcessList(list);
                }
                //二级审核人审核
                else if (visitor1.getCurrentNode() == 2) {
                    visitor.setNextStepReviewer(visitor.getReviewer3());
                    visitorService.updateVisitorReviewProcess(visitor);
                }
                //如果有下一级审核人员，发送钉钉，企微审核消息链接
                if (StrUtil.isNotBlank(visitor.getNextStepReviewer())) {
                    //查询下一节点审核人信息
                    SysPeople nextPeople = sysPeopleService.selectSysPeopleById(Long.parseLong(visitor.getNextStepReviewer()));

                    //查询随访人员信息
                    Visitor visitor2 = new Visitor();
                    visitor2.setParentId(visitor.getId());
                    String url = getExamineUrl(String.valueOf(visitor.getId()), nextPeople.getPhone());
                    log.info("approve发送审核链接：{}", url);

                    try {
                        sendWeCom(nextPeople.getPhone(), url + " --访客姓名：" + visitor.getName());
                    } catch (Exception e) {
                        log.error("访客approve-sendWeCom异常：", e);
                    }
                } else {//最后一级审核
                    visitor.setExamineState(examine.getExamine());
                    //保存审核历史表
                    examine.setRejectReason(visitor.getRejectReason());
                    SysPeople people = sysPeopleService.selectSysPeopleById(visitor.getUserId());
                    examine.setCreateBy(people.getName());
                    visVisitorExamineService.insertVisVisitorExamine(examine);

                    //修改环节状态
                    visitorService.updateVisitorReviewProcess(visitor);

                    // 园区人脸下发到设备
                    if (StringUtils.isEmpty(visitor1.getGuid())) {
                        List<Visitor> listVisitorId = new ArrayList<>();
                        log.info("======开始下发主数据人脸信息：{}", visitor1.getId());
                        Visitor s = deviceDistribute(visitor1, 1);
                        Visitor visitor3 = new Visitor();
                        visitor3.setGuid(s.getGuid());
                        visitor3.setFaceGuid(s.getFaceGuid());
                        visitor3.setId(visitor1.getId());
                        //查询随访人员
                        Visitor visitor11 = new Visitor();
                        visitor11.setParentId(visitor1.getId());
                        List<Visitor> visitors = visitorService.selectVisitorItemList(visitor11);
                        if (!CollectionUtils.isEmpty(visitors)) {
                            for (Visitor visitor2 : visitors) {
                                Visitor visitorInfo = new Visitor();
                                visitor2.setUserId(visitor1.getUserId());
                                visitor2.setRuleGuidMap(s.getRuleGuidMap());
                                log.info("======开始下发从数据人脸信息：{}", visitor1.getId());
                                log.info("从数据规则id：{}", JSON.toJSONString(s.getRuleGuidMap()));
                                Visitor visitorId = deviceDistribute(visitor2, 2);
                                visitorInfo.setId(visitor2.getId());
                                visitorInfo.setGuid(visitorId.getGuid());
                                visitorInfo.setFaceGuid(visitorId.getFaceGuid());
                                listVisitorId.add(visitorInfo);
                            }
                        }
                        listVisitorId.add(visitor3);
                        log.info("更新访客人员信息到设备：{}", listVisitorId);
                        visitorService.updateVisitorInfoGuid(listVisitorId);
                    }

                    // 同意后，给被访人和访客们发送审核结束短信
                    List<String> phoneList = new ArrayList<>();
                    phoneList.add(visitor.getPhone());
                    Visitor visitor2 = new Visitor();
                    visitor2.setParentId(visitor.getId());
                    List<Visitor> itemList = visitorService.selectVisitorItemList(visitor2);
                    if (CollUtil.isNotEmpty(itemList)) {
                        phoneList.addAll(itemList.stream().map(Visitor::getPhone).collect(Collectors.toList()));
                        phoneList = phoneList.stream().distinct().collect(Collectors.toList());
                    }
                    log.info("approve-发同意短信:{}", JSON.toJSONString(phoneList));
                    for (String phone : phoneList) {
                        try {
                            sendMessage(phone, "1", parkName, smsProperties.getTemplate2());
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                    }
                }
            }
            //审核拒绝
            if (Constants.ONE.equals(examine.getExamine())) {
                visitor.setExamineState(examine.getExamine());
                //保存审核历史表
                examine.setRejectReason(visitor.getRejectReason());
                visVisitorExamineService.insertVisVisitorExamine(examine);

                //修改环节状态
                visitorService.updateVisitorReviewProcess(visitor);

                try {
                    sendWeCom(telephone, visitor.getName() + "的访客审核已驳回");
                } catch (Exception e) {
                    log.error("访客approve-sendWeCom驳回异常：", e);
                }
                // 申请人发送短信（审核不通过）
                log.info("approve-发拒绝短信:{}", visitor.getPhone());
                try {
                    sendMessage(visitor.getPhone(), "1", parkName, smsProperties.getTemplate3());
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }

            visitorService.approve(visitor);

            return toAjax(true);
        } catch (Exception e) {
            log.error("审核异常:", e);
            throw new ServiceException("审核异常");
        } finally {
            redisService.deleteObject(APPROVE_KEY);
        }
    }



    /**
     * 被访人审核
     */
    @Log(title = "被访人审核", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVisitorExamineRespondent")
    public AjaxResult updateVisitorExamineRespondent(@RequestBody Visitor visitor) {
        List<SysManageRecord> record = visitorService.querySysManageRecord(visitor.getUserId());
        if (CollectionUtils.isEmpty(record)) {
            throw new RuntimeException("被访人未授权通行");
        }
        VisVisitorExamine examine = visitor.getExamine();
        visitor.setState(examine.getExamine());
        visitor.setReviewer(String.valueOf(visitor.getUserId()));
        visitor.setNextStepReviewer(visitor.getReviewer3());
        if(StringUtils.isNotEmpty(visitor.getReviewer2())) {
            visitor.setNextStepReviewer(visitor.getReviewer2());
        }
        visitorService.saveVisitorAuditRecords(visitor);

        // 1保存审核环节
        if(Constants.ZERO.equals(examine.getExamine())) {
            // 1.1保存安环部审核人
            Visitor visitor1 = new Visitor();
            visitor1.setId(visitor.getId());
            visitor1.setType("7529");
            visitor1.setReviewer(visitor.getReviewer3());
            visitorService.saveVisitorReviewProcess(visitor1);

            // 1.2保存设备部审核人
            Visitor visitor2 = new Visitor();
            visitor2.setId(visitor.getId());
            visitor2.setType("8121");
            visitor2.setReviewer(visitor.getReviewer2());
            visitorService.saveVisitorReviewProcess(visitor2);
            visitor.setType(null);
            visitorService.updateVisitor(visitor);
            SysPeople people = sysPeopleService.selectSysPeopleById(Long.valueOf(visitor.getReviewer2()));
            // 审核通知企微发送消息（小程序来源）
            String appletLink = getAppletLink(String.valueOf(visitor.getId()), "pages/visitor/visitor/examineIndex");
            sendWeCom(people.getPhone(), appletLink + " --访客姓名：" + visitor.getName());
        }

        if(Constants.ONE.equals(examine.getExamine())) {
            Visitor visitor2 = new Visitor();
            if("1".equals(examine.getExamine())) {
                visitor2.setOutTime(new Date());
            }
            visitor2.setId(visitor.getId());
            visitor2.setEndTime(visitor.getEndTime());
            visitorService.updateVisitor(visitor2);
            examine.setVisitorId(visitor.getId());
            LoginUser user = SecurityUtils.getLoginUser();
            visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
            examine.setCreateBy(visitor.getUserName());
            return toAjax(visVisitorExamineService.insertVisVisitorExamine(examine));
        }
        return toAjax(true);

    }

    /**
     * 修改访客信息
     */
    @Log(title = "访客审核", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVisitorExamine")
    public AjaxResult updateVisitorExamine(@RequestBody Visitor visitor) {
        log.info("updateVisitorExamine-入参：{}",JSON.toJSONString(visitor));
        List<SysManageRecord> record = visitorService.querySysManageRecord(visitor.getUserId());
        if (CollectionUtils.isEmpty(record)) {
            throw new RuntimeException("被访人未授权通行");
        }
        SysPeople sysPeople = visitorService.queryVisitorReviewProcess(visitor.getId());
        // 保存审核记录
        VisVisitorExamine examine = visitor.getExamine();
        visitor.setState(examine.getExamine());
        SysPeople people = sysPeopleService.selectSysPeopleById(sysPeople != null ? sysPeople.getId() : visitor.getUserId());
        visitor.setReviewer(String.valueOf(people.getId()));
        visitor.setNextStepReviewer(String.valueOf(people.getId()));
        if("8121".equals(people.getPosition())) {
            visitor.setPosition("7529");
        }
        if("7529".equals(people.getPosition())) {
            visitor.setPosition("8121");
        }
        String string = visitorService.queryReviewProcessOld(visitor);
        log.info("queryReviewProcessOld-Position：{},result：{}", visitor.getPosition(), string);
        visitor.setNextStepReviewer(StringUtils.isNotEmpty(visitor.getReviewer2()) ? visitor.getReviewer2() : visitor.getReviewer3());
        if(StringUtils.isNotEmpty(string)) {
            visitor.setNextStepReviewer(string);
        }
        if(StringUtils.isEmpty(visitor.getNextStepReviewer())) {
            visitor.setNextStepReviewer(String.valueOf(visitor.getUserId()));
        }
        visitorService.saveVisitorAuditRecords(visitor);

        if(sysPeople == null) {
            Visitor visitor2 = new Visitor();
            visitor2.setId(visitor.getId());
            visitor2.setVisitorPosition(visitor.getPosition());
            visitor2.setReviewer2(visitor.getReviewer2());
            visitor2.setReviewer3(visitor.getReviewer3());
            visitorService.updateVisitor(visitor2);
            if(Constants.ONE.equals(examine.getExamine())) {
                try {
                    sendMessage(visitor.getPhone(), "1", null, smsProperties.getTemplate8());
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                visitor.setState(examine.getExamine());
                visitorService.updateVisitorReviewProcess(visitor);

                Visitor visitor3 = new Visitor();
                if("1".equals(examine.getExamine())) {
                    visitor3.setOutTime(new Date());
                }
                visitor3.setId(visitor.getId());
                visitor3.setEndTime(visitor.getEndTime());
                visitorService.updateVisitor(visitor3);
                examine.setVisitorId(visitor.getId());
                LoginUser user = SecurityUtils.getLoginUser();
                visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
                examine.setCreateBy(visitor.getUserName());
                return toAjax(visVisitorExamineService.insertVisVisitorExamine(examine));
            }

            // 保存设备部或安环部审核人
            Visitor visitor1 = new Visitor();
            visitor1.setType(visitor.getPosition());
            visitor1.setReviewer(StringUtils.isNotEmpty(visitor.getReviewer2()) ? visitor.getReviewer2() : visitor.getReviewer3());
            visitor1.setId(visitor.getId());
            visitorService.saveVisitorReviewProcess(visitor1);

            // 审核通知企微发送消息（小程序来源）
            SysPeople people1 = sysPeopleService.selectSysPeopleById(Long.valueOf(visitor.getNextStepReviewer()));
            String appletLink = getAppletLink(String.valueOf(visitor.getId()), "pages/visitor/visitor/examineIndex");
            sendWeCom(people1.getPhone(), appletLink + " --访客姓名：" + visitor.getName());
            return toAjax(true);
        }
        visitor.setPeoplePhone(sysPeople.getPhone());

        log.info("修改访客信息：{}", visitor);
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        CheckCodeVo codeVo = new CheckCodeVo();
        Visitor visitor1 = visitorService.selectVisitorById(visitor.getId());

        // 校验黑名单
        checkBlack(visitor, itemList);

        int i = visitorService.queryVisitorReviewProcessCount(visitor.getId());
        // 设备部门审核同意
        if(Constants.ZERO.equals(examine.getExamine()) && i > 1) {
            visitor.setState(examine.getExamine());
            visitorService.updateVisitorReviewProcess(visitor);

            OfficialAccountVo officialAccountVo = sysPeopleService.queryPeopleById(string);
            // 审核通知企微发送消息（小程序来源）
            String appletLink = getAppletLink(String.valueOf(visitor.getId()), "pages/visitor/visitor/examineIndex");
            sendWeCom(officialAccountVo.getPhone(), appletLink + " --访客姓名：" + visitor.getName());
            Visitor visitor2 = new Visitor();
            visitor2.setId(visitor.getId());
            visitor2.setVisitorPosition(people.getPosition());
            visitorService.updateVisitor(visitor2);
            return toAjax(true);
        }

        // 设备部门审核不同意
        OfficialAccountVo officialAccountVo = sysPeopleService.queryPeopleById(String.valueOf(visitor.getUserId()));
        if(Constants.ONE.equals(examine.getExamine()) && i > 1) {
            Visitor visitor2 = new Visitor();
            visitor2.setId(visitor.getId());
            visitor2.setState(examine.getExamine());
            visitor2.setReviewer(visitor.getReviewer());
            visitorService.updateVisitorReviewProcess(visitor2);
            // 审核通知企微发送消息（小程序来源）
            sendWeCom(officialAccountVo.getPhone(), visitor.getName() + "的访客审核被拒绝");
            try {
                sendMessage(visitor.getPhone(), "1", null, smsProperties.getTemplate8());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            Visitor visitor3 = new Visitor();
            if("1".equals(examine.getExamine())) {
                visitor3.setOutTime(new Date());
            }
            visitor3.setId(visitor.getId());
            visitor3.setEndTime(visitor.getEndTime());
            visitorService.updateVisitor(visitor3);
            examine.setVisitorId(visitor.getId());
            LoginUser user = SecurityUtils.getLoginUser();
            visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
            examine.setCreateBy(visitor.getUserName());
            return toAjax(visVisitorExamineService.insertVisVisitorExamine(examine));
        }

        //审核通过
        if ("0".equals(examine.getExamine())) {
            // 保存审核二维码地址信息
            codeVo.setCode(qdUrl + visitor.getId() + "&time=" + new Date().getTime());
            codeVo.setVisitorId(String.valueOf(visitor.getId()));
            String replace = UUID.randomUUID().toString().replace("-", "");
            codeVo.setId(replace);
            if (StringUtils.isNotEmpty(visitor.getCheckCodeId())) {
                codeVo.setId(visitor.getCheckCodeId());
            }

            if (visitor1 != null) {
                codeVo.setStartTime(visitor1.getStartTime());
                codeVo.setEndTime(visitor1.getEndTime());
            }
            visitorService.saveVisCheckCode(codeVo);

            // 园区人脸下发到设备
            if (visitor1 != null && StringUtils.isEmpty(visitor1.getGuid())) {
                List<Visitor> listVisitorId = new ArrayList<>();
                Visitor s = parkDeviceDistribute(visitor, record);
                Visitor visitor3 = new Visitor();
                visitor3.setGuid(s.getGuid());
                visitor3.setFaceGuid(s.getFaceGuid());
                visitor3.setId(visitor.getId());
                if (!CollectionUtils.isEmpty(visitor.getItemList())) {
                    for (Visitor visitor2 : visitor.getItemList()) {
                        Visitor visitorInfo = new Visitor();
                        visitor2.setUserId(visitor.getUserId());
                        Visitor visitorId = parkDeviceDistribute(visitor2, record);
                        visitorInfo.setId(visitor2.getId());
                        visitorInfo.setGuid(visitorId.getGuid());
                        visitorInfo.setFaceGuid(visitorId.getFaceGuid());
                        listVisitorId.add(visitorInfo);
                    }
                }
                listVisitorId.add(visitor3);
                log.info("更新访客人员信息到设备：" + listVisitorId);
                visitorService.updateVisitorInfoGuid(listVisitorId);
            }

            // 申请人发送短信（审核通过）
            String appletLink = getAppletLink(String.valueOf(visitor.getId()), "pagesC/visExamineEwm/index");
            String[] split = appletLink.split("wxaurl.cn/");
            try {
                sendMessage(visitor.getPhone(), split[1], null, smsProperties.getTemplate5());

                redisService.setCacheObject(CacheConstants.WEIXIN_URL_LINK + visitor.getPhone(), appletLink, 24L, TimeUnit.HOURS);

                // 被访人发送短信（审核通过）
                sendMessage(officialAccountVo.getPhone(), visitor.getName() + "访问" + officialAccountVo.getName(), null, smsProperties.getTemplate9());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }


        if("1".equals(examine.getExamine())) {
            // 申请人发送短信（审核不通过）
            SysPeople people1 = sysPeopleService.selectSysPeopleById(visitor.getUserId());
            sendWeCom(people1.getPhone(), visitor.getName() + "的访客审核被拒绝");
            try {
                sendMessage(visitor.getPhone(), "1", null, smsProperties.getTemplate8());

                // 被访人发送短信（审核不通过）
                sendMessage(officialAccountVo.getPhone(), visitor.getName() + "访问" + officialAccountVo.getName(), null, smsProperties.getTemplate10());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        visitor.setState(examine.getExamine());
        visitorService.updateVisitorReviewProcess(visitor);

        Visitor visitor2 = new Visitor();
        if("1".equals(examine.getExamine())) {
            visitor2.setOutTime(new Date());
        }
        visitor2.setId(visitor.getId());
        visitor2.setEndTime(visitor.getEndTime());
        visitorService.updateVisitor(visitor2);
        examine.setVisitorId(visitor.getId());
        LoginUser user = SecurityUtils.getLoginUser();
        visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
        examine.setCreateBy(visitor.getUserName());
        return toAjax(visVisitorExamineService.insertVisVisitorExamine(examine));
    }

    /**
     * 校验黑名单
     */
    private void checkBlack(Visitor visitor, List<Visitor> itemList) {
        //判断是否存在黑名单，存在即审核失败
        SysBlackList sysBlackList = new SysBlackList();
        sysBlackList.setPhone(visitor.getPhone());
        List<SysBlackList> list = sysBlackListService.selectSysBlackListList(sysBlackList);
        if (list.size() > 0) {
            throw new ServiceException("存在黑名单无法审核通过");
        }
        for (Visitor items : itemList) {
            SysBlackList sysBlackLists = new SysBlackList();
            sysBlackLists.setPhone(items.getPhone());
            List<SysBlackList> lists = sysBlackListService.selectSysBlackListList(sysBlackLists);
            if (lists.size() > 0) {
                throw new ServiceException("存在黑名单无法审核通过");
            }
        }
    }

    /**
     * 园区人脸设备下发
     */
    private Visitor deviceDistribute(Visitor visitor,Integer type) {
        // 查询被访人授权记录
        Visitor s = new Visitor();
        SysEquipment equipment = new SysEquipment();
        equipment.setFlag("0");
        equipment.setIsCj("0");
        equipment.setProductId(3L);
        List<SysEquipment> equipList = equipmentService.selectSysEquipmentList(equipment);
        String guid = IdUtils.simpleUUID();
        String faceId = IdUtils.simpleUUID();
        s.setGuid(guid);
        s.setFaceGuid(faceId);

        Map<String, String> map = new HashMap<>();
        //通过规则获取绑定设备信息
        for (SysEquipment e : equipList) {
            //将人员信息下发到设备
            Person person = new Person();
            person.setName(visitor.getName());
            person.setPhone(visitor.getPhone());
            person.setId(guid);

            String ip = e.getIp();
            String pass = e.getPassword();
            //添加临时规则
            String ruleGuid = "";
            if(type == 1) {
                String s1 = sdkService.ruleCreate("vis_" + visitor.getId(), ip, pass, visitor.getStartTime(), visitor.getEndTime());
                log.info("设备：{}-创建规则结果：{}", e.getIp(), s1);
                JSONObject jsonObject1 = JSONObject.parseObject(s1);
                if (!StringUtils.equals("LAN_SUS-0", jsonObject1.getString("code"))) {
                    log.error("临时访客创建规则下发失败visitorId:{},ip:{}", visitor.getId(), e.getIp());
                    continue;
                }
                ruleGuid = jsonObject1.getJSONObject("data").getString("ruleId");
                map.put(ip, ruleGuid);
            } else {
                ruleGuid = visitor.getRuleGuidMap().get(ip);
            }

            //添加人员规则
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ruleId", ruleGuid);
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("timezoneRule", jsonObject);
            List<JSONObject> objects = new ArrayList<>();
            objects.add(jsonObject2);
            person.setRule(objects);

            //创建人员
            log.info("设备：{}，临时访客创建人员：{}", ip, JSON.toJSONString(person));
            String s2 = sdkService.personCreate(person, ip, pass);
            log.info("设备：{}，临时访客创建人员返回：{}", ip, s2);
            JSONObject jsonObject3 = JSONObject.parseObject(s2);
            if (!StringUtils.equals("LAN_SUS-0", jsonObject3.getString("code"))) {
                log.error("临时访客创建人员下发失败visitorId:{},ip:{}", visitor.getId(), e.getIp());
                continue;
            }
            //设置人员有效期
            String s3 = sdkService.permissionsCreate(guid, DateUtil.format(visitor.getEndTime(), DatePattern.NORM_DATETIME_PATTERN), ip, pass);
            JSONObject jsonObject4 = JSONObject.parseObject(s3);
            if (!StringUtils.equals("LAN_SUS-0", jsonObject4.getString("code"))) {
                log.error("临时访客设置人员有效期下发失败visitorId:{},ip:{}", visitor.getId(), e.getIp());
            }
            //设置人脸图片
            if (StringUtils.isNotEmpty(visitor.getAvatar())) {
                String s4 = sdkService.imageCreateUrl(guid, faceId, visitor.getAvatar(), ip, pass);
                JSONObject jsonObject5 = JSONObject.parseObject(s4);
                if (!StringUtils.equals("LAN_SUS-0", jsonObject5.getString("code"))) {
                    log.error("临时访客设置人员图片下发失败visitorId:{},ip:{}", visitor.getId(), e.getIp());
                }
            }
            //保存下发记录
            SysPeopleEquipment sysPeopleEquipment = new SysPeopleEquipment();
            sysPeopleEquipment.setVisitorId(visitor.getId());
            sysPeopleEquipment.setEquipmentId(e.getId());
            sysPeopleEquipment.setGuid(guid);
            sysPeopleEquipment.setFaceGuid(faceId);
            peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
        }
        s.setRuleGuidMap(map);
        return s;
    }

    /**
     * 园区人脸设备下发
     */
    private Visitor parkDeviceDistribute(Visitor visitor, List<SysManageRecord> record) {
        // 查询被访人授权记录
        Visitor s = new Visitor();
        for (SysManageRecord sysManageRecord : record) {
            SysRule rule = sysRuleService.selectSysRuleById(sysManageRecord.getRuleId());
            String[] pointIds = rule.getPointId().split(",");
            List<SysEquipment> equipList = new ArrayList<>();
            for (String point : pointIds) {
                SysEquipment equipment = new SysEquipment();
                equipment.setPointId(Long.parseLong(point));
                equipment.setFlag("0");
                equipment.setIsCj("0");
                equipment.setProductId(3L);
                List<SysEquipment> equipmentDtoList = equipmentService.selectSysEquipmentList(equipment);
                equipList.addAll(equipmentDtoList);
            }
            String guid = IdUtils.simpleUUID();
            String faceId = IdUtils.simpleUUID();
            s.setGuid(guid);
            s.setFaceGuid(faceId);
            //通过规则获取绑定设备信息
            for (SysEquipment e : equipList) {
                //将人员信息下发到设备
                Person person = new Person();
                person.setName(visitor.getName());
                person.setPhone(visitor.getPhone());
                person.setId(guid);
                String ip = e.getIp();
                String pass = e.getPassword();
                sdkService.personCreate(person, ip, pass);
                sdkService.permissionsCreate(guid, DateUtil.format(visitor.getEndTime(), DatePattern.NORM_DATETIME_PATTERN), ip, pass);

                if (StringUtils.isNotEmpty(visitor.getAvatar())) {
                    sdkService.imageCreateUrl(guid, faceId, visitor.getAvatar(), ip, pass);
                }
                //保存下发记录
                SysPeopleEquipment sysPeopleEquipment = new SysPeopleEquipment();
                sysPeopleEquipment.setVisitorId(visitor.getId());
                sysPeopleEquipment.setEquipmentId(e.getId());
                sysPeopleEquipment.setGuid(guid);
                sysPeopleEquipment.setFaceGuid(faceId);
                peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
            }
        }
        return s;
    }


    /**
     * 取消访问申请
     */
    @Log(title = "取消访问申请", businessType = BusinessType.DELETE)
    @PostMapping("/cancel")
    @Transactional
    public AjaxResult cancel(@RequestBody Visitor visitor) {
        log.info("取消访问申请入参 {}", JSON.toJSONString(visitor));
        //审核业务
        visitorService.cancel(visitor);

        return toAjax(true);
    }

    /**
     * 访客签到签退
     */
    @Log(title = "访客签到签退", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVisitorInOut")
    public AjaxResult updateVisitorInOut(@RequestBody Visitor visitor) {
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        for (Visitor items : itemList) {
            if ("in".equals(visitor.getTabFlag())) {
                items.setInTime(new Date());
            } else {
                items.setOutTime(new Date());
            }
            visitorService.updateVisitor(items);
        }
        if ("in".equals(visitor.getTabFlag())) {
            visitor.setInTime(new Date());
        } else {
            visitor.setOutTime(new Date());
        }
        return toAjax(visitorService.updateVisitor(visitor));
    }


    private void delVisVisitorItemList(Long id) {
        Visitor item = new Visitor();
        item.setParentId(id);
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        String admitGuids = "";
        for (Visitor items : itemList) {
            admitGuids += items.getGuid() + ",";
        }
        if (!"".equals(admitGuids)) {
            String cloud = configService.selectConfigByKey("sys.equipment.cloud");
            if ("true".equals(cloud)) {
                admitGuids = admitGuids.substring(0, admitGuids.length() - 1);
                if (!"null".equals(admitGuids)) {
                    String data = sysApiService.admitDelete(admitGuids);
                }
            } else {
                List<SysEquipment> equipmentDtoList = equipmentService.selectSysEquipmentList(new SysEquipment());
                for (SysEquipment eq : equipmentDtoList) {
                    sdkService.personDelete(admitGuids, eq.getIp(), eq.getPassword());
                }
            }
        }
    }

    /**
     * 删除访客信息
     */
    @RequiresPermissions("visitor:visitor:remove")
    @Log(title = "访客信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        String admitGuids = "";
        for (Long visitorId : ids) {
            Visitor Visitor = visitorService.selectVisitorById(visitorId);
            admitGuids += Visitor.getGuid() + ",";
            visitorService.deleteVisitorItemByParentId(visitorId);
            //删除子项存在的注册人员信息
            delVisVisitorItemList(visitorId);
        }
        return toAjax(visitorService.deleteVisitorByIds(ids));
    }

    @Log(title = "访客信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/canceVisitor/{id}")
    public AjaxResult canceVisitor(@PathVariable Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        //保存访客通行规则
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        try {
            if ("true".equals(cloud)) {
                sysApiService.authDeviceRevoke(visitor);
            } else {
                sdkService.authDeviceRevoke(visitor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(visVisitorExamineService.deleteVisVisitorExamineByVisitorId(id));
    }

    public AjaxResult sendMessage(String phone, String code, String parkName, String templateId) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(phone)) {
            return error("手机号不能为空!");
        }
        if (!smsProperties.getEnabled()) {
            error("当前系统没有开启短信功能！");
        }
        Map<String, String> map = new HashMap<>(1);
        map.put("code", code);
        if (StringUtils.isNotBlank(parkName)) {
            map.put("park_name", parkName);
        }
        SmsTemplate smsTemplate = SpringUtils.getBean(SmsTemplate.class);
        log.info("访客短信发送{}模板：{}参数：{}", phone, templateId, JSON.toJSONString(map));
        SmsResult result = smsTemplate.send(phone, templateId, map);
        log.info("短信发送{}结果：{}", phone, JSON.toJSONString(result));
        if (!result.getIsSuccess()) {
            return error(result.getMessage());
        }
        return AjaxResult.success("成功", result.getResponse());
    }


    @PostMapping("/test")
    public AjaxResult test(@RequestBody JSONObject js) throws Exception {
        String code = js.getString("code");
        String template = js.getString("template");
        String parkName = js.getString("parkName");
        String phone = js.getString("phone");
        return sendMessage(phone, code, parkName, template);
    }

    /**
     * 查询访客记录列表
     *
     * @param visitor
     * @return
     */
    @GetMapping("/queryVisitorRecordList")
    public TableDataInfo queryVisitorRecordList(VisitorRecordVo visitor) {
        startPage();
        List<VisitorRecordVo> list = visitorService.queryVisitorRecordList(visitor);
        return getDataTable(list);
    }

    /**
     * 删除访客记录
     *
     * @param ids
     * @return
     */
    @PostMapping("/deleteVisitorRecordList")
    public AjaxResult deleteVisitorRecordList(String ids) {
        String[] split = ids.split(",");
        visitorService.deleteVisitorRecordList(split);
        return AjaxResult.success();
    }

    /**
     * 新增访客记录
     *
     * @return
     */
    @PostMapping("/saveVisitorRecord")
    public AjaxResult saveVisitorRecord(VisitorRecordVo recordVo) {
        Visitor visitor = new Visitor();
        if ("2".equals(recordVo.getType())) {
            visitorService.updateVisitorRecord(recordVo);
            visitor.setEndTime(recordVo.getEndTime());
            visitorService.updateVisitor(visitor);
            return AjaxResult.success();
        }
        visitor.setStartTime(recordVo.getStartTime());
        visitorService.saveVisitorRecord(recordVo);
        return AjaxResult.success();
    }

    /**
     * 校验头像上传宇泛人脸机是否通过
     *
     * @param avatar
     */
    private void checkPhoto(String avatar, String name) throws Exception {
        if (StringUtils.isNotEmpty(avatar)) {
            String[] split = avatar.split(minioGwurl);
            String s = minioUrl + split[1];
            try {
                File file = FileUtils.urlToFile("111", s);
                String body = HttpUtil.createPost(upload).form("file", file).execute().body();
                if (!file.delete()) {
                    log.info("删除临时文件失败成功");
                }
                JSONObject object = JSONObject.parseObject(body);
                String string = object.get("code").toString();
                if (!"0".equals(string)) {
                    log.info("来访人头像校验失败：{}", avatar);
                    throw new ServiceException("来访人" + name + "头像校验失败,请重新上传");
                }
            } catch (HttpException e) {
                log.error("来访人头像校验失败", e);
            }
        }
    }

    /**
     * 查询访客数量（今日，本周，本月）
     *
     * @param recordVo
     * @return
     */
    @PostMapping("/queryVisitorCount")
    public AjaxResult queryVisitorCount(VisitorRecordVo recordVo) {
        return success(visitorService.queryVisitorCount(recordVo));
    }

    /**
     * 首页头像展示
     * @param recordVo
     * @return
     */
    @PostMapping("/queryVisitorAvatar")
    public AjaxResult queryVisitorAvatar(VisitorRecordVo recordVo) {
        return success(visitorService.queryVisitorAvatar(recordVo));
    }

    @GetMapping("/queryTest")
    public AjaxResult queryTest(VisitorRecordVo recordVo) {
        return success(visitorService.queryTest(recordVo));
    }



    /**
     * 查询我的审核列表
     */
    @GetMapping(value = "/getReviewList")
    public TableDataInfo getReviewList(Visitor visitor) {

        //查询当前登陆人
        LoginUser loginUser = SecurityUtils.getLoginUser();

        Long userId = loginUser.getUserid();
        SysUser sysUser = sysUserService.selectUserById(userId);

        Long peopleId = sysPeopleService.selectAppSysPeople(sysUser);

        startPage();
        //临时访客
        if (StringUtils.equals("0", visitor.getVisitorType())) {
            List<Visitor> list = visitorService.queryReviewList(peopleId);
            return getDataTable(list);
        }
        //出门证
        if (StringUtils.equals("1", visitor.getVisitorType())) {
            List<VisExitOutVo> list = visCarryStuffService.queryReviewList(peopleId);

            //查询物品信息列表
            List<Long> collect = list.stream().map(VisExitOutVo::getId).collect(Collectors.toList());
            VisStuffInfoVo visStuffInfoVo = new VisStuffInfoVo();
            visStuffInfoVo.setExitIds(collect);
            List<VisStuffInfoVo> stuffList = visCarryStuffService.selectStuffList(visStuffInfoVo);
            if (CollUtil.isEmpty(stuffList)) {
                return getDataTable(list);
            }

            //处理字典值
            Map<String, String> map = dictDataService.queryDictData("vis_out_stuff_type");
            stuffList.forEach(stuff -> {
                if (StrUtil.isNotBlank(stuff.getType())) {
                    stuff.setTypeName(map.get(stuff.getType()));
                }
            });

            //构造数据
            Map<Long, List<VisStuffInfoVo>> collect1 = stuffList.stream().collect(Collectors.groupingBy(VisStuffInfoVo::getExitId));
            list.forEach(exit -> {
                exit.setVisStuffInfoList(collect1.get(exit.getId()));
            });

            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }
}
