package com.dcsoft.system.uniubi.controller;


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.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.RemoteFileService;
import com.dcsoft.system.api.domain.SysFile;
import com.dcsoft.system.api.model.LoginUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.kq.domain.KqGroupUser;
import com.dcsoft.system.kq.service.IKqGroupUserService;
import com.dcsoft.system.ladder.domain.EmpowerManageVo;
import com.dcsoft.system.ladder.domain.LadderRecordVo;
import com.dcsoft.system.ladder.domain.StoreyInfoVo;
import com.dcsoft.system.ladder.domain.TLadderRule;
import com.dcsoft.system.ladder.service.ITEmpowerManageService;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.*;
import com.dcsoft.system.uniubi.service.ISysSdkService;

import com.dcsoft.system.utils.FTPUtil;
import com.dcsoft.system.utils.PictureUtils;
import com.dcsoft.system.visitor.domain.CheckCodeVo;
import com.dcsoft.system.visitor.domain.VisVisitorExamine;
import com.dcsoft.system.visitor.domain.Visitor;
import com.dcsoft.system.visitor.domain.VisitorRecordVo;
import com.dcsoft.system.visitor.service.IVisVisitorExamineService;
import com.dcsoft.system.visitor.service.IVisitorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.dcsoft.common.core.web.domain.AjaxResult.success;


/**
 * 用户管理 业务处理
 *
 * @author xueyi
 */
@Slf4j
@RestController
@RequestMapping("/sdk")
public class SysSdkController {

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

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

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

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

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

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

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

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

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

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

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

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

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    protected ISysPeopleService peopleService;

    @Autowired
    private IKqGroupUserService groupUserService;

    @Autowired
    protected IVisitorService visitorService;

    @Autowired
    protected ISysPeopleRecordService peopleRecordService;

    @Autowired
    protected ISysEquipmentService equipmentService;

    @Autowired
    protected ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysEmpowerRecordService sysEmpowerRecordService;

    @Autowired
    private ISysRuleService sysRuleService;

    @Autowired
    private IVisVisitorExamineService visVisitorExamineService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemoteFileService fileService;

    @Resource
    private ITEmpowerManageService empowerManageService;

    @Autowired
    private ISysBlackListService sysBlackListService;


