package com.jpsoft.shinestar.modules.uniview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.utils.LApiUtil;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.constant.LApiConstant;
import com.jpsoft.shinestar.modules.pacs.dto.IsPersonExistVo;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.pacs.dto.PacsResult;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import com.jpsoft.shinestar.modules.uniview.dto.DataServersDTO;
import com.jpsoft.shinestar.modules.uniview.dto.LibDTO;
import com.jpsoft.shinestar.modules.uniview.dto.PersonDateDTO;
import com.jpsoft.shinestar.modules.uniview.dto.ServerAddrDTO;
import com.jpsoft.shinestar.modules.uniview.request.LapiRequest;
import com.jpsoft.shinestar.modules.uniview.service.ILapiService;
import com.jpsoft.shinestar.modules.uniview.vo.LibraryVo;
import io.netty.handler.codec.http.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-3-15 9:37
 */
@Slf4j
@Service
public class LapiServiceImpl implements ILapiService {
    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private LapiRequest lapiRequest;

//    @Autowired
//    private ExecuteFailLogService deleteFailLogService;

    @Autowired
    private SysLogService sysLogService;

    /**
     * 宇视设备局域网http方式支持
     * @param ipAddress
     * @param port
     * @return
     * @throws Exception
     */
    @Override
    public DeviceInfo findByIpAddressAndPort(String ipAddress, String port) throws Exception {
        JSONObject jsonObject = LApiUtil.getRequest(ipAddress + ":" + port + LApiConstant.DEVICEBASICINFO);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setId(UUID.randomUUID().toString());
        deviceInfo.setIpAddress(ipAddress);
        deviceInfo.setPort(port);
        deviceInfo.setIsOnline(true);
        deviceInfo.setDeviceNo(response.getString("SerialNumber"));

        return deviceInfo;
    }

