package com.yx.face.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.yx.face.boot.restful.RestDTO;
import com.yx.face.boot.restful.ServiceException;
import com.yx.face.boot.uitls.*;
import com.yx.face.dao.*;
import com.yx.face.model.dto.FaceDeviceDTO;
import com.yx.face.model.entity.Admin;
import com.yx.face.model.entity.FaceDevice;
import com.yx.face.model.entity.FaceDeviceLogo;
import com.yx.face.model.entity.FaceRequestLog;
import com.yx.face.model.excel.FaceLogVoExcel;
import com.yx.face.model.excel.UploadExcel;
import com.yx.face.model.excel.UserWhitelistExcel;
import com.yx.face.model.query.FaceServerLogQu;
import com.yx.face.model.query.QueryUser;
import com.yx.face.model.search.FaceDeviceSearch;
import com.yx.face.model.search.FaceServerLogSearch;
import com.yx.face.model.vo.*;
import com.yx.face.service.AdminService;
import com.yx.face.service.FaceService;
import com.yx.face.service.TbDeviceWhiteListService;
import com.yx.face.service.feign.TBDeviceFaceService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: FaceServiceImpl <br>
 * @date: 2021/6/2 14:49 <br>
 * @author: PWB <br>
 */

@Slf4j
@Service
public class FaceServiceImpl implements FaceService {

    @Value("${face.service.tb}")
    private String ip;

    @Resource
    private FacePassDao facePassDao;
    @Resource
    private FaceDeviceDao faceDeviceDao;
    @Resource
    private FaceLogDao faceLogDao;
    @Resource
    private FaceRequestLogDao faceRequestLogDao;
    @Autowired
    private TBDeviceFaceService tbDeviceFaceService;
    @Autowired
    private AdminService adminService;
    @Resource
    private FaceDeviceLogoDao faceDeviceLogoDao;
    @Resource
    private SystemConfigDao systemConfigDao;
    @Resource
    private TbDeviceWhiteListService tbDeviceWhiteListService;

    @Override
    public Boolean authFaceDevice(Integer deviceId) {
        FaceDevice faceDevice = faceDeviceDao.selectByPrimaryKey(deviceId);
        if (faceDevice == null) {
            throw new ServiceException("无此设备");
        }
        FaceDevice device = new FaceDevice();
        device.setId(deviceId);
        device.setAuth(1);
        device.setUpdateTime(new Date());
        Boolean aBoolean = tbDeviceWhiteListService.addOrDeleteTbDeviceWhiteList(faceDevice.getSn(), "00");
        if (aBoolean) {
            return faceDeviceDao.updateByPrimaryKeySelective(device) == 1;
        }
        return aBoolean;
    }

    @Override
    public Boolean stopFaceDevice(Integer deviceId) {
        FaceDevice faceDevice = faceDeviceDao.selectByPrimaryKey(deviceId);
        if (faceDevice == null) {
            throw new ServiceException("无此设备");
        }
        FaceDevice device = new FaceDevice();
        device.setId(deviceId);
        device.setAuth(0);
        device.setUpdateTime(new Date());
        Boolean aBoolean = tbDeviceWhiteListService.addOrDeleteTbDeviceWhiteList(faceDevice.getSn(), "01");
        if (aBoolean) {
            return faceDeviceDao.updateByPrimaryKeySelective(device) == 1;
        }
        return aBoolean;
    }