    /**
     * 宇泛人脸设备二维码回调地址
     * @param info
     * @return
     */
    @PostMapping("/backUrlEwm")
    public JSONObject ewm(EwmInfo info) {
        // 钉工牌二维码校验
        if(info.getQRdata().contains("dingbadge")) {
            return dingTalkEwm(info);
        }
        CheckCodeVo codeVo = visitorService.queryVisCheckCodeById(info.getQRdata());
        if(codeVo == null || !codeVo.getCode().contains("/pages/visitor/visitor/visExamineEwm")) {
            throw new ServiceException("无效验证码");
        }
        JSONObject obj=new JSONObject();
        SysEquipment equipment=equipmentService.selectEquipmentBySequence(info.getDeviceKey());
        //判断是用户二维码还是访客二维码
        //用户，判断是否是时间是否是分钟内的码
        String qRdata=codeVo.getCode();
        String[] time=qRdata.split("&time=");
        //判断改设备是否绑定改人员
//        if(StringUtils.isNotEmpty(time[1])){
//            //判断是否在权限时间内
//            if(new Date().getTime()-Long.parseLong(time[1])<5*60*1000){
//                String[] ids=time[0].split("id=");      //判断改设备是否绑定改人员
//                SysEmpowerRecord sysEmpowerRecord=new SysEmpowerRecord();
//                sysEmpowerRecord.setEquipmentId(equipment.getId());
//                sysEmpowerRecord.setPeopleId(ids[1]);
//                List<SysEmpowerRecord> SysEmpowerRecordList= sysEmpowerRecordService.selectSysEmpowerRecordList(sysEmpowerRecord);
//                if(SysEmpowerRecordList.size()>0){
//                    SysRule rule=sysRuleService.selectSysRuleById(SysEmpowerRecordList.get(0).getRuleId());
//                    if(rule.getEndTime().getTime()>new Date().getTime()){
//                        SysPeople people=peopleService.selectSysPeopleById(Long.parseLong(ids[1]));
//                        obj.put("ttsModContent",people.getName()+"请进");
//                        obj.put("displayModContent",people.getName()+"请进");
//                        obj.put("isOpenRelay",1);
//                    }
//                }else{
//                    obj.put("ttsModContent","未授权，请联系管理员");
//                    obj.put("displayModContent","未授权，请联系管理员");
//                    obj.put("isOpenRelay",2);
//                }
//            }else{
//                obj.put("ttsModContent","二维码已过期");
//                obj.put("displayModContent","二维码已过期");
//                obj.put("isOpenRelay",2);
//            }
//        }else{
            //访客

            String[] ids=qRdata.split("id=");
            String[] split = ids[1].split("&time=");
            Visitor visitor1 = visitorService.selectVisitorById(Long.parseLong(split[0]));
            SysEmpowerRecord sysEmpowerRecord=new SysEmpowerRecord();
            sysEmpowerRecord.setEquipmentId(equipment.getId());
            sysEmpowerRecord.setPeopleId(String.valueOf(visitor1.getUserId()));
            List<SysEmpowerRecord> SysEmpowerRecordList= sysEmpowerRecordService.selectSysEmpowerRecordList(sysEmpowerRecord);
            if(CollectionUtils.isEmpty(SysEmpowerRecordList)){
                SysRule rule=sysRuleService.selectSysRuleById(SysEmpowerRecordList.get(0).getRuleId());
                if(rule.getEndTime().getTime()>new Date().getTime()){
                    Visitor visitor=visitorService.selectVisitorById(Long.parseLong(split[0]));
                    obj.put("ttsModContent",visitor.getName()+"请进");
                    obj.put("displayModContent",visitor.getName()+"请进");
                    obj.put("isOpenRelay",1);
                    // 保存识别记录
                    VisitorRecordVo record = new VisitorRecordVo();
                    String entryExitType = SysEmpowerRecordList.get(0).getEntryExitType();
                    // 进门设备
                    if("1".equals(entryExitType)) {
                        record.setVisitorId(split[0]);
                        record.setSequence(info.getDeviceKey());
                        record.setStartTime(new Date(Long.parseLong(info.getTime())));
                        record.setType("1");
                        visitorService.saveVisitorRecord(record);
                        visitor.setInTime(new Date());
                        visitorService.updateVisitor(visitor);
                        saveHeadOffice(record);
                        return obj;
                    }
                    // 出门设备
                    if("2".equals(entryExitType)) {
                        record.setEndTime(new Date(Long.parseLong(info.getTime())));
                        record.setVisitorId(split[0]);
                        record.setType("2");
                        visitorService.updateVisitorRecord(record);
                        visitor.setOutTime(new Date());
                        visitorService.updateVisitor(visitor);
                        saveHeadOffice(record);
                        return obj;
                    }
                }
            }else{
                obj.put("ttsModContent","未授权，请联系管理员");
                obj.put("displayModContent","未授权，请联系管理员");
                obj.put("isOpenRelay",2);
            }

//        }
        return obj;
    }

    /**
     * 同步总部访客记录信息
     * @param record
     */
    private void saveHeadOffice(VisitorRecordVo record) {
        //推送记录给总平台
        if("true".equals(uploadMiddling)){
            String body = HttpUtil.createPost(saveVisitorRecord).body(JSON.toJSONString(record)).execute().body();
            log.info("同步总部访客记录信息：{}", body);
        }

    }