    @Override
    public Boolean keepAlive(String id) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(id);
        if (deviceInfo == null) {
            throw new Exception("设备未绑定");
        }
//        JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.KEEPALIVE);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.KEEPALIVE, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        return true;
    }

    private String getFaceResultDescription(int faceResult) {
        String text = "";

        switch (faceResult) {
            case 0:
                text = "新增成功";
                break;
            case 1000:
                text = "算法初始化失败";
                break;
            case 1001:
                text = "人脸检测失败";
                break;
            case 1002:
                text = "图片未检测到人脸";
                break;
            case 1003:
                text = "jpeg照片解码失败";
                break;
            case 1004:
                text = "图片质量分数不满足";
                break;
            case 1005:
                text = "图片缩放失败;（即图片分辨率不满足要求，请将图片缩放后再下发）";
                break;
            case 1006:
                text = "未启用智能";
                break;
            case 1007:
                text = "导入图片过小";
                break;
            case 1008:
                text = "导入图片过大";
                break;
            case 1009:
                text = "导入图片分辨率超过1920*1080";
                break;
            case 1010:
                text = "导入图片不存在";
                break;
            case 1011:
                text = "人脸元素个数已达到上限";
                break;
            case 1012:
                text = "智能棒算法模型不匹配";
                break;
            case 1013:
                text = "人脸导入库成员证件号非法";
                break;
            case 1014:
                text = "人脸导入库成员图片格式错误";
                break;
            case 1015:
                text = "通道布控已达设备能力上限";
                break;
            case 1016:
                text = "其它客户端正在进行操作人脸库";
                break;
            case 1017:
                text = "人脸库文件正在更新中";
                break;
            case 1018:
                text = "Json反序列化失败";
                break;
            case 1019:
                text = "Base64解码失败";
                break;
            case 1020:
                text = "人脸照片，编码后的大小和实际接收到的长度不一致，关注Data和Size大小是否正确。";
                break;
        }

        return text;
    }

    @Override
    public PacsResult addPersonToDevice(Long id, String deviceId) throws Exception {
        PacsResult pacsResult = new PacsResult();
        DeviceInfo deviceInfo = null;
        PersonInfo personInfo = null;

        Boolean success = false;
        personInfo = personInfoService.get(id);

        if (StringUtils.isEmpty(personInfo.getFaceImageUrl())){
            throw new Exception("照片不存在!");
        }

        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
        String base64Data = OSSUtil.downloadToBase64(personInfo.getFaceImageUrl() + "?x-oss-process=image/resize,h_600");

        deviceInfo = deviceInfoService.get(deviceId);

        HashMap<String, Object> map = new HashMap<>();
        map.put("Num", 1L);
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("PersonID", personInfo.getId());
        map1.put("LastChange", new Date().getTime());
        map1.put("PersonCode", personInfo.getId().toString());
        map1.put("PersonName", personInfo.getName()); // + "_" + personInfo.getId().toString()
        map1.put("Remarks", companyInfo.getName());

        //TimeTemplateNum 首字符必须大写
        map1.put("TimeTemplateNum", 0L);

        map1.put("IdentificationNum", 1L);
        HashMap<String, Object> map2 = new HashMap<>();
        List listMap2 = new ArrayList();
        listMap2.add(map2);
        map2.put("Type", 0L);
        map2.put("Number", personInfo.getIdCard());
        map1.put("IdentificationList", listMap2);

        HashMap<String, Object> map3 = new HashMap<>();

        if (StringUtils.isNotBlank(base64Data)) {
            map1.put("ImageNum", 1L);
            //照片base64长度
            Integer imageSize = base64Data.length();
            map3.put("Name", personInfo.getId() + ".jpg");
            map3.put("Size", imageSize);
            map3.put("Data", base64Data);
            map3.put("FaceID", personInfo.getId());

            //照片字节大小
            Integer fileSize = imageSize - (imageSize / 8) * 2;

            if (fileSize > 512 * 1024 || fileSize < 10 * 1024) {
                throw new Exception("人员照片大小限定为10k~512k");
            }
        } else {
            throw new Exception("照片不存在");
        }

        List listMap3 = new ArrayList();
        listMap3.add(map3);
        map1.put("ImageList", listMap3);
        List listMap1 = new ArrayList();
        listMap1.add(map1);
        map.put("PersonInfoList", listMap1);

        //获取人员人脸库id
        String faceDbId = getFaceDbId(deviceInfo, companyInfo.getName());

        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.PEOPLE_LIBRARIES + faceDbId + "/People", HttpMethod.POST, map);
        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);

        JSONObject faceObject = response
                .getJSONArray("PersonList").getJSONObject(0)
                .getJSONArray("FaceList").getJSONObject(0);

        int faceResult = faceObject.getInteger("ResultCode");

        if (faceResult == 0) {
            success = isSuccessAddPerson(personInfo, deviceInfo, faceDbId);
            pacsResult.setSuccess(success);
        } else {
            log.error("由于图片保存失败，删除人员信息,PersonID={}", id);
            deletePersonFromDevice(id,deviceId);

            pacsResult.setMsg(deviceInfo.getAliasName() + ":" + getFaceResultDescription(faceResult));
            pacsResult.setSuccess(false);
        }

        return pacsResult;
    }

    @Override
    public String getFaceDbId(DeviceInfo deviceInfo, String companyName) throws Exception {
//        if (StringUtils.isBlank(companyName)) {
//            throw new Exception("公司名称为空");
//        }
        String faceDbId = "";

        //JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.GETFACEDB);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.GETFACEDB, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        List listData = response.getJSONArray("LibList");
        if (listData.size() > 0) {
            for (int i = 0; i < listData.size(); i++) {
                JSONObject jsonObject1 = (JSONObject) JSONArray.toJSON(listData.get(i));
                String name = jsonObject1.getString("Name");

                if (StringUtils.isNotBlank(name) && name.equals(companyName)) {
                    faceDbId = jsonObject1.getString("ID");
                    break;
                }
            }
            //人员所属的公司库不存在，保存到默认库
            if (StringUtils.isBlank(faceDbId)) {
                for (int i = 0; i < listData.size(); i++) {
                    JSONObject jsonObject1 = (JSONObject) JSONArray.toJSON(listData.get(i));
                    String name = jsonObject1.getString("Name");
                    if ("默认员工库".equals(name)) {
                        faceDbId = jsonObject1.getString("ID");
                        break;
                    }
                }
                if (StringUtils.isBlank(faceDbId)) {
                    faceDbId = getDefaultLib(deviceInfo.getId());
                }


            }
        } else {
            faceDbId = getDefaultLib(deviceInfo.getId());
        }

        return faceDbId;
    }

    public Boolean isExistFaceDbId(DeviceInfo deviceInfo, String companyName) throws Exception {
        if (StringUtils.isBlank(companyName)) {
            throw new Exception("公司名称为空");
        }
        String faceDbId = "";
//        JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.GETFACEDB);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.GETFACEDB, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        List listData = response.getJSONArray("LibList");
        if (listData.size() <= 0) {
            //
            return false;
        }
        for (int i = 0; i < listData.size(); i++) {
            JSONObject jsonObject1 = (JSONObject) JSONArray.toJSON(listData.get(i));
            String name = jsonObject1.getString("Name");
            if (StringUtils.isNotBlank(name) && companyName.equals(name)) {
                return true;
            }
        }
        return false;


    }

    @Override
    public PacsMsgResult deletePersonFromDevice(Long id, String deviceId) throws Exception {
        if (StringUtils.isBlank(deviceId)) {
            throw new Exception("相关设备不能为空");
        }

        PersonInfo personInfo = personInfoService.getIgnoreDelFlag(id);

        if (personInfo == null) {
            throw new Exception("人员信息不存在");
        }

        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
        if (companyInfo == null) {
            throw new Exception("人员没有相应公司");
        }

        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

        PacsMsgResult pacsMsgResult = new PacsMsgResult();
        pacsMsgResult.setPersonId(id);
        pacsMsgResult.setDeviceId(deviceId);
        pacsMsgResult.setPersonName(personInfo.getName());
        pacsMsgResult.setAliasName(deviceInfo.getAliasName());

        String faceDbId = getFaceDbId(deviceInfo, companyInfo.getName());

        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(),
                LApiConstant.DELETEPERSON + faceDbId + "/People/" + personInfo.getId(), HttpMethod.DELETE, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");

        if (dataJson.getInteger("ResponseCode") == 0 && dataJson.getInteger("StatusCode") == 0) {
            pacsMsgResult.setSuccess(true);
        } else {
            pacsMsgResult.setSuccess(false);
            pacsMsgResult.setMsg("状态码:" + dataJson.getInteger("StatusCode"));
        }

        return pacsMsgResult;
    }

    @Override
    public PacsMsgResult remoteOpen(String deviceInfoId) throws Exception {
        PacsMsgResult msgResult = new PacsMsgResult();

        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (deviceInfo.getDelFlag()) {
            throw new Exception("设备已删除");
        }

//      JSONObject jsonObject = LApiUtil.putRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.REMOTEOPENED);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.REMOTEOPENED, HttpMethod.PUT, null);
        JSONObject dataJson = jsonObject.getJSONObject("Response");

        JSONObject response = LApiUtil.getResponse(dataJson);

        if ("Succeed".equals(dataJson.getString("StatusString"))) {
            msgResult.setSuccess(true);
        } else {
            msgResult.setMsg(dataJson.getString("ResponseString"));
            msgResult.setSuccess(false);
        }

        return msgResult;
    }

    @Override
    public Boolean reboot(String deviceInfoId) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (deviceInfo.getDelFlag()) {
            throw new Exception("设备已删除");
        }
