package com.yx.face.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yx.face.boot.config.TaskPoolConfig;
import com.yx.face.boot.core.SnowflakeIdWorker;
import com.yx.face.boot.uitls.DateUtils;
import com.yx.face.boot.uitls.FileUploadUtil;
import com.yx.face.boot.uitls.JsonUtils;
import com.yx.face.boot.uitls.RedisUtil;
import com.yx.face.dao.*;
import com.yx.face.model.dto.FacePassDTO;
import com.yx.face.model.entity.*;
import com.yx.face.model.vo.SystemLongTermDocumentsVO;
import com.yx.face.netty_client.NettyClient;
import com.yx.face.service.FaceTBService;
//import com.yx.face.service.SuKangMaAipService;
import com.yx.face.service.UserControlEarlyWarningListService;
import com.yx.face.service.feign.TBDeviceFaceService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.Column;
import java.util.*;
import java.util.stream.Collectors;

import static org.apache.coyote.http11.Constants.a;

/**
 * @description: FaceTBServiceImpl <br>
 * @date: 2021/6/3 10:40 <br>
 * @author: PWB <br>
 */
@Slf4j
@Service
public class FaceTBServiceImpl implements FaceTBService {
    @Resource
    private FacePassDao facePassDao;
    @Resource
    private FaceDeviceDao faceDeviceDao;
    @Resource
    private FaceRequestLogDao faceRequestLogDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private FaceLogDao faceLogDao;
    //    @Resource
//    private SystemConfigDao systemConfigDao;
    @Resource
    private SystemLongTermDocumentsDao systemLongTermDocumentsDao;
    @Autowired
    private AsyncTriggerRetryImpl asyncTriggerRetry;
    @Resource
    private FaceTaskDao faceTaskDao;
    @Autowired
    private TBDeviceFaceService tbDeviceFaceService;

    @Autowired
    private UserControlEarlyWarningListService userControlEarlyWarningListService;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${web.address}")
    private String address;
//
//    @Autowired
//    private NettyClient nettyClient;

//    @Autowired
//    private TaskPoolConfig taskPoolConfig;