    /**
     * 钉工牌二维码校验开门
     */
    @PostMapping("/dingTalkEwm")
    public JSONObject dingTalkEwm(EwmInfo info) {
        JSONObject obj = new JSONObject();

        // 校验二维码
        DingtalkCode code = deCode(info);
        if("invalidPayCode".equals(code.getCode())) {
            obj.put("ttsModContent", "无效二维码");
            obj.put("displayModContent", "无效二维码");
            obj.put("isOpenRelay", Constants.ACCESS_CONTROL_TWO);
            return obj;
        }

        if(StringUtils.isNotEmpty(code.getCode())) {
            obj.put("ttsModContent", code.getMessage());
            obj.put("displayModContent", code.getMessage());
            obj.put("isOpenRelay", Constants.ACCESS_CONTROL_TWO);
            return obj;
        }

        // 获取钉工牌工号校验是否有权限通过
        String details = getDetails(code.getUserId());
        SysPeople people = new SysPeople();
        people.setGh(details);
        people.setSequence(info.getDeviceKey());
        SysPeople sysPeople = equipmentService.queryPeopleInfo(people);
        if(sysPeople == null) {
            obj.put("ttsModContent", Constants.TTS_MOD_CONTENT);
            obj.put("displayModContent", Constants.DISPLAY_MOD_CONTENT);
            obj.put("isOpenRelay", Constants.ACCESS_CONTROL_TWO);
            return obj;
        }

        // 校验通行规则
        SysRule rule = sysRuleService.selectSysRuleById(sysPeople.getRuleId());
        if(rule.getEndTime().getTime() > new Date().getTime()) {
            asyncsendV2(code.getUserId(), "text", "开门");
            obj.put("ttsModContent", sysPeople.getName()+"请进");
            obj.put("displayModContent", sysPeople.getName()+"请进");
            obj.put("isOpenRelay", Constants.ACCESS_CONTROL_ONE);
            return obj;
        }
        obj.put("ttsModContent", "通行时间已过期");
        obj.put("displayModContent", "通行时间已过期");
        obj.put("isOpenRelay",Constants.ACCESS_CONTROL_TWO);
        return obj;
    }