//        JSONObject jsonObject = LApiUtil.putRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.REBOOT);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.REBOOT, HttpMethod.PUT, null);
        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);

        if (response!=null) {
            return true;
        }
        else{
            return false;
        }
    }

    @Override
    public List<PacsResult> addCompanyLib(String companyInfoId, String deviceInfoIds) throws Exception {
        CompanyInfo companyInfo = companyInfoService.get(companyInfoId);
        if (companyInfo == null) {
            throw new Exception("公司不存在");
        }
        if (StringUtils.isBlank(deviceInfoIds)) {
            throw new Exception("请选择设备");
        }
        List<String> idList = Arrays.asList(deviceInfoIds.split(","));
        List<PacsResult> pacsResultList = new ArrayList<>();
        for (String deviceInfoId : idList) {
            DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
            PacsResult pacsResult = new PacsResult();
            try {
                if (deviceInfo == null) {
                    throw new Exception("设备不存在");
                }
                Boolean isExist = isExistFaceDbId(deviceInfo, companyInfo.getName());
                if (isExist) {
                    throw new Exception("已有人脸库不可重复创建");
                }
                HashMap map = new HashMap();
                map.put("BelongIndex", "");
                map.put("LastChange", new Date().getTime());
                map.put("MemberNum", 0);
                map.put("Name", companyInfo.getName());
                map.put("Type", 3);
                //JSONObject jsonObject = LApiUtil.postRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.ADDLIBRARY, map);
                JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.ADDLIBRARY, HttpMethod.POST, map);

                JSONObject dataJson = jsonObject.getJSONObject("Response");
                JSONObject response = LApiUtil.getResponse(dataJson);
                pacsResult.setMsg("添加成功");
                pacsResult.setSuccess(true);
                HashMap dataMap = new HashMap<>();
                dataMap.put("CompanyId", companyInfoId);
                dataMap.put("CompanyName", companyInfo.getName());
                dataMap.put("deviceId", deviceInfoId);
                dataMap.put("LibraryId", response.getString("ID"));
                pacsResult.setData(dataMap);

            } catch (Exception e) {
                log.error(e.getMessage());
                pacsResult.setMsg(e.getMessage());
                pacsResult.setSuccess(false);
                pacsResult.setData("");
            }

            pacsResultList.add(pacsResult);


        }


        return pacsResultList;
    }

    public String getDefaultLib(String deviceInfoId) throws Exception {

        if (StringUtils.isBlank(deviceInfoId)) {
            throw new Exception("请选择设备");
        }
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        try {
            if (deviceInfo == null) {
                throw new Exception("设备不存在");
            }


            HashMap map = new HashMap();
            map.put("BelongIndex", "");
            map.put("LastChange", new Date().getTime());
            map.put("MemberNum", 0);
            map.put("Name", "默认员工库");
            map.put("Type", 3);
//            JSONObject jsonObject = LApiUtil.postRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.ADDLIBRARY, map);
            JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.ADDLIBRARY, HttpMethod.POST, map);
            JSONObject dataJson = jsonObject.getJSONObject("Response");
            JSONObject response = LApiUtil.getResponse(dataJson);
            return response.getString("ID");

        } catch (Exception e) {
            log.error(e.getMessage());

        }
        return "";
    }

    @Override
    public PacsResult deleteCompanyLib(String deviceInfoId, String libraryId) throws Exception {
        if (StringUtils.isBlank(deviceInfoId)) {
            throw new Exception("设备id为空");
        }
        if (StringUtils.isBlank(libraryId)) {
            throw new Exception("人脸库id为空");
        }
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }

        PacsResult pacsResult = new PacsResult();
        try {
//          JSONObject jsonObject = LApiUtil.deleteRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.DELETELIBRARY + libraryId);
            JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(),
                    LApiConstant.DELETELIBRARY + libraryId, HttpMethod.DELETE, null);

            JSONObject dataJson = jsonObject.getJSONObject("Response");
            JSONObject response = LApiUtil.getResponse(dataJson);
            pacsResult.setSuccess(true);
            pacsResult.setMsg("删除成功");
            pacsResult.setData("");
        } catch (Exception e) {
            pacsResult.setMsg(e.getMessage());
            pacsResult.setSuccess(false);
            pacsResult.setData("");
        }


        return pacsResult;
    }

    @Override
    public PacsResult updateCompanyLib(String companyId, String deviceInfoId, String libraryId) throws Exception {
        if (StringUtils.isBlank(companyId)) {
            throw new Exception("公司id为空");
        }
        CompanyInfo companyInfo = companyInfoService.get(companyId);
        if (companyInfo == null) {
            throw new Exception("公司不存在");
        }
        if (StringUtils.isBlank(deviceInfoId)) {
            throw new Exception("设备id为空");
        }
        if (StringUtils.isBlank(libraryId)) {
            throw new Exception("人脸库id为空");
        }
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        HashMap map = new HashMap();
        map.put("Num", 1);
        List list = new ArrayList();
        HashMap map1 = new HashMap();
        map1.put("ID", libraryId);
        map1.put("LastChange", new Date().getTime());
        map1.put("Name", companyInfo.getName());
        map1.put("Type", 3);
        map1.put("BelongIndex", "");
        list.add(map1);
        map.put("LibList", list);
//        JSONObject jsonObject = LApiUtil.putRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.UPDATALIBRARY, map);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.UPDATALIBRARY, HttpMethod.PUT, map);
        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);

        HashMap dataMap = new HashMap<>();
        dataMap.put("deviceId", deviceInfo.getId());
        dataMap.put("deviceName", deviceInfo.getAliasName());
        PacsResult pacsResult = new PacsResult();
        pacsResult.setSuccess(true);
        pacsResult.setMsg("更新成功");
        pacsResult.setData(dataMap);
        return pacsResult;
    }

    @Override
    public List<PacsResult> deleteDeviceAllCompanyLib(String deviceInfoId) throws Exception {
        if (StringUtils.isBlank(deviceInfoId)) {
            throw new Exception("设备id为空");
        }
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }

        //JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.UPDATALIBRARY);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.UPDATALIBRARY, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        List<LibraryVo> list = JSONObject.parseArray(response.getString("LibList"), LibraryVo.class);
        if (list.size() <= 0) {
            throw new Exception("设备没有配置人员库");
        }
        List<PacsResult> pacsResultList = new ArrayList<>();
        for (LibraryVo libraryVo : list) {
            PacsResult pacsResult = new PacsResult();
            try {
//                JSONObject jsonObject1 = LApiUtil.deleteRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.DELETELIBRARY + libraryVo.getID());
                JSONObject jsonObject1 = lapiRequest.send(deviceInfo.getDeviceNo(),
                        LApiConstant.DELETELIBRARY + libraryVo.getID(), HttpMethod.DELETE, null);

                JSONObject dataJson1 = jsonObject1.getJSONObject("Response");
                JSONObject response1 = LApiUtil.getResponse(dataJson1);
                pacsResult.setSuccess(true);
                pacsResult.setMsg("删除成功");
                pacsResult.setData("");
            } catch (Exception e) {
                pacsResult.setMsg(e.getMessage());
                pacsResult.setSuccess(false);
                pacsResult.setData("");
            }
            pacsResultList.add(pacsResult);
        }


        return pacsResultList;
    }

    @Override
    public Boolean isSuccessAddPerson(PersonInfo personInfo, DeviceInfo deviceInfo, String faceDbId) {
        HashMap map = new HashMap();
        map.put("Num", 1);
        map.put("Limit", 3);
        map.put("Offset", 0);
        List list = new ArrayList();
        HashMap map1 = new HashMap();
        map1.put("QryType", 27);
        map1.put("QryCondition", 0);
        map1.put("QryData", personInfo.getId().toString());
        list.add(map1);
        map.put("QueryInfos", list);
        try {
            //JSONObject jsonObject = LApiUtil.postRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.PEOPLE_LIBRARIES + faceDbId + "/People/Info", map);
            JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.PEOPLE_LIBRARIES + faceDbId + "/People/Info", HttpMethod.POST, map);

            JSONObject dataJson = jsonObject.getJSONObject("Response");
            JSONObject response = LApiUtil.getResponse(dataJson);
            Integer num = response.getInteger("Total");
            if (num > 0) {

                try {
                    personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), true);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                return true;
            } else {
                try {
                    personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), false);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } catch (Exception e) {

            personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), null);
            return false;
        }


        return false;
    }

    @Override
    public Boolean isPersonImageExist(PersonInfo personInfo, DeviceInfo deviceInfo, String faceDbId) {
        HashMap map = new HashMap();
        map.put("Num", 1);
        map.put("Limit", 3);
        map.put("Offset", 0);
        List list = new ArrayList();
        HashMap map1 = new HashMap();
        map1.put("QryType", 27);
        map1.put("QryCondition", 0);
        map1.put("QryData", personInfo.getId().toString());
        list.add(map1);
        map.put("QueryInfos", list);

        try {
            JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.PEOPLE_LIBRARIES + faceDbId + "/People/Info", HttpMethod.POST, map);

            JSONObject dataJson = jsonObject.getJSONObject("Response");
            JSONObject response = LApiUtil.getResponse(dataJson);
            Integer num = response.getInteger("Total");
            if (num > 0) {
                JSONObject personList = response.getJSONObject("PersonList");

                JSONArray personInfoList = personList.getJSONArray("PersonInfoList");
                Map map2 = (Map) personInfoList.get(0);

                Integer imageNum = (Integer) map2.get("ImageNum");
                if (imageNum > 0) {
                    return true;
                }

            }
        } catch (Exception e) {

            return false;
        }


        return false;
    }

    @Override
    public Map<String, Object> getDeviceRule(String deviceInfoId) throws Exception {

        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }
        //JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.RULE);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.RULE, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        return response;
    }

    @Override
    public Boolean setDeviceRule(String deviceInfoId, Integer needCap, Integer needMask,
                                 Integer measureTemperature, Integer type, BigDecimal minTemper, BigDecimal maxTemper,
                                 Integer preAlarmEnabled,BigDecimal preAlarmOffset,BigDecimal alarmThreshold) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("Num", 3);
        List list = new ArrayList();
        //安全帽数据
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("DoorOpenMode", 0);
        map1.put("Mode", 1);
        map1.put("Enabled", needCap);
        //口罩数据
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("DoorOpenMode", 0);
        map2.put("Mode", 2);
        map2.put("Enabled", needMask);
        //测温数据
        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("DoorOpenMode", 0);
        map3.put("Mode", 3);
        map3.put("Enabled", measureTemperature);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        map.put("RuleList", list);

        if (measureTemperature == 1) {
            HashMap<String, Object> temperatureMap = new HashMap<>();
            temperatureMap.put("Type", type);
            temperatureMap.put("Minimum", minTemper);
            temperatureMap.put("Maximum", maxTemper);
            temperatureMap.put("AlarmThreshold", alarmThreshold);
            temperatureMap.put("preAlarmEnabled", preAlarmEnabled);
            temperatureMap.put("preAlarmOffset", preAlarmOffset);

            map.put("TemperatureRule", temperatureMap);
        }