    @Override
    public Boolean downFace(Long userId, Date startTime, Date endTime, Integer adminId) {
        List<FaceDevice> snList = faceDeviceDao.getSnList(adminId);
        if (CollectionUtils.isEmpty(snList)) {
            return true;
        }
        UserInfo userInfo = userInfoDao.selectByPrimaryKey(userId);
        Map<String, Object> result;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(1);
        Map<String, Object> dataItem = Maps.newHashMapWithExpectedSize(8);
        FaceRequestLog requestLog;
        Date now = new Date();
        FacePass facePass;
        for (FaceDevice device : snList) {
       /*     facePassId = facePassDao.getFacePassIdBySn(device.getSn(), userId);
            if (facePassId != null) {
                continue;
            }*/
            facePass = new FacePass();
            facePass.setUserId(userId);
            facePass.setDeviceSn(device.getSn());
            facePass.setDeviceId(device.getId());
            facePass.setStartTime(startTime);
            facePass.setEndTime(endTime);
            facePass.setStatus(2);
            facePass.setType(3);
            facePass.setTaskId(String.valueOf(SnowflakeIdWorker.getSnowId()));
            facePass.setUpdateTime(now);
            facePass.setCreateTime(now);
            facePassDao.insertSelective(facePass);
            dataItem.put("pin", userId);
            dataItem.put("name", userInfo.getUsername());
            dataItem.put("validPeriodStart", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, facePass.getStartTime()));
            dataItem.put("validPeriodEnd", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, facePass.getEndTime()));
            dataItem.put("userType", 0);
            dataItem.put("photo", userInfo.getAvatar());
            dataItem.put("rightno", 104);
            dataItem.put("cardid", userInfo.getIdNumber());
            data.add(dataItem);
            params.put("SN", device.getSn());
            params.put("Data", data);
            requestLog = new FaceRequestLog();
            requestLog.setName("下发人脸");
            requestLog.setContext("/downUser");
            requestLog.setParams("");
            requestLog.setStatus(0);
            requestLog.setUsedTime(0L);
            requestLog.setUpdateTime(now);
            requestLog.setCreateTime(now);
            faceRequestLogDao.insertSelective(requestLog);
            params.put("taskId", requestLog.getId());
            result = tbDeviceFaceService.downUser(params);
            log.info("下发人脸downFace = {}", result);
        }
        return true;
    }

    @Override
    public List<FacePassDTO> batchDownFace(List<FacePassDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return dtoList;
        }
        List<FaceDevice> snList = faceDeviceDao.getSnList(null);
        if (CollectionUtils.isEmpty(snList)) {
            return dtoList;
        }
        Map<String, Object> result;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(dtoList.size());
        Map<String, Object> dataItem;
        FaceRequestLog requestLog;
        Date now = new Date();
        for (FaceDevice device : snList) {
            for (FacePassDTO passDTO : dtoList) {
                dataItem = Maps.newHashMapWithExpectedSize(7);
                dataItem.put("pin", passDTO.getUserId());
                dataItem.put("name", passDTO.getUsername());
                dataItem.put("validPeriodStart", passDTO.getStartTime());
                dataItem.put("validPeriodEnd", passDTO.getEndTime());
                dataItem.put("userType", 0);
                dataItem.put("photo", "");
                dataItem.put("rightno", 104);
                data.add(dataItem);
            }
            params.put("SN", device.getSn());
            params.put("Data", data);
            requestLog = new FaceRequestLog();
            requestLog.setName("下发人脸");
            requestLog.setContext("/downUser");
            requestLog.setParams("");
            requestLog.setStatus(0);
            requestLog.setUsedTime(0L);
            requestLog.setUpdateTime(now);
            requestLog.setCreateTime(now);
            faceRequestLogDao.insertSelective(requestLog);
            params.put("taskId", requestLog.getId());
            result = tbDeviceFaceService.downUser(params);
            log.info("下发人脸downFace = {}", result);
        }
        return dtoList;
    }


    @Override
    public Boolean delFace(List<Long> userIds, Integer adminId) {
        List<FaceDevice> snList = faceDeviceDao.getSnList(adminId);
        if (CollectionUtils.isEmpty(snList)) {
            return true;
        }
        boolean userIdsNotEmpty = CollectionUtils.isEmpty(userIds);
        Map<String, Object> result;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(userIds.size());
        Map<String, Object> dataItem;
        FaceRequestLog requestLog;
        Date now = new Date();
        for (FaceDevice device : snList) {
            requestLog = new FaceRequestLog();
            if (userIdsNotEmpty) {
                for (Long userId : userIds) {
                    dataItem = Maps.newHashMapWithExpectedSize(1);
                    dataItem.put("pin", userId);
                    data.add(dataItem);
                }
                params.put("Data", data);
            } else {
                params.put("Data", "all");
            }
            params.put("SN", device.getSn());
            requestLog.setName("删除人员人脸信息");
            requestLog.setContext("/delUser");
            requestLog.setParams("");
            requestLog.setStatus(0);
            requestLog.setUsedTime(0L);
            requestLog.setUpdateTime(now);
            requestLog.setCreateTime(now);
            faceRequestLogDao.insertSelective(requestLog);
            params.put("taskId", requestLog.getId());
            result = tbDeviceFaceService.delUser(params);
            log.info("删除人员人脸信息downFace = {}", result);
        }
        return true;
    }

    @Override
    public Boolean delFaceBySn(String sn, List<Long> userIds, Integer adminId) {
        Integer deviceId = faceDeviceDao.getIdBySn(sn);
        if (deviceId == null) {
            return true;
        }
        Map<String, Object> result;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(userIds.size());
        Map<String, Object> dataItem;
        FaceRequestLog requestLog;
        Date now = new Date();
        requestLog = new FaceRequestLog();
        if (CollectionUtils.isEmpty(userIds)) {
            for (Long userId : userIds) {
                dataItem = Maps.newHashMapWithExpectedSize(1);
                dataItem.put("pin", userId);
                data.add(dataItem);
            }
            params.put("Data", data);
        } else {
            params.put("Data", "all");
        }
        params.put("SN", sn);
        requestLog.setName("删除人员人脸信息");
        requestLog.setContext("/delUser");
        requestLog.setParams("");
        requestLog.setStatus(0);
        requestLog.setUsedTime(0L);
        requestLog.setUpdateTime(now);
        requestLog.setCreateTime(now);
        faceRequestLogDao.insertSelective(requestLog);
        params.put("taskId", requestLog.getId());
        result = tbDeviceFaceService.delUser(params);
        log.info("删除人员人脸信息downFace = {}", result);
        return true;
    }

    /*=============================================【以下为推送】====================================================*/
    @Override
    public Map<String, Object> connect(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        if (dto == null) {
            return result;
        }
        String sn = null;
        String version = null;
        String devIP = null;
        Integer userCount = null;
        Integer swipeCardCount = null;
        if (dto.get("SN") != null) {
            sn = dto.get("SN").toString();
        }
        if (dto.get("version") != null) {
            version = dto.get("version").toString();
        }
        if (dto.get("devIP") != null) {
            devIP = dto.get("devIP").toString();
        }
        if (dto.get("swipeCardCount") != null) {
            swipeCardCount = (Integer) dto.get("swipeCardCount");
        }
        if (dto.get("userCount") != null) {
            userCount = (Integer) dto.get("userCount");
        }
        Integer deviceId = faceDeviceDao.getIdBySn(sn);
        FaceDevice device = new FaceDevice();
        device.setId(deviceId);
        device.setOnline(1);
        device.setPassCount(swipeCardCount);
        device.setUserCount(userCount);
        device.setAppVersion(version);
        device.setInterIp(devIP);
        Date now = new Date();
        device.setUpdateTime(now);
        if (deviceId == null) {
//            device.setSn(sn);
//            device.setEnable(1);
//            device.setCreateTime(now);
//            faceDeviceDao.insertSelective(device);
            return result;
        }
        faceDeviceDao.updateByPrimaryKeySelective(device);
        return result;
    }

    @Override
    public Map<String, Object> disconnect(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        String sn = null;
        if (dto.get("SN") != null) {
            sn = dto.get("SN").toString();
        }
        if (!StringUtils.hasText(sn)) {
            return result;
        }
        Integer deviceId = faceDeviceDao.getIdBySn(sn);
        if (deviceId == null) {
            return result;
        }
        FaceDevice device = new FaceDevice();
        device.setId(deviceId);
        device.setOnline(0);
        device.setUpdateTime(new Date());
        faceDeviceDao.updateByPrimaryKeySelective(device);
        return result;
    }

    @Override
    public Map<String, Object> report(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        if (dto == null) {
            return result;
        }
        String sn = null;
        String version = null;
        String devIP = null;
        Integer userCount = null;
        Integer swipeCardCount = null;
        if (dto.get("SN") != null) {
            sn = dto.get("SN").toString();
        }
        if (!StringUtils.hasText(sn)) {
            return result;
        }
        Map<String, Object> data = (Map<String, Object>) dto.get("data");
        if (CollectionUtils.isEmpty(data)) {
            return result;
        }
        if (data.get("swipeCardCount") != null) {
            swipeCardCount = (Integer) data.get("swipeCardCount");
        }
        if (data.get("userCount") != null) {
            userCount = (Integer) data.get("userCount");
        }
        if (data.get("version") != null) {
            version = data.get("version").toString();
        }

        if (data.get("devIP") != null) {
            devIP = data.get("devIP").toString();
        }
        Integer deviceId = faceDeviceDao.getIdBySn(sn);
        FaceDevice device = new FaceDevice();
        device.setId(deviceId);
        device.setOnline(1);
        device.setPassCount(swipeCardCount);
        device.setUserCount(userCount);
        device.setAppVersion(version);
        device.setInterIp(devIP);
        Date now = new Date();
        device.setUpdateTime(now);
        if (deviceId == null) {
//            device.setSn(sn);
//            device.setEnable(1);
//            device.setCreateTime(now);
//            faceDeviceDao.insertSelective(device);
            return result;
        }
        faceDeviceDao.updateByPrimaryKeySelective(device);
        return result;
    }

    @Override
    public Map<String, Object> eventRecords(Map<String, Object> dto) throws InterruptedException {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        String sn = null;
        if (dto.get("SN") != null) {
            sn = dto.get("SN").toString();
        }
        //判断是否为空
        if (org.apache.commons.lang3.StringUtils.isBlank(sn)) {
            return result;
        }
        String snId = faceDeviceDao.getFaceDeviceOne(sn);
        //sn是否存在
        if (org.apache.commons.lang3.StringUtils.isBlank(snId)) {
            return result;
        }
        Integer action = null;
        String orgid = "";
        if (dto.get("action") != null) {
            action = (Integer) dto.get("action");
        }
        if (dto.get("orgid") != null) {
            orgid = dto.get("orgid").toString();
        }

        List<Map<String, Object>> dataList = (List) dto.get("data");
        log.info("人脸返回内容；=" + dataList + "数据");

        if (CollectionUtils.isEmpty(dataList)) {
            return result;
        }
        Integer recordid;
        String pin;
        String name = "";
        String photo = null;
        String cardid = "";
        String cardIdEx = "";
        Integer verifytype = 0;
        Integer rightno = 104;

        Integer outtype = 0;
        String idCard = "";
        String phone = "";
        //温度
        String extend3 = "";
        String extend1 = "";
        //健康码组装数据
        String extend5 = "";
        //体温是否异常 0 正常 1 异常
        String twStatus = "";
        //健康码状态00 绿码 01 黄码 10 红码
        String jkmStatus = "";
        //健康码状态 0 健康码 1 国康码
        String jkmType = "";
        //阴性 阳性
        String hsStatus = "";
        //疫苗状态 0针 等等依次累加
        String ymStatus = "";
        //行程信息
        String xcInfo = "";

        // * name 姓名
        String sfzName = "";
        //sex 性别
        String sfzSex = "";
        //nation民族
        String sfzNation = "";
        //born出生年月
        String sfzBorn = "";
        //address地址
        String sfzAddress = "";
        //apartment签发机关
        String sfzApartment = "";
        //period有效期限
        String sfzPeriod = "";
        //no身份证号
        String sfzNo = "";
        //country国籍
        String sfzCountry = "";
        //cn_name中文名
        String sfzCnName = "";
        //Idcard_version证件版本
        String sfzIdcardVersion = "";
        //card_type身份证类型
        String sfzCardType = "";
        //photo 身份证照片
        String sfzPhoto = "";

        String verify_score = null;
        FaceLog faceLog;
        Long userId;
        Date logTime;
        long nowL = System.currentTimeMillis();
        Date now = new Date(nowL);
        String faceTime = "";
        for (Map<String, Object> data : dataList) {
            if (data.get("recordid") != null) {
                recordid = (Integer) data.get("recordid");
            } else {
                continue;
            }
            if (data.get("pin") != null) {
                pin = data.get("pin").toString();

            } else {
                continue;
            }
            if (data.get("name") != null) {
                name = data.get("name").toString();
            }
            if (data.get("photo") != null) {
                photo = data.get("photo").toString();
            }
            if (data.get("cardid") != null) {
                cardid = data.get("cardid").toString();
            }
            if (data.get("cardIdEx") != null) {
                cardIdEx = data.get("cardIdEx").toString();
            }
            if (data.get("verifytype") != null) {
                verifytype = (Integer) data.get("verifytype");
            }
            if (data.get("rightno") != null) {
                rightno = (Integer) data.get("rightno");
            }
            if (data.get("time") != null) {
                faceTime = data.get("time").toString();
            }
            if (data.get("outtype") != null) {
                outtype = (Integer) data.get("outtype");
            }
            if (data.get("phone") != null) {
                phone = data.get("phone").toString();
            }
            if (data.get("extend3") != null) {
                extend3 = data.get("extend3").toString();
            }
            if (data.get("extend1") != null) {
                extend1 = data.get("extend1").toString();
            }
            if (data.get("verify_score") != null) {
                verify_score = data.get("verify_score").toString();
            }


            if (data.get("twStatus") != null) {
                twStatus = data.get("twStatus").toString();
            }
            if (data.get("jkmStatus") != null) {
                jkmStatus = data.get("jkmStatus").toString();
            }
            if (data.get("jkmType") != null) {
                jkmType = data.get("jkmType").toString();
            }
            if (data.get("hsStatus") != null) {
                hsStatus = data.get("hsStatus").toString();
                String[] split = hsStatus.split(",");
                hsStatus = split[0];
//                hsStatus = data.get("hsStatus").toString();
//                String[] split = hsStatus.split(",");
//                hsStatus = split[1].trim();

            }
            if (data.get("ymStatus") != null) {
                ymStatus = data.get("ymStatus").toString();
                String[] split = ymStatus.split(";");
                ymStatus = split[0];
//                ymStatus = data.get("ymStatus").toString();
//                String[] split = ymStatus.split(",");
//                ymStatus = split[1];
            }
            if (data.get("xcInfo") != null) {
                xcInfo = data.get("xcInfo").toString();
            }
//            if (verifytype == 2) {
            Map<String, Object> map = (Map<String, Object>) data.get("idCard");
            if (map != null && !map.isEmpty()) {
                log.info("verifytype==2 代表刷身份证解析身份证 ；{}", data.get("idCard"));
                //身份证信息
//                Map<String, Object> map = (Map<String, Object>) data.get("idCard");
                if (map.get("address") != null) {
                    sfzAddress = map.get("address").toString();
                }
                if (map.get("apartment") != null) {
                    sfzApartment = map.get("apartment").toString();
                }
                if (map.get("born") != null) {
                    sfzBorn = map.get("born").toString();
                }
                if (map.get("card_type") != null) {
                    sfzCardType = map.get("card_type").toString();
                }
                if (map.get("cn_name") != null) {
                    sfzCnName = map.get("cn_name").toString();
                }
                if (map.get("country") != null) {
                    sfzCountry = map.get("country").toString();
                }
                if (map.get("idCard_version") != null) {
                    sfzIdcardVersion = map.get("idCard_version").toString();
                }
                if (map.get("name") != null) {
                    sfzName = map.get("name").toString();
                }
                if (map.get("nation") != null) {
                    sfzNation = map.get("nation").toString();
                }
                if (map.get("no") != null) {
                    sfzNo = map.get("no").toString();
                }
                if (map.get("period") != null) {
                    sfzPeriod = map.get("period").toString();
                }
                if (map.get("photo") != null) {
                    sfzPhoto = map.get("photo").toString();
                    if (StringUtils.hasText(sfzPhoto)) {
                        sfzPhoto = buildImage(sfzPhoto, sn + pin);
                    }
                }
                if (map.get("sex") != null) {
                    sfzSex = map.get("sex").toString();
                }
            }

            if (StringUtils.hasText(photo)) {
                photo = buildImage(photo, sn + pin);
            }
            faceLog = new FaceLog();
            if (verifytype == 0) {
                userId = Long.valueOf(pin);
                UserInfo userInfo = userInfoDao.selectByPrimaryKey(userId);
                if(userInfo != null && userInfo.getPhone() !=null) faceLog.setPhone(userInfo.getPhone());
            } else {
                userId = 0L;
            }
            if (verifytype == 0) {
                if (facePassDao.getFacePassBySn(sn, userId, DateUtils.addMinutes(now, -2)) == null) {
                    continue;
                }
                logTime = faceLogDao.getRecent(userId, sn);
                if (logTime != null) {
                    if (DateUtils.addSeconds(logTime, 30).getTime() > nowL) {
                        continue;
                    }
                }
            }

            faceLog.setRecordid(Long.valueOf(recordid));
            faceLog.setAction(action);
            faceLog.setDeviceSn(sn);
            faceLog.setUserId(userId);
            faceLog.setName(name);
            faceLog.setPhoto(photo);
            faceLog.setCardid(cardid);
            faceLog.setCardidex(cardIdEx);
            faceLog.setVerifyType(verifytype);
            faceLog.setRightno(rightno);
            faceLog.setOutType(outtype);
            faceLog.setFaceTime(faceTime);
            faceLog.setOrgid(orgid);
            faceLog.setPhone(phone);
            faceLog.setExtend3(extend3);
            faceLog.setExtend1(extend1);
            faceLog.setExtend5(extend5);
            faceLog.setTwStatus(twStatus);
            faceLog.setJkmStatus(jkmStatus);
            faceLog.setJkmType(jkmType);
            faceLog.setHsStatus(hsStatus);
            faceLog.setYmStatus(ymStatus);
            faceLog.setXcInfo(xcInfo);
            //身份证模块数据
            faceLog.setSfzSex(sfzSex);
            faceLog.setSfzPhoto(sfzPhoto);
            faceLog.setSfzPeriod(sfzPeriod);
            faceLog.setSfzNo(sfzNo);
            faceLog.setSfzNation(sfzNation);
            faceLog.setSfzName(sfzName);
            faceLog.setSfzIdcardVersion(sfzIdcardVersion);
            faceLog.setSfzCountry(sfzCountry);
            faceLog.setSfzCnName(sfzCnName);
            faceLog.setSfzCardType(sfzCardType);
            faceLog.setSfzBorn(sfzBorn);
            faceLog.setSfzApartment(sfzApartment);
            faceLog.setSfzAddress(sfzAddress);
            faceLog.setAdminId(faceDeviceDao.getAdminIdBySn(sn));
            faceLog.setVerifyScore(verify_score);
            faceLog.setCreateTime(now);
            if (verifytype == 0 || verifytype == 2) {
                faceLogDao.insertSelective(faceLog);
                //预警数据插入
                userControlEarlyWarningListService.addWarningInformation(faceLog.getDeviceSn(), faceLog.getCardid(), faceLog.getId());
            }
//            Map<String, String> maps = new HashMap<>(1);
//            maps.put("face-log", JSONObject.toJSONString(faceLog));
//            nettyClient.sendMessage(JSON.toJSONString(maps));

        }
        return result;
    }

    @Override
    public Map<String, Object> pushUsers(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }

    @Override
    public Map<String, Object> delUser(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        if (dto == null) {
            return result;
        }
        String sn = null;
        if (dto.get("SN") != null) {
            sn = dto.get("SN").toString();
        }
        if (!StringUtils.hasText(sn)) {
            return result;
        }
        Object Obj = dto.get("data");
        if (Obj == null) {
            return result;
        }
        List<Map<String, Object>> data = Obj instanceof List ? ((List<Map<String, Object>>) Obj) : null;
        String dataStr;
        if (data == null) {
            dataStr = Obj.toString();
            if ("all".equals(dataStr)) {
                facePassDao.removeFacePassBySn(sn, null);
            }
            return result;
        }
        if (data.isEmpty()) {
            return result;
        }
        for (Map<String, Object> map : data) {
            facePassDao.removeFacePassBySn(sn, (Long) map.get("pin"));
        }
        return result;
    }


    @Override
    public Map<String, Object> pushTaskResult(Map<String, Object> dto) {
        System.out.println(dto+"*************");
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        return result;
    }

    @Override
    public Map<String, Object> getTaskId(Map<String, Object> dto) {
        Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
        result.put("errCode", "00");
        result.put("taskId", SnowflakeIdWorker.getSnowId());
        return result;
    }

    @Override
    public void pushUsersOnline(List<Map<String, String>> list) {
//        for (Map<String, String> map : list) {
//            String taskId = (String) redisUtil.get(map.get("taskId"));
//            if (StringUtils)
//            redisUtil.get()
//            redisUtil.get(map.get("taskId"));
//        }
//
//
//
//
//        //获取员工通道
//        List<FaceDevice> faceDeviceList = faceDeviceDao.selectTypeFaceDev(2);
//        if (faceDeviceList.isEmpty()) {
//            log.info("设备为空===========");
//            return;
//        }
//        //获取员工列表
//        List<SystemLongTermDocumentsVO> systemLongTermDocumentsDaoList = systemLongTermDocumentsDao.getList(42, null);
//        if (faceDeviceList.isEmpty()) {
//            log.info("获取员工列表===========");
//            return;
//        }
//        List<SystemLongTermDocumentsVO> mapList = new ArrayList<>();
//        for (SystemLongTermDocumentsVO vo : systemLongTermDocumentsDaoList) {
//            for (Map<String, String> map : list) {
//                String s = map.get(vo.getIdNumber());
//                if (StringUtils.hasText(s)) {
//                    mapList.add(vo);
//                    break;
//                }
//            }
//        }
//        //取差集
//        List<SystemLongTermDocumentsVO> differenceList = systemLongTermDocumentsDaoList.stream()
//                .filter(item -> !mapList.stream()
//                        .map(e -> e.getIdNumber())
//                        .collect(Collectors.toList())
//                        .contains(item.getIdNumber()))
//                .collect(Collectors.toList());
//        String sn = list.get(0).get("SN");
//        FaceDevice faceDeviceBySn = faceDeviceDao.getFaceDeviceBySn(sn);
//        for (SystemLongTermDocumentsVO vo : differenceList) {
//            faceDeviceList(faceDeviceBySn, vo);
//        }
    }

    @Override
    public Map<String, Object> syncUsers(Map<String, Object> param) {
        log.info("param===========" + param);
        Map map = new HashMap();
        ArrayList<Map<String, Object>> objects = new ArrayList<>();
        Integer taskId = (Integer) param.get("taskId");
        if ((taskId != null && "123456789".equals(taskId.toString()))||((taskId != null && "987654321".equals(taskId.toString())))) {
            String string = (String) redisUtil.get(taskId.toString());
            List<SystemLongTermDocuments> list = JSON.parseArray(string, SystemLongTermDocuments.class);
            if (list!= null && !list.isEmpty()) {
                for (SystemLongTermDocuments documents : list) {
                    Map<String, Object> dataItem = Maps.newHashMapWithExpectedSize(8);
                    // 下发参数
                    dataItem.put("pin", documents.getJdyId());
                    dataItem.put("name", documents.getName());
                    dataItem.put("validPeriodStart", DateUtil.format(documents.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                    dataItem.put("validPeriodEnd", DateUtil.format(documents.getExpireTime(), "yyyy-MM-dd HH:mm:ss"));
                    dataItem.put("userType", 0);
                    dataItem.put("photo", documents.getPhoto());
                    dataItem.put("rightno", 105);
                    dataItem.put("cardid", documents.getIdNumber());
                    objects.add(dataItem);
                }
            }
        }
        String sn = (String) param.get("SN");
        systemLongTermDocumentsDao.updateListSn(sn);
//        redisUtil.delete(taskId.toString());
        map.put("errCode", "00");
        map.put("totalNum", "3");
        map.put("updateTime", "11");
        map.put("data", objects);
        return map;
    }


    @Async
    public void faceDeviceList(FaceDevice faceDevice, SystemLongTermDocumentsVO vo) {
        //天波人脸服务请求日志表
        FaceRequestLog requestLog;
        Date now = new Date();
        //人脸下发表
        FacePass facePass;
        //唯一id
        Long faceTaskId;
        //人脸清除定时任务
        FaceTask faceTask;
        //人脸下发到设备里面
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(1);
        Map<String, Object> dataItem = Maps.newHashMapWithExpectedSize(8);
        // 下发参数
        dataItem.put("pin", vo.getCardNo());
        dataItem.put("name", vo.getName());
        dataItem.put("validPeriodStart", DateUtil.format(vo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        dataItem.put("validPeriodEnd", DateUtil.format(vo.getExpireTime(), "yyyy-MM-dd HH:mm:ss"));
        dataItem.put("userType", 0);
        dataItem.put("photo", vo.getPhoto());
        dataItem.put("rightno", 105);
        dataItem.put("cardid", vo.getIdNumber());
        data.add(dataItem);
        params.put("SN", faceDevice.getSn());
        params.put("Data", data);
        //天波人脸服务请求日志表
        requestLog = new FaceRequestLog();
        requestLog.setName("下发人脸");
        requestLog.setContext("/downUser");
        requestLog.setParams(JSONObject.toJSONString(params));
        requestLog.setStatus(1);
        requestLog.setUsedTime(0L);
        requestLog.setUpdateTime(now);
        requestLog.setCreateTime(now);
        //人脸下发记录表
        faceRequestLogDao.insertSelective(requestLog);
        params.put("taskId", requestLog.getId());
        //人脸下发表
        facePass = new FacePass();
        facePass.setUserId(Long.valueOf(vo.getCardNo()));
        facePass.setDeviceSn(faceDevice.getSn());
        facePass.setDeviceId(faceDevice.getId());
        facePass.setStartTime(vo.getCreateTime());
        facePass.setEndTime(vo.getExpireTime());
        facePass.setAdminId(vo.getAdminId());
        facePass.setStatus(2);
        facePass.setType(2);
        facePass.setTaskId(vo.getAdminId().toString());
        facePass.setUpdateTime(now);
        facePass.setCreateTime(now);
        //人脸下发
        facePassDao.insertSelective(facePass);
        //数据同步
        asyncTriggerRetry.send(params, facePass);

        faceTaskId = faceTaskDao.getFaceTaskId(faceDevice.getSn(), Long.valueOf(vo.getCardNo()));
        faceTask = new FaceTask();
        faceTask.setId(faceTaskId);
        faceTask.setTaskTime(facePass.getEndTime());
        faceTask.setStatus(0);
        faceTask.setUpdateTime(now);
        if (faceTaskId == null) {
            faceTask.setDeviceSn(faceDevice.getSn());
            faceTask.setUserId(Long.valueOf(vo.getCardNo()));
            faceTask.setCreateTime(now);
            faceTaskDao.insertSelective(faceTask);
        }
        faceTaskDao.updateByPrimaryKeySelective(faceTask);

    }

    private String buildImage(String image, String phone) {
        String path = null;
        if (StringUtils.hasText(image)) {
            long l = System.currentTimeMillis();
            String name = l + UUID.randomUUID().toString().concat(".png");
            path = FileUploadUtil.uploadUtil(image, name);
            return path;
        }
        return path;
    }

}