    /**
     * 宇泛人脸设备回调地址
     *
     * @return 回调信息
     */
    @PostMapping("/backUrl")
    public BackResult backUrl(BackInfo info) {
        SysPeopleRecord peopleRecord = new SysPeopleRecord();
        if (!"STRANGERBABY".equals(info.getPersonId())){
            log.info("设备序列号：{}", info);
            SysEquipment eqs=equipmentService.selectEquipmentBySequence(info.getDeviceKey());
            peopleRecord.setEquipmentId(eqs.getId()+"");
            peopleRecord.setAdmitGuid(info.getPersonId());
            peopleRecord.setAliveType(info.getAliveType());
            peopleRecord.setDeviceNo(info.getDeviceKey());
            peopleRecord.setType(info.getIdentifyType());
            peopleRecord.setCardNo(info.getIdcardNum());
            peopleRecord.setRecType(info.getRecType());
            peopleRecord.setPermissionTimeType(info.getPermissionTimeType());
            peopleRecord.setPassTimeType(info.getPassTimeType());
            peopleRecord.setRecModeType(info.getRecModeType());
            peopleRecord.setTimestamp(Long.parseLong(info.getTime()));
            peopleRecord.setShowTime(Long.parseLong(info.getTime()));
            peopleRecord.setShowDate(new Date(Long.parseLong(info.getTime())));
            peopleRecord.setRecMode(info.getModel());
            peopleRecord.setDeviceIp(info.getIp());
            //标准版本
            /*SysPeopleEquipment peopleEquipment= peopleEquipmentService.selectSysPeopleEquipmentByGuId(info.getPersonId());
            if(peopleEquipment!=null){
                peopleRecord.setPeopleId(peopleEquipment.getPeopleId()+"");
                peopleRecord.setFlag("0");
                //判断识别人员是否在考勤组中，是在考勤组中将识别信息塞入到考勤记录中
                KqGroupUser kqGroupUser=new KqGroupUser();
                kqGroupUser.setUserId(peopleEquipment.getPeopleId());
                List<KqGroupUser> list=groupUserService.selectKqGroupUserList(kqGroupUser);
                if(list.size()>0){//考勤记录
                    peopleRecord.setGroupId(list.get(0).getGroupId());
                    //依据考勤记录将信息放入到考勤结果表中
                    sdkService.insertKqxx(peopleRecord);
                }
            }else{
                Visitor vis= visitorService.selectByGuid(peopleRecord.getAdmitGuid());
                if(vis!=null){
                    peopleRecord.setPeopleId(vis.getId()+"");
                }
                peopleRecord.setFlag("1");
            }*/
            SysPeople sysPeople=new SysPeople();
            sysPeople.setGuid(info.getPersonId());
            SysPeople people= peopleService.selectByGuid(sysPeople);
            if(people!=null){
                peopleRecord.setPeopleId(people.getId()+"");
                //考勤版本
//               ;
//                peopleRecord.setFlag("0");
//                //判断识别人员是否在考勤组中，是在考勤组中将识别信息塞入到考勤记录中
//                KqGroupUser kqGroupUser=new KqGroupUser();
//                kqGroupUser.setUserId(people.getId());
//                List<KqGroupUser> list=groupUserService.selectKqGroupUserList(kqGroupUser);
//                if(list!=null&&list.size()>0){//考勤记录
//                    peopleRecord.setGroupId(list.get(0).getGroupId());
//                    //依据考勤记录将信息放入到考勤结果表中
//                    sdkService.insertKqxx(peopleRecord);
//                }
                //标准版本
//            String imgUrl=getImg(info.getPath(),info.getIp(),eqs.getPassword());
//            peopleRecord.setFilePath(imgUrl);
            }
            if(StringUtils.isNotEmpty(info.getPath())){//考勤版本
             /*   String urls="http://"+eqs.getIp()+":8090/download/image?pass="+eqs.getPassword()+"&filename="+info.getPath();
                MultipartFile file= PictureUtils.createMultipartFile(urls,eqs.getSequence()+".jpg");
                R<SysFile> datas= fileService.uploadMinio(file,"IdentifyRecords");
                if(datas.getData()!=null){
                    peopleRecord.setFilePath(datas.getData().getUrl());
                }*/
                String imgUrl=getImg(info.getPath(),info.getIp(),eqs.getPassword());
                peopleRecord.setFilePath(imgUrl);
            }

            /*Visitor visitor = visitorService.queryVisitorGuid(info.getPersonId());
            if(visitor != null && StringUtils.isNotEmpty(visitor.getGuid())) {
                VisitorRecordVo record = new VisitorRecordVo();
                String entryExitType = eqs.getEntryExitType();
                // 进门设备
                if("1".equals(entryExitType)) {
                    record.setVisitorId(String.valueOf(visitor.getId()));
                    record.setSequence(info.getDeviceKey());
                    record.setStartTime(new Date(Long.parseLong(info.getTime())));
                    record.setType("1");
                    visitorService.saveVisitorRecord(record);
                    visitor.setInTime(new Date());
                    visitorService.updateVisitor(visitor);
                    saveHeadOffice(record);
                    return new BackResult(1,true);
                }
                // 出门设备
                if("2".equals(entryExitType)) {
                    record.setEndTime(new Date(Long.parseLong(info.getTime())));
                    record.setVisitorId(String.valueOf(visitor.getId()));
                    record.setType("2");
                    visitorService.updateVisitorRecord(record);
                    visitor.setOutTime(new Date());
                    visitorService.updateVisitor(visitor);
                    saveHeadOffice(record);
                    return new BackResult(1,true);
                }
            }*/

            peopleRecordService.insertSysPeopleRecord(peopleRecord);


            //推送记录给总平台
            if("true".equals(uploadMiddling)){
                JSONObject paramMap=new JSONObject();
                peopleRecord.setSign(sign);
                paramMap.put("peopleRecord",peopleRecord);
                com.dcsoft.system.utils.HttpUtil.postDataJson(uploadUrl,paramMap);
            }
        }
        return new BackResult(1,true);
    }