    @Override
    public Boolean addFaceDevice(FaceDeviceDTO deviceDTO) {
        FaceDevice device = faceDeviceDao.getFaceDeviceBySn(deviceDTO.getSn());
        if (device != null) {
            if (!device.getAdminId().equals(0)) {
                if (!device.getAdminId().equals(deviceDTO.getAdminId())) {
                    throw new ServiceException("该设备也绑定别的账号");
                }
            }
            device.setName(deviceDTO.getName());
            device.setEnable(deviceDTO.getEnable());
            device.setAdminId(deviceDTO.getAdminId());
            return faceDeviceDao.updateByPrimaryKeySelective(device) == 1;
        }
        AdminVO info = adminService.getInfo(deviceDTO.getAdminId());
        if (info.getType() != 5) {
            throw new ServiceException("不能将设备添加到区级以外的账号上");
        }


        FaceDevice faceDevice = new FaceDevice();
        // faceDevice.setId();
        faceDevice.setSn(deviceDTO.getSn());
        faceDevice.setName(deviceDTO.getName());
        faceDevice.setEnable(deviceDTO.getEnable());
        faceDevice.setAdminId(deviceDTO.getAdminId());
        faceDevice.setPass(deviceDTO.getPass());
        faceDevice.setRemark(deviceDTO.getRemark());
        Date now = new Date();
        faceDevice.setUpdateTime(now);
        faceDevice.setCreateTime(now);
        return faceDeviceDao.insertSelective(faceDevice) == 1;
    }

    @Override
    public Boolean modifyFaceDevice(FaceDeviceDTO deviceDTO) {
        FaceDevice device = faceDeviceDao.selectByPrimaryKey(deviceDTO.getDeviceId());
        if (device == null) {
            throw new ServiceException("没有发现该设备");
        }
        if (deviceDTO.getSn() != null) {
            device = faceDeviceDao.getFaceDeviceBySn(deviceDTO.getSn());
            if (device != null) {
                if (!device.getId().equals(deviceDTO.getDeviceId())) {
                    throw new ServiceException("也存在该设备");
                }
            }
        }
        FaceDevice faceDevice = new FaceDevice();
        faceDevice.setId(deviceDTO.getDeviceId());
        faceDevice.setSn(deviceDTO.getSn());
        faceDevice.setName(deviceDTO.getName());
        faceDevice.setEnable(deviceDTO.getEnable());
        faceDevice.setPass(deviceDTO.getPass());
        faceDevice.setRemark(deviceDTO.getRemark());
        faceDevice.setUpdateTime(new Date());
        faceDevice.setAdminId(deviceDTO.getAdminId());
        return faceDeviceDao.updateByPrimaryKeySelective(faceDevice) == 1;
    }

    @Override
    public Boolean deleteDevice(Integer deviceId) {
        FaceDevice device = faceDeviceDao.selectByPrimaryKey(deviceId);
        if (device == null) {
            throw new ServiceException("无此数据");
        }
        Boolean aBoolean = tbDeviceWhiteListService.addOrDeleteTbDeviceWhiteList(device.getSn(), "01");
        if (!aBoolean) {
            throw new ServiceException("删除失败");
        }
        FaceRequestLog requestLog = new FaceRequestLog();
        requestLog.setName("删除人员人脸信息");
        requestLog.setContext("/delUser");
        requestLog.setParams("");
        requestLog.setStatus(0);
        requestLog.setUsedTime(0L);
        Date now = new Date();
        requestLog.setUpdateTime(now);
        requestLog.setCreateTime(now);
        faceRequestLogDao.insertSelective(requestLog);
        faceDeviceDao.deleteByPrimaryKey(deviceId);
        Map<String, Object> map = Maps.newHashMap();
        map.put("SN", device.getSn());
        map.put("taskId", requestLog.getId());
        map.put("Data", "all");
        try {
            tbDeviceFaceService.delUser(map);
        } catch (Exception e) {
            log.info("删除人脸异常 {}", e.getMessage());
        }
        return true;
    }

    @Override
    public PageInfo<FaceDeviceVO> getFaceDevices(RestDTO<FaceDeviceSearch> dto) {
        FaceDeviceSearch data = dto.getData();
        AdminVO info = adminService.getInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", info);
        map.put("fde", data);
//        data.setAdminId(info.getAdminId());
//        data.setType(info.getType().intValue());
//        data.setProvinceId(info.getProvinceId());
//        data.setCityId(info.getCityId());
//        data.setAreaId(info.getAreaId());

        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(faceDeviceDao.getFaceDevices(map));
    }