//      JSONObject jsonObject = LApiUtil.putRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.RULE, map);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.RULE, HttpMethod.PUT, map);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);

        return true;
    }

    @Override
    public JSONObject getFaceDetectionRule(String deviceInfoId) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }

        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.FACE_DETECTION_RULE, HttpMethod.GET, null);

        return jsonObject;
    }

    @Override
    public JSONObject setFaceDetectionRule(String deviceInfoId,JSONObject requestBody) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }

        JSONObject responseBody = lapiRequest.sendJson(deviceInfo.getDeviceNo(), LApiConstant.FACE_DETECTION_RULE, HttpMethod.PUT, requestBody);

        return responseBody;
    }

    @Override
    public void updateDeviceServerConfig(DeviceInfo deviceInfo, String newAddress, String newPort) throws Exception {
        try{
            String deviceNo = deviceInfo.getDeviceNo();
            DataServersDTO dataServersDTO = getDeviceDateServer(deviceNo);

            if (dataServersDTO != null) {
                ServerAddrDTO serverAddrDTO = dataServersDTO.getServerAddr();

                if (StringUtils.isNotBlank(newAddress)) {
                    serverAddrDTO.setAddress(newAddress);
                }
                if (StringUtils.isNotBlank(newPort)) {
                    serverAddrDTO.setPort(Integer.valueOf(newPort));
                }

                dataServersDTO.setServerAddr(serverAddrDTO);

                //设置传输协议为V1
                dataServersDTO.setProtocol(1083);
                dataServersDTO.setSubProtocol(2025);

                List<DataServersDTO> dataServersDTOList = new ArrayList<>();
                dataServersDTOList.add(dataServersDTO);
                HashMap<String, Object> map = new HashMap<>();
                map.put("Num", 1);

                map.put("DataServerList", dataServersDTOList);
                JSONObject jsonObject = lapiRequest.send(deviceNo, LApiConstant.DATASERVERS, HttpMethod.PUT, map);
                JSONObject dataJson = jsonObject.getJSONObject("Response");
                JSONObject response = LApiUtil.getResponse(dataJson);

                if (dataJson.getString("ResponseString").equals("Succeed") && dataJson.getString("StatusString").equals("Succeed")) {
                    //  deviceInfo.setDeviceNo(newDeviceNo);
                    SysLog sysLog = new SysLog();
                    sysLog.setCreateTime(new Date());
                    sysLog.setData("ip:" + newAddress + ",port:" + newPort);
                    sysLog.setPointcut(deviceNo);
                    sysLog.setRemark("修改设备ip和端口");
                    sysLogService.insert(sysLog);
                    deviceInfo.setUpdateTime(new Date());
                    deviceInfoService.update(deviceInfo);
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    @Override
    public DataServersDTO getDeviceDateServer(String deviceNo) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线");
        }
        JSONObject jsonObject = lapiRequest.send(deviceNo, LApiConstant.DATASERVERS, HttpMethod.GET, null);
        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        String s = response.getString("DataServerList");
        List<DataServersDTO> dataServersDTOList = JSONObject.parseArray(s, DataServersDTO.class);
        if (dataServersDTOList.size() > 0) {
            for (DataServersDTO dataServersDTO : dataServersDTOList) {
                if (dataServersDTO.getEnabled() > 0) {
                    return dataServersDTO;
                }
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> getOpenDoorMode(String deviceInfoId) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }
        //JSONObject jsonObject = LApiUtil.getRequest(deviceInfo.getIpAddress() + ":" + deviceInfo.getPort() + LApiConstant.RULE);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.OPENDOORMODE, HttpMethod.GET, null);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        return response;
    }

    @Override
    public Boolean setOpenDoorMode(String deviceInfoId, String type) throws Exception {
        DeviceInfo deviceInfo = deviceInfoService.get(deviceInfoId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("Mode", type);
        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.OPENDOORMODE, HttpMethod.PUT, map);

        JSONObject dataJson = jsonObject.getJSONObject("Response");
        JSONObject response = LApiUtil.getResponse(dataJson);
        return true;
    }

    @Override
    public List<IsPersonExistVo> existPersonInDevice(List<Long> personIdList, DeviceInfo deviceInfo) throws Exception {
        //单位名称库id，方法内如果没有单位名称库则会返回默认员工库id
        String faceDbId = getFaceDbId(deviceInfo, deviceInfo.getCompanyName());

        if (StringUtils.isBlank(faceDbId)) {
            throw new Exception("人脸库不存在");
        }

        List<IsPersonExistVo> isPersonExistVoList = new ArrayList<>();

        //获取人脸库信息
        JSONObject jsonObject1 = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.ADDLIBRARY, HttpMethod.GET, null);
        JSONObject dataJson1 = jsonObject1.getJSONObject("Response");
        JSONObject response1 = LApiUtil.getResponse(dataJson1);
        String libList = response1.getString("LibList");
        List<LibDTO> libDTOList = JSONObject.parseArray(libList, LibDTO.class);
        Long personNum = 0L;
        if (libDTOList.size() > 0) {
            for (LibDTO libDTO : libDTOList) {
                if (libDTO.getId().equals(Long.valueOf(faceDbId))) {
                    personNum = libDTO.getPersonNum();
                    break;
                }
            }
        }
        //基准，单次查询的最大个数为1000->200
        int limit = 200;

        //获取人脸库中人员个数
        Integer num = Integer.parseInt(personNum.toString());

        limit = Math.min(num,limit);

        Integer totalPage = (int) Math.ceil((double) num / limit);
        Set<Long> existPersonSet = new HashSet<>();

        for (int i = 0; i < totalPage; i++) {
            HashMap map = new HashMap<>();
            map.put("Limit", limit);
            map.put("Offset", i * limit);

            JSONObject jsonObject2 = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.DELETELIBRARY + faceDbId + "/UpdateTime", HttpMethod.POST, map);
            JSONObject dataJson2 = jsonObject2.getJSONObject("Response");
            JSONObject response2 = LApiUtil.getResponse(dataJson2);
            String personList = response2.getString("PersonList");

            List<PersonDateDTO> personDateDTOList = JSONObject.parseArray(personList, PersonDateDTO.class);

            for (PersonDateDTO personDateDTO : personDateDTOList) {
                existPersonSet.add(personDateDTO.getPersonID());
            }
        }

        if (personIdList.size() > 0) {
            for (Long id : personIdList) {
                IsPersonExistVo isPersonExistVo = new IsPersonExistVo();
                isPersonExistVo.setPersonId(id);
                isPersonExistVo.setIsPersonExist(existPersonSet.contains(id));
                isPersonExistVoList.add(isPersonExistVo);
            }
        }

        return isPersonExistVoList;
    }

    @Override
    public void sendGUIShowInfo(String deviceNo,String personName, String passTime, int resultCode, String resultMsg) {
        HashMap<String, Object> map = new HashMap<>();
        List<Map> showInfoListMap = new ArrayList<>();
        Map<String, Object> showInfoMap1 = new HashMap<>();
        Map<String, Object> showInfoMap2 = new HashMap<>();

        map.put("ResultCode", resultCode);
        map.put("ResultMsg", resultMsg);
        map.put("PassTime", passTime);
        map.put("ShowInfoNum", 2);

        showInfoMap1.put("Key", "姓名:");
        showInfoMap1.put("Value", personName);
        showInfoListMap.add(showInfoMap1);

        showInfoMap2.put("Key", "状态:");
        showInfoMap2.put("Value", resultMsg);
        showInfoListMap.add(showInfoMap2);

        map.put("ShowInfoList", showInfoListMap);

        try {
            JSONObject jsonObject = lapiRequest.send(deviceNo, LApiConstant.GUIShowInfo, HttpMethod.PUT, map);
            log.warn(jsonObject.toString());
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    @Override
    public void setLongConnectionInfo(String deviceNo,int recordResponseEnable, int keepAliveInterval) {
        HashMap<String, Object> map = new HashMap<>();

        try {
            map.put("RecordResponseEnable", recordResponseEnable);
            map.put("KeepAliveInterval", keepAliveInterval);

            JSONObject jsonObject = lapiRequest.send(deviceNo, LApiConstant.LongConnectionInfo, HttpMethod.PUT, map);
            log.warn(jsonObject.toString());
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    @Override
    public JSONObject getPeopleLibPermission(String deviceId, String libId) throws Exception{
        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }

        JSONObject jsonObject = lapiRequest.send(deviceInfo.getDeviceNo(), LApiConstant.PEOPLE_LIBRARIES + libId + "/PermissionInfo", HttpMethod.GET, null);

        return jsonObject;
    }

    @Override
    public JSONObject setPeopleLibPermission(String deviceId, String libId, JSONObject requestBody) throws Exception{
        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }

        if (!deviceInfo.getIsOnline()) {
            throw new Exception("设备离线，请联系管理员");
        }

        JSONObject responseBody = lapiRequest.sendJson(deviceInfo.getDeviceNo(), LApiConstant.PEOPLE_LIBRARIES + libId + "/PermissionInfo", HttpMethod.PUT, requestBody);

        return responseBody;
    }
}