    private String getImg(String path,String ip,String pass) {
        String url="";
        InputStream in = null;
        OutputStream os= null;
        try{
            String paths = "/IdentifyRecords/";
            //读取单个文件
            FTPClient ftpClient = FTPUtil.getFTPClient(ip,8010,"admin",pass);
            String fileName = path.split("IdentifyRecords")[1];

            String pathsl =paths+fileName.substring(0,fileName.lastIndexOf("/")+1);
            String fileNames =fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());

            String savePath=pathUrl +paths+fileName;

            in = FTPUtil.getFTPFile(ftpClient,pathsl,fileNames);
            File file = new File(savePath);//System.getProperty("java.io.tmpdir")缓存
            System.out.println("文件夹"+savePath.substring(0,savePath.lastIndexOf("/")));
            if (!file.exists()|| !file.isDirectory()) { //如果是目录先创建
                new File(savePath.substring(0,savePath.lastIndexOf("/"))).mkdirs(); //目录先创建
            }
            os = new FileOutputStream(file);

            int bytesRead;
            int len = 8192;
            byte[] buffer = new byte[len];
            while ((bytesRead = in.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            url=identifyRecords+paths+fileName;
            //关闭连接
            FTPUtil.disConnection(ftpClient);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                //关闭流
                if (in != null)
                    in.close();
                if (os != null)
                os.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return url;
    }


    /**
     * 回调信息
     *
     * @return 回调信息
     */
    @GetMapping("/personCreate")
    public AjaxResult personCreate() {
      /*  Person person =new Person();
        person.setId("323dc840fabc42d9afd4401e911a579e");
        person.setName("test1");
        String msg=sdkService.personCreate(person,"192.168.1.34","123123a");*/
        return success();
    }

    @PostMapping("/backUrlHeart")
    public AjaxResult heart(HeartInfo info) {
        //获取设备缓存的设备时间
        redisService.setCacheObject(info.getDeviceKey(),info.getTime());
        redisService.expire(info.getDeviceKey(),2*60);
        SysEquipment equipment=new SysEquipment();
        equipment.setProductId(3L);
        List<SysEquipment> list=equipmentService.selectSysEquipmentList(equipment);
        for(SysEquipment e:list){
            String time = redisService.getCacheObject(e.getSequence());
            if(StringUtils.isNotEmpty(time)){
                e.setFlag("0");
                equipmentService.updateSysEquipment(e);
            }else{
                e.setFlag("1");
                equipmentService.updateSysEquipment(e);
            }
        }
        return success();

    }

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

    }

    /**
     * 解析钉工牌二维码
     */
    private DingtalkCode deCode(EwmInfo info) {
        String requestId = redisService.getCacheObject(info.getQRdata());
        if(StringUtils.isEmpty(requestId)) {
            requestId = String.valueOf(UUID.randomUUID());
            redisService.setCacheObject(info.getQRdata(), requestId, 10L, TimeUnit.MINUTES);
        }
        info.setRequestId(requestId);
        info.setPayCode(info.getQRdata());
        String body = HttpUtil.createPost(deCode)
                .header("x-acs-dingtalk-access-token", getToken())
                .body(JSON.toJSONString(info))
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(body);
        DingtalkCode code = new DingtalkCode();
        if(object.get("code") != null) {
            code.setMessage(object.get("message").toString());
            code.setCode(object.get("code").toString());
            return code;
        }
        code.setUserId(object.get("userId").toString());
        return code;
    }

    /**
     * 查询钉工牌详情
     */
    private String getDetails(String userId) {
        Map<String, String> map = new HashMap<>();
        map.put("userid", userId);
        String body = HttpUtil.createPost(getDetails + "?access_token=" + getToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(body);
        if(!Constants.OK.equals(object.get("errmsg").toString())) {
            log.error("钉工牌详情接口异常码:" + object.get("errmsg").toString());
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "钉工牌详情接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(object.get("result").toString());
        return jsonObject.get("job_number").toString();
    }

    /**
     * 钉工牌消息通知
     */
    public void asyncsendV2(String userId, 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", agentId);
        map.put("msg", msgVo);
        map.put("userid_list", userId);
        String body = HttpUtil.createPost(asyncsendV2 + "?access_token=" + getToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(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());
        }

    }

    /**
     * 梯控二维码回调
     */
    @PostMapping("/qRCodeUrl")
    public AjaxResult qRCodeUrl(@RequestBody EwmInfo info) {
        // 钉工牌二维码校验
        LadderControlVo controlVo = new LadderControlVo();
        info.setQRdata(info.getQrCode());
        if(info.getQRdata().contains("dingbadge")) {
            LadderControlVo control = dingTalkLadderEwm(info);
            controlVo.setDeviceKey(info.getDeviceKey());
            controlVo.setList(control.getList());
            // 保存记录
            saveLadderRecord(control, info);
            log.info("梯控二维码回调：" + success(controlVo));
            return success(controlVo);
        }
        String bigtype = equipmentService.queryDeviceSequence(info.getDeviceKey());
        if(!"3".equals(bigtype)) {
            throw new ServiceException(10001, "无效二维码");
        }
        // 访客
        LadderControlVo control = visitorLadderEwm(info);
        controlVo.setDeviceKey(info.getDeviceKey());
        controlVo.setList(control.getList());
        saveRecord(control, info);
        log.info("梯控二维码回调：" + success(controlVo));
        return success(controlVo);
    }

    /**
     * 钉工牌梯控规则
     */
    private LadderControlVo dingTalkLadderEwm(EwmInfo info) {
        // 校验二维码
        DingtalkCode code = deCode(info);
        if("invalidPayCode".equals(code.getCode())) {
            throw new ServiceException(10001, "无效二维码");
        }

        if(StringUtils.isNotEmpty(code.getCode())) {
            throw new ServiceException(10002, "二维码过期");
        }

        // 获取钉工牌工号校验是否有权限通过
        String details = getDetails(code.getUserId());
        SysPeople people = new SysPeople();
        people.setGh(details);
        people.setSequence(info.getDeviceKey());
        EmpowerManageVo manageVo = empowerManageService.queryEmpowerRecordInfo(people);
        if (manageVo == null) {
            throw new ServiceException(10003, Constants.DISPLAY_MOD_CONTENT);
        }

        // 查询梯控规则
        TLadderRule tLadderRule = empowerManageService.queryLadderRuleInfo(manageVo.getLadderRuleId());

        // 获取楼层数据
        List<StoreyInfoVo> list = empowerManageService.queryStoreyInfo(Arrays.asList(tLadderRule.getPointId().split(",")));
        LadderControlVo controlVo = new LadderControlVo();
        controlVo.setList(list.stream().map(StoreyInfoVo::getStorey).collect(Collectors.toList()));
        controlVo.setGh(details);
        return controlVo;

    }

    /**
     * 访客梯控规则
     */
    private LadderControlVo visitorLadderEwm(EwmInfo info) {
        CheckCodeVo codeVo = visitorService.queryVisCheckCodeById(info.getQRdata());
        if(codeVo == null || !codeVo.getCode().contains("/pages/visitor/visitor/visExamineEwm")) {
            throw new ServiceException("无效验证码");
        }

        String[] ids = codeVo.getCode().split("id=");
        String[] split = ids[1].split("&time=");
        SysPeople people = new SysPeople();
        people.setSequence(info.getDeviceKey());
        people.setId(Long.valueOf(split[0]));
        Visitor visitor = visitorService.selectVisitorInfo(people);
        if (visitor == null) {
            throw new ServiceException(10003, Constants.DISPLAY_MOD_CONTENT);
        }

        if(visitor.getEndTime().getTime() < new Date().getTime()) {
            throw new ServiceException(10002, "二维码过期");
        }

        // 查询梯控规则
        TLadderRule tLadderRule = empowerManageService.queryLadderRuleInfo(visitor.getLadderRuleId());

        // 获取楼层数据
        List<StoreyInfoVo> list = empowerManageService.queryStoreyInfo(Arrays.asList(tLadderRule.getPointId().split(",")));
        LadderControlVo controlVo = new LadderControlVo();
        controlVo.setList(list.stream().map(StoreyInfoVo::getStorey).collect(Collectors.toList()));
        controlVo.setPeopleId(split[0]);
        return controlVo;
    }

    /**
     * 保存记录
     */
    private void saveRecord(LadderControlVo control, EwmInfo info) {
        VisitorRecordVo record = new VisitorRecordVo();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(control.getPeopleId())) {
            if(visitorService.queryVisitorRecord(Long.valueOf(control.getPeopleId())) > 0) {
                record.setEndTime(new Date());
                record.setVisitorId(control.getPeopleId());
                visitorService.updateVisitorRecord(record);
            }
        }

        record.setVisitorId(control.getPeopleId());
        record.setSequence(info.getDeviceKey());
        record.setStartTime(new Date());
        visitorService.saveVisitorRecord(record);
    }

    /**
     * 保存记录
     */
    private void saveLadderRecord(LadderControlVo control, EwmInfo info) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LadderRecordVo recordVo =  new LadderRecordVo();
        recordVo.setGh(control.getGh());
        recordVo.setDeviceKey(info.getDeviceKey());
        recordVo.setIdentifyType(Constants.TWO);
        recordVo.setIdentifyTime(dateFormat.format(new Date()));
        empowerManageService.saveLadderRecord(recordVo);
    }



    /**
     * 保存梯口识别记录
     */
    @PostMapping("/saveLadderRecord")
    public AjaxResult saveLadderRecord(@RequestBody LadderRecordVo recordVo) throws ParseException {
        log.info("保存梯口识别记录接口:" + recordVo);
        recordVo.setIdentifyType(Constants.ONE);
        empowerManageService.saveLadderRecord(recordVo);
        String equipmentId = peopleRecordService.selectPeopleRecordById(recordVo.getDeviceKey());
        String peopleId = peopleService.selectPeopleById(recordVo.getCard());
        SysPeopleRecord sysPeopleRecord = new SysPeopleRecord();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date parse = sf.parse("2024年02月26日 11:14:08");
        sysPeopleRecord.setShowDate(parse);
        sysPeopleRecord.setDeviceNo(recordVo.getDeviceKey());
        sysPeopleRecord.setRecMode("2");
        sysPeopleRecord.setCardNo(recordVo.getCard());
        sysPeopleRecord.setEquipmentId(StringUtils.isEmpty(equipmentId) ? "" : equipmentId);
        sysPeopleRecord.setPeopleId(StringUtils.isEmpty(peopleId) ? "" : peopleId);
        peopleRecordService.insertSysPeopleRecord(sysPeopleRecord);
        return success();
    }



    @PostMapping("/uploadMiddling")
    public AjaxResult uploadMiddling(@RequestBody JSONObject event) {
        System.out.println("======通行回调信息============="+event);
        String studentJson = JSON.toJSONString(event.get("peopleRecord"));
        SysPeopleRecord peopleRecord = JSON.parseObject(studentJson,SysPeopleRecord.class);
        //根据guId查找上级平台的人员ID
        SysPeople people=new SysPeople();
        people.setGuid(peopleRecord.getAdmitGuid());
        SysPeople peoples=peopleService.selectByGuid(people);
        if(peoples!=null){
            peopleRecord.setPeopleId(peoples.getId()+"");
        }else{
            peopleRecord.setPeopleId(null);
        }
        peopleRecordService.insertSysPeopleRecord(peopleRecord);
        return success(event);
    }

    @PostMapping("/saveVisitorAuditing")
    public AjaxResult saveVisitorAuditing(@RequestBody Visitor visitor) {
        log.info("修改访客信息：{}", visitor);
        VisVisitorExamine examine=visitor.getExamine();
        Visitor item=new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList=visitorService.selectVisitorItemList(item);

        visitor.setItemList(itemList);
        if("0".equals(examine.getExamine())){//审核通过
            //判断是否存在黑名单，存在即审核失败
            SysBlackList sysBlackList=new SysBlackList();
            sysBlackList.setPhone(visitor.getPhone());
            List<SysBlackList> list=sysBlackListService.selectSysBlackListList(sysBlackList);
            if(list.size()>0){
                return AjaxResult.error("存在黑名单无法审核通过");
            }
            for(Visitor items:itemList){
                SysBlackList sysBlackLists=new SysBlackList();
                sysBlackLists.setPhone(items.getPhone());
                List<SysBlackList> lists=sysBlackListService.selectSysBlackListList(sysBlackLists);
                if(lists.size()>0){
                    return AjaxResult.error("存在黑名单无法审核通过");
                }
            }

            Visitor visitor1 = visitorService.selectVisitorById(visitor.getId());
            CheckCodeVo codeVo = new CheckCodeVo();
            codeVo.setCode(qdUrl+visitor.getId() + "&time=" + new Date().getTime());
            codeVo.setVisitorId(String.valueOf(visitor.getId()));
            codeVo.setId(UUID.randomUUID().toString().replace("-", ""));
            if(StringUtils.isNotEmpty(visitor.getCheckCodeId())) {
                codeVo.setId(visitor.getCheckCodeId());
            }
            if(visitor1 != null) {
                codeVo.setStartTime(visitor1.getStartTime());
                codeVo.setEndTime(visitor1.getEndTime());
            }
            visitorService.saveVisCheckCode(codeVo);
        }

        Visitor visitor1 = new Visitor();
        visitor1.setId(visitor.getId());
        visitor1.setType("1");
        visitorService.updateVisitor(visitor1);


        examine.setVisitorId(visitor.getId());
        LoginUser user= SecurityUtils.getLoginUser();
        visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
        examine.setCreateBy(visitor.getUserName());
        return success(visVisitorExamineService.insertVisVisitorExamine(examine));
    }


    @PostMapping("/updateState")
    public AjaxResult updateState(@RequestBody Visitor visitor) {
        return success(visitorService.updateState(visitor));
    }

    /**
     * 修改总部签离状态
     * @param visitor
     * @return
     */
    @PostMapping("/updateGroupSignOut")
    public AjaxResult updateGroupSignOut(@RequestBody Visitor visitor) {
        return success(visitorService.updateSignOut(visitor));
    }

    /**
     * 修改园区签离状态
     * @param visitor
     * @return
     */
    @PostMapping("/updateParkSignOut")
    public AjaxResult updateParkSignOut(@RequestBody Visitor visitor) {
        return success(visitorService.updateSignOut(visitor));
    }

    /**
     * 通行二维码识别
     * @param info
     * @return
     */
    @PostMapping("/equipmentQrCodeUrl")
    public AjaxResult equipmentQrCodeUrl(@RequestBody EwmInfo info) {
        // 钉工牌二维码校验
        LadderControlVo controlVo = new LadderControlVo();
        info.setQRdata(info.getQrCode());
        if(info.getQRdata().contains("dingbadge")) {
            String gh = dingTalkEquipmentEwm(info);
            controlVo.setDeviceKey(info.getDeviceKey());
            List<String> list = new ArrayList<>();
            list.add("1");
            controlVo.setList(list);
            // 保存记录
            SysPeople people = new SysPeople();
            people.setGh(gh);
            savePeopleRecord(people, info.getDeviceKey());
            log.info("通行二维码回调：" + success(controlVo));
            return success(controlVo);
        }
        return success();
    }

    /**
     * 钉钉通行规则
     */
    private String dingTalkEquipmentEwm(EwmInfo info) {
        // 校验二维码
        DingtalkCode code = deCode(info);
        if("invalidPayCode".equals(code.getCode())) {
            throw new ServiceException(10001, "无效二维码");
        }

        if(StringUtils.isNotEmpty(code.getCode())) {
            throw new ServiceException(10002, "二维码过期");
        }

        // 获取钉工牌工号校验是否有权限通过
        String details = getDetails(code.getUserId());
        SysPeople people = new SysPeople();
        people.setGh(details);
        people.setSequence(info.getDeviceKey());
        List<SysEmpowerRecord> list = equipmentService.queryEmpowerRecord(people);
        if(CollectionUtils.isEmpty(list)) {
            throw new ServiceException(10003, "您未授权");
        }
        return details;
    }

    /**
     * 保存通行授权记录url
     * @param recordVo
     * @return
     */
    @PostMapping("/saveTrafficRecords")
    public AjaxResult saveTrafficRecords(@RequestBody LadderRecordVo recordVo) {
        SysPeople people = new SysPeople();
        people.setDoorNo(recordVo.getCard());
        savePeopleRecord(people, recordVo.getDeviceKey());
        return success();
    }

    /**
     * 保存通行授权记录
     * @param sysPeople
     * @param sequence
     */
    private void savePeopleRecord(SysPeople sysPeople, String sequence) {
        SysPeople people = equipmentService.queryPeople(sysPeople);
        SysEquipment equipment = equipmentService.queryEmpower(sequence);

        if(people != null && equipment != null) {
            SysPeopleRecord peopleRecord = new SysPeopleRecord();
            peopleRecord.setDeviceName(equipment.getName());
            peopleRecord.setRecMode("8");
            peopleRecord.setCardNo(people.getDoorNo());
            peopleRecord.setDeviceName(equipment.getName());
            peopleRecord.setRecType("1");
            peopleRecord.setTimestamp(new Date().getTime());
            peopleRecord.setEquipmentId(String.valueOf(equipment.getId()));
            peopleRecord.setPeopleId(String.valueOf(people.getId()));
            peopleRecordService.insertSysPeopleRecord(peopleRecord);
       }
    }



}