    @Override
    public PageInfo<FacePassVO> getFacePasses(RestDTO<QueryUser> dto) {
        AdminVO info = adminService.getInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", info);
        map.put("query", dto.getData());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<FacePassVO> list = facePassDao.getFacePasses(map);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getPhone() != null)
                list.get(i).setPhone(SMSOrIdCardUtils.hidePhone(list.get(i).getPhone()));
            if (list.get(i).getUsername() != null)
                list.get(i).setUsername(SMSOrIdCardUtils.hideName(list.get(i).getUsername()));
        }
        return new PageInfo<>(list);
    }

    @SneakyThrows
    @Override
    public PageInfo<FaceLogVO> getFaceLogs(RestDTO<FaceServerLogSearch> dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        FaceServerLogSearch data = dto.getData();
        //时间减去8小时
//        if (StringUtils.isNotBlank(data.getEndTime()) && StringUtils.isNotBlank(data.getStartTime())) {
//            String startTime = DateUtils.getReduceEightTime(data.getStartTime());
//            String endTime = DateUtils.getReduceEightTime(data.getEndTime());
//            data.setStartTime(startTime);
//            data.setEndTime(endTime);
//            log.info("startTime;{} ====== endTime;  {}", startTime, endTime);
//        }
//        if (StringUtils.isNotBlank(data.getStartTime()) && StringUtils.isBlank(data.getEndTime())) {
//            String startTime = DateUtils.getReduceEightTime(data.getStartTime());
//            String endTime = DateUtils.getReduceEightTime(data.getEndTime());
//            data.setStartTime(startTime);
//            data.setEndTime(endTime);
//            log.info("startTime;{} ====== endTime;  {}", startTime, endTime);
//        }
        AdminVO info = adminService.getInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", info);
        map.put("query", data);

        /*1.获取所有满足条件的adminId*/
        List<Long> adminIds = adminService.getAdminListSearch(map);
        map.put("adminIds", adminIds);
        /*2.获取所有满足条件的设备编号
         * 注：因为没有设备的相关查询条件所以不需要查询 所有满足条件的设备编号
         * */

        /*3.通过查询回来的id值 插入map中重新查询face_log表 进行单表查询*/
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<FaceLogVO> list = faceLogDao.getFaceLogsNew(map);
        /*4.查询完成之后应当对其中的数据包括进行填入
         *   1.对admin中的数据字段进行填入
         *   2.对face_device中的数据字段进行填入
         * */

        /*4.1 获取所有adminId并把获取相关的admin*/
        List<Long> adminList = list.stream().collect(Collectors.groupingBy(FaceLogVO::getAdminId)).keySet().stream().map(key -> key).collect(Collectors.toList());
        List<AdminVO> adminVOList = adminService.getByAdminlist(adminList);
        Map<Integer, AdminVO> adminVOMap = adminVOList.stream().collect(Collectors.toMap(AdminVO::getAdminId, AdminVO -> AdminVO));


        List<String> snList = list.stream().collect(Collectors.groupingBy(FaceLogVO::getDeviceSn)).keySet().stream().map(key -> key).collect(Collectors.toList());
        List<FaceDeviceVO> faceDeviceVOList = faceDeviceDao.getBySnList(snList);
        Map<String, FaceDeviceVO> faceDeviceVOMap = faceDeviceVOList.stream().collect(Collectors.toMap(FaceDeviceVO::getSn, FaceDeviceVO -> FaceDeviceVO));
//        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
//        List<FaceLogVO> list = faceLogDao.getFaceLogs(map);
        for (FaceLogVO faceLog : list) {
            AdminVO adminVO = adminVOMap.get(faceLog.getAdminId());
            if (Objects.nonNull(adminVO)) {
                faceLog.setUsername(adminVO.getUsername());
            }
            FaceDeviceVO faceDeviceVO = faceDeviceVOMap.get(faceLog.getDeviceSn());
            if (Objects.nonNull(faceDeviceVO)) {
                faceLog.setDeviceName(faceDeviceVO.getName());
                faceLog.setOutType(faceDeviceVO.getPass());
            }

            if (!faceLog.getJkmStatus().equals("01") && !faceLog.getJkmStatus().equals("10")) {
                if (faceLog.getPhone() != null)
                    faceLog.setPhone(SMSOrIdCardUtils.hidePhone(faceLog.getPhone()));
                if (faceLog.getCardid() != null)
                    faceLog.setCardid(SMSOrIdCardUtils.hideIdNumber(faceLog.getCardid()));
            }

            if (faceLog.getName() != null)
                faceLog.setName(faceLog.getName().trim());

            if (StringUtils.isNotBlank(faceLog.getYmStatus())) {
                String[] split = faceLog.getYmStatus().split(",");
                faceLog.setYmStatus(split[1]);
            }
            if (StringUtils.isNotBlank(faceLog.getHsStatus())) {
                String[] split = faceLog.getHsStatus().split(";");
                faceLog.setHsStatus(split[0]);
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public Map<String, Object> queryFaceSuccess(String taskId) {
        Map<String, Object> facePassByTaskId = facePassDao.getFacePassByTaskId(taskId);
        HashMap<String, Object> map = new HashMap<>();
        if (facePassByTaskId != null) {
            FacePassUserInFoVO facePassVO = facePassDao.getUserName((Long) facePassByTaskId.get("userId"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Calendar cal = Calendar.getInstance();
//              map.get("createTime");
//              String s = map.get("createTime").toString().replace("T", " ");
//              String format = sdf.format(facePassVO.getCreateTime());
//              Date parse = sdf.parse(s);
                cal.setTime(facePassVO.getCreateTime());
                cal.add(Calendar.HOUR_OF_DAY, +24);
                Date time = cal.getTime();
                String format = sdf.format(time);
                map.putAll(facePassByTaskId);
                map.put("avatar", facePassVO.getAvatar());
                map.put("username", facePassVO.getUsername());
                map.put("phone", facePassVO.getPhone());
                map.put("idNumber", facePassVO.getIdNumber());
                map.put("createTime", format);
                map.put("status", true);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("数据异常", e.getMessage());
                String format = sdf.format(new Date());
                map.put("avatar", facePassVO.getAvatar());
                map.put("username", facePassVO.getUsername());
                map.put("phone", facePassVO.getPhone());
                map.put("idNumber", facePassVO.getIdNumber());
                map.put("createTime", format);
                map.put("status", true);
                return map;
            }
        } else {
            map.put("status", false);
        }
        return map;
    }

    @Override
    public List<FaceLogVoExcel> getFaceLogsExcel(FaceServerLogSearch data) {
//        //时间减去8小时
//        if (StringUtils.isNotBlank(data.getEndTime()) && StringUtils.isNotBlank(data.getStartTime())) {
//            String startTime = DateUtils.getReduceEightTime(data.getStartTime());
//            String endTime = DateUtils.getReduceEightTime(data.getEndTime());
//            data.setStartTime(startTime);
//            data.setEndTime(endTime);
//            log.info("startTime;{} ====== endTime;  {}", startTime, endTime);
//        }
//        if (StringUtils.isNotBlank(data.getStartTime()) && StringUtils.isBlank(data.getEndTime())) {
//            String startTime = DateUtils.getReduceEightTime(data.getStartTime());
//            String endTime = DateUtils.getReduceEightTime(data.getEndTime());
//            data.setStartTime(startTime);
//            data.setEndTime(endTime);
//            log.info("startTime;{} ====== endTime;  {}", startTime, endTime);
//        }
        AdminVO info = adminService.getInfo();
        if (info.getIsOut() != 1) {
            throw new ServiceException("你没有导出的权限");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", info);
        map.put("query", data);
        List<FaceLogVO> list = faceLogDao.getFaceLogs(map);

        List<FaceLogVoExcel> faceLogs = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            if (info.getIsHideImportant() == 1) {
                if (list.get(i).getPhone() != null)
                    list.get(i).setPhone(SMSOrIdCardUtils.hidePhone(list.get(i).getPhone()));
                if (list.get(i).getCardid() != null)
                    list.get(i).setCardid(SMSOrIdCardUtils.hideIdNumber(list.get(i).getCardid()));
                if (list.get(i).getName() != null)
                    list.get(i).setName(list.get(i).getName().trim());
            }
            FaceLogVO fv = list.get(i);
            FaceLogVoExcel fle = new FaceLogVoExcel();
            fle.setDeviceSn(fv.getDeviceSn() == null ? null : fv.getDeviceSn());
            fle.setDeviceName(fv.getDeviceName() == null ? null : fv.getDeviceName());
            fle.setName(fv.getName() == null ? null : fv.getName());
            fle.setPhoto(fv.getPhoto() == null ? null : fv.getPhoto());
            fle.setCardid(fv.getCardid() == null ? null : fv.getCardid());
            fle.setPhone(fv.getPhone() == null ? null : fv.getPhone());
            if (fv.getJkmStatus() != null) {
                String jkmStatus = fv.getJkmStatus();
                if (jkmStatus.equals("00")) fle.setJkmStatus("绿码");
                else if (jkmStatus.equals("01")) fle.setJkmStatus("黄码");
                else if (jkmStatus.equals("10")) fle.setJkmStatus("红码");
                else {
                    fle.setJkmStatus("未知");
                }
            }

            if (fv.getTwStatus() != null) {
                String twStatus = fv.getTwStatus();
                if (twStatus.equals("0")) fle.setTwStatus("正常");
                else if (twStatus.equals("1")) fle.setTwStatus("异常");
                else {
                    fle.setTwStatus("未知");
                }
            }
            fle.setExtend3(fv.getExtend3() == null ? null : fv.getExtend3());
            fle.setHsStatus(fv.getHsStatus() == null ? null : fv.getHsStatus());
            fle.setXcInfo(fv.getXcInfo() == null ? null : fv.getXcInfo());
            fle.setYmStatus(fv.getYmStatus() == null ? null : fv.getYmStatus());

            if (fv.getOutType() != null) {
                Integer outType = fv.getOutType();
                if (outType == 0) fle.setOutType("通用");
                else if (outType == 1) fle.setOutType("进门");
                else if (outType == 2) fle.setOutType("出门");
                else {
                    fle.setJkmStatus("未知");
                }
            }

            if (fv.getVerifyType() != null) {
                Integer verifyType = fv.getVerifyType();
                if (verifyType == 0) fle.setVerifyType("人脸");
                else if (verifyType == 1) fle.setVerifyType("卡");
                else if (verifyType == 2) fle.setVerifyType("身份证");
                else if (verifyType == 3) fle.setVerifyType("二维码");
                else if (verifyType == 4) fle.setVerifyType("远程");
                else if (verifyType == 6) fle.setVerifyType("IC卡+人脸");
                else {
                    fle.setJkmStatus("未知");
                }
            }

            if (fv.getRightno() != null) {
                Integer rightno = fv.getRightno();
                if (rightno == 106) fle.setRightno("管理员");
                else if (rightno == 105) fle.setRightno("操作员");
                else if (rightno == 104) fle.setRightno("普通员工");
                else if (rightno == 103) fle.setRightno("访客");
                else if (rightno == 102) fle.setRightno("禁止");
                else if (rightno == 101) fle.setRightno("黑名单");
                else {
                    fle.setJkmStatus("未知");
                }
            }
            fle.setCreateTime(fv.getCreateTime());

            faceLogs.add(fle);
        }

        return faceLogs;
    }

    @Override
    public List<FaceDeviceVO> getFaceDeviceList(JSONObject adminId) {
        AdminVO info;
        Map<String, Object> map = new HashMap<>();
        if (adminId != null && !adminId.isEmpty()) {
            info = adminService.getInfo(adminId.getInteger("adminId"));
        } else {
            info = adminService.getInfo();
        }
        map.put("adminVo", info);
        return faceDeviceDao.getFaceDeviceList(map);

    }

    /**
     * 设备 log 上传
     *
     * @param file
     * @param adminId
     * @return
     */
    @Override
    public String addFaceDeviceLogImg(InputStream file, Integer adminId) {
        String path = null;
        //按指定大小把图片进行缩和放（会遵循原图高宽比例）
        //此处把图片压成60*60的缩略图
        try {
            BufferedImage image = Thumbnails.of(file).size(60, 60).asBufferedImage();//变为400*300,遵循原图比例缩或放到400*某个高度
            //输出流
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            String base64 = Base64.encode(stream.toByteArray());
            stream.flush();
            stream.close();
            String name = UUID.randomUUID().toString().concat(".jpg");
            path = FileUploadUtil.uploadLogImgUtil(base64, name);
            //判断logo 是否存在
            FaceDeviceLogo faceDeviceLogo = faceDeviceLogoDao.selectList(adminId);
            if (faceDeviceLogo == null) {
                faceDeviceLogo = new FaceDeviceLogo();
                faceDeviceLogo.setLogoImg(path);
                faceDeviceLogo.setAdminId(adminId);
                faceDeviceLogoDao.insert(faceDeviceLogo);
            } else {
                faceDeviceLogo.setLogoImg(path);
                faceDeviceLogoDao.updateByPrimaryKeySelective(faceDeviceLogo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    @Override
    public Boolean issuedAll(Integer type, Integer adminId, String sn) {
        List<String> list = new ArrayList<>();
        AdminVO info = adminService.getInfo();
        if (info == null) {
            list.add("数据匹配失败未找到此账号");
            throw new ServiceException(list.toString());
        }
        //设备列表
        List<FaceDevice> listSn = faceDeviceDao.selectSnList(type, sn, info.getProvinceId(), adminId);

        FaceDeviceLogo faceDeviceLogo = faceDeviceLogoDao.selectList(info.getAdminId());
        if (faceDeviceLogo == null) {
            list.add("LOGO失效下发失败请重新上传下发");
            throw new ServiceException(list.toString());
        }

        String base64 = FileUploadUtil.downloadFile(faceDeviceLogo.getLogoImg());
        if (StringUtils.isBlank(base64)) {
            list.add("LOGO失效下发失败请重新上传下发");
            throw new ServiceException(list.toString());
        }

        for (FaceDevice faceDevice : listSn) {
            //停用-0|启用-1
            Integer enable = faceDevice.getEnable();
            //离线-0|在线-1
            Integer online = faceDevice.getOnline();
            //未授权-0|已授权-1
            Integer auth = faceDevice.getAuth();
            if (enable == 0 || online == 0 || auth == 0) {
                list.add(faceDevice.getSn() + ":离线未授权停用状态LOGO下发失败请检查设备状态");
                continue;
            } else {
                List<String> stringList = new ArrayList<>();
                stringList.add(faceDevice.getSn());
                JSONObject img = new JSONObject();
                img.put("logo", base64);
                JSONObject json = new JSONObject();
                json.put("SN", stringList);
                json.put("type", "downLogo");
                json.put("taskId", faceDevice.getId());
                json.put("Data", img);
                log.info("log下发参数； {}", json);
                String sync = OkHttpUtils.builder().url(ip + "/Face/sendControl").localPost(json.toJSONString()).sync();
                log.info("log下发返回参数；{}", sync);
                JSONObject jsonObject = JSONObject.parseObject(sync);
                String msg = jsonObject.getString("msg");
                if ("命令下发成功".equals(msg)) {
                    log.info("logo命令下发成功" + jsonObject);
                } else {
                    list.add(faceDevice.getSn() + ":离线未授权停用状态LOGO下发失败请检查设备状态");
                }
            }
        }
        if (!list.isEmpty()) {
            throw new ServiceException(list.toString());
        }
        return true;
    }

    @Override
    public String getLogo(Integer adminId) {
        FaceDeviceLogo faceDeviceLogo = faceDeviceLogoDao.selectList(adminId);
        if (faceDeviceLogo == null) {
            return "";
        }
        return faceDeviceLogo.getLogoImg();
    }

    @Override
    public Boolean doReboot(String sn) {
        FaceDevice faceDeviceBySn = faceDeviceDao.getFaceDeviceBySn(sn);
        if (faceDeviceBySn == null) {
            throw new ServiceException("此设备不存在");
        }
        List<String> sns = new ArrayList<>();
        sns.add(sn);
        Map<String, Object> map = Maps.newHashMap();
        Map<String, Object> data = Maps.newHashMap();
        data.put("rebootType", "2");
        data.put("time", "");
        map.put("SN", sns);
        map.put("taskId", System.currentTimeMillis());
        map.put("type", "reboot");
        map.put("Data", data);
        try {
            Map<String, Object> sendControl = tbDeviceFaceService.sendControl(map);
            log.info("重启设备返回参数；{}", sendControl);
            if (sendControl.isEmpty()) {
                throw new ServiceException("设备重启失败请检查是否离线");
            }
            if (!"00".equals((String) sendControl.get("errCode"))) {
                //设备不在线 重试 3次
//                    Boolean retry = triggerRetry(map);
                throw new ServiceException("设备重启失败请检查是否离线");
            }
        } catch (Exception e) {
            log.info("下发失败 原因 {}", e.getMessage());
            throw new ServiceException("设备重启失败请检查是否离线");
            //设备不在线 重试 3次
//            Boolean retry = triggerRetry(map);
        }
        return true;
    }

    @Override
    public FaceLogVO getDetails(FaceServerLogQu qu, Integer adminId) {
        String pwd = PasswordUtils.buildPw(qu.getPassword());
        if (StringUtils.equals(qu.getPassword(), pwd)) {
            throw new ServiceException("密码有误哦~");
        }
        SystemConfigVO vo = systemConfigDao.sysConfiguration(adminId);
        if (vo == null) {
            throw new ServiceException("未配置此权限哦~");
        }
        if (vo.getStatus() != 1) {
            throw new ServiceException("此权限未开启哦~");
        }
        return faceLogDao.getDetails(qu.getId());
    }

    @Override
    public void uploadExcel(List<Object> datas) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UploadExcel uploadExcel = (UploadExcel) datas.get(i);
            if (StringUtils.isBlank(uploadExcel.getIdNumber()) || StringUtils.isBlank(uploadExcel.getPhoto())) {
                continue;
            }
            URL urlfile = null;
            try {
                urlfile = new URL(uploadExcel.getPhoto());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            byte[] data = null;
            try {
                InputStream inputStream = urlfile.openStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
                swapStream.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                String encode = new BASE64Encoder().encode(data);
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] bytes1 = decoder.decodeBuffer(encode);
                for (int j = 0; j < bytes1.length; ++j) {
                    if (bytes1[j] < 0) {// 调整异常数据
                        bytes1[j] += 256;
                    }
                }
                // 生成jpeg图片
                OutputStream out = new FileOutputStream("D:\\3\\"+uploadExcel.getIdNumber()+"-"+ (int)(Math.random()*100000)+".jpg");
                out.write(bytes1);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //发送失败重试三次

    public Boolean triggerRetry(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        int times = 1;
        while (times <= 3) {
            try {
                Thread.sleep(1000 * 20);   // 休眠20秒
                result = tbDeviceFaceService.downUser(params);
                log.info("下发人脸重试downFace = {} 重试次数 {}", params, times);
                if (result.get("msg") != null) {
                    String msg = result.get("msg").toString();
                    if (msg.contains("不在线")) {
                        times++;
                    } else {
                        //代表成功
                        times = 6;
                    }
                } else {
                    times++;
                }
            } catch (Exception e) {
                times++;
                log.info("下发失败 原因 {}", e.getMessage());
            }
        }
        //成功
        if (times == 6) {
            return true;
        }
        return false;
    }
}
